1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3 1999, 2000, 2001 Free Software Foundation, Inc.
4 Written by Per Bothner, 1994.
5 Based on CCCP program by Paul Rubin, June 1986
6 Adapted to ANSI C, Richard Stallman, Jan 1987
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 In other words, you are welcome to use, share and improve this program.
23 You are forbidden to forbid anyone else to use, share and improve
24 what you give them. Help stamp out software-hoarding! */
28 #include "intl.h" /* for _("<command line>") below. */
34 cpp_hashnode **params; /* Parameters, if any. */
35 cpp_token *expansion; /* First token of replacement list. */
36 unsigned int line; /* Starting line number. */
37 unsigned int count; /* Number of tokens in expansion. */
38 unsigned short paramc; /* Number of parameters. */
39 unsigned int fun_like : 1; /* If a function-like macro. */
40 unsigned int variadic : 1; /* If a variadic macro. */
41 unsigned int disabled : 1; /* If macro is disabled. */
42 unsigned int syshdr : 1; /* If macro defined in system header. */
45 typedef struct macro_arg macro_arg;
48 cpp_token *first; /* First token in unexpanded argument. */
49 cpp_token *expanded; /* Macro-expanded argument. */
50 cpp_token *stringified; /* Stringified argument. */
51 unsigned int count; /* # of tokens in argument. */
52 unsigned int expanded_count; /* # of tokens in expanded argument. */
55 /* Macro expansion. */
57 static void lock_pools PARAMS ((cpp_reader *));
58 static void unlock_pools PARAMS ((cpp_reader *));
59 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
60 static void builtin_macro PARAMS ((cpp_reader *, cpp_token *));
61 static cpp_context *push_arg_context PARAMS ((cpp_reader *, macro_arg *));
62 static enum cpp_ttype parse_arg PARAMS ((cpp_reader *, macro_arg *, int));
63 static macro_arg *parse_args PARAMS ((cpp_reader *, const cpp_hashnode *));
64 static cpp_context *next_context PARAMS ((cpp_reader *));
65 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
66 static unsigned char *quote_string PARAMS ((unsigned char *,
67 const unsigned char *,
69 static void make_string_token PARAMS ((cpp_pool *, cpp_token *,
70 const U_CHAR *, unsigned int));
71 static void make_number_token PARAMS ((cpp_reader *, cpp_token *, int));
72 static void stringify_arg PARAMS ((cpp_reader *, macro_arg *));
73 static void paste_all_tokens PARAMS ((cpp_reader *, cpp_token *));
74 static int paste_tokens PARAMS ((cpp_reader *, cpp_token *, cpp_token *));
75 static int funlike_invocation_p PARAMS ((cpp_reader *, const cpp_hashnode *,
77 static void replace_args PARAMS ((cpp_reader *, cpp_macro *, macro_arg *,
80 /* #define directive parsing and handling. */
82 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
83 static int warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
85 static int save_parameter PARAMS ((cpp_reader *, cpp_macro *, cpp_hashnode *));
86 static int parse_params PARAMS ((cpp_reader *, cpp_macro *));
87 static void check_trad_stringification PARAMS ((cpp_reader *,
91 /* Allocates a buffer to hold a token's TEXT, and converts TOKEN to a
92 CPP_STRING token containing TEXT in quoted form. */
94 make_string_token (pool, token, text, len)
100 U_CHAR *buf = _cpp_pool_alloc (pool, len * 4 + 1);
102 token->type = CPP_STRING;
103 token->val.str.text = buf;
104 token->val.str.len = quote_string (buf, text, len) - buf;
105 buf[token->val.str.len] = '\0';
109 /* Allocates and converts a temporary token to a CPP_NUMBER token,
110 evaluating to NUMBER. */
112 make_number_token (pfile, token, number)
117 unsigned char *buf = _cpp_pool_alloc (&pfile->ident_pool, 20);
119 sprintf ((char *) buf, "%d", number);
120 token->type = CPP_NUMBER;
121 token->val.str.text = buf;
122 token->val.str.len = ustrlen (buf);
126 static const char * const monthnames[] =
128 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
129 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
132 /* Handle builtin macros like __FILE__. */
134 builtin_macro (pfile, token)
138 unsigned char flags = ((token->flags & (PREV_WHITE | BOL)) | AVOID_LPASTE);
139 cpp_hashnode *node = token->val.node;
141 switch (node->value.builtin)
147 const struct line_map *map = pfile->map;
149 if (node->value.builtin == BT_BASE_FILE)
150 while (! MAIN_FILE_P (map))
151 map = INCLUDED_FROM (&pfile->line_maps, map);
154 make_string_token (&pfile->ident_pool, token,
155 (const unsigned char *) name, strlen (name));
159 case BT_INCLUDE_LEVEL:
160 /* The line map depth counts the primary source as level 1, but
161 historically __INCLUDE_DEPTH__ has called the primary source
163 make_number_token (pfile, token, pfile->line_maps.depth - 1);
167 /* If __LINE__ is embedded in a macro, it must expand to the
168 line of the macro's invocation, not its definition.
169 Otherwise things like assert() will not work properly. */
170 make_number_token (pfile, token,
171 SOURCE_LINE (pfile->map, pfile->cur_token[-1].line));
176 int stdc = (!CPP_IN_SYSTEM_HEADER (pfile)
177 || pfile->spec_nodes.n__STRICT_ANSI__->type != NT_VOID);
178 make_number_token (pfile, token, stdc);
184 if (pfile->date.type == CPP_EOF)
186 /* Allocate __DATE__ and __TIME__ from permanent storage,
187 and save them in pfile so we don't have to do this again.
188 We don't generate these strings at init time because
189 time() and localtime() are very slow on some systems. */
190 time_t tt = time (NULL);
191 struct tm *tb = localtime (&tt);
193 make_string_token (&pfile->ident_pool, &pfile->date,
195 make_string_token (&pfile->ident_pool, &pfile->time,
198 sprintf ((char *) pfile->date.val.str.text, "%s %2d %4d",
199 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
200 sprintf ((char *) pfile->time.val.str.text, "%02d:%02d:%02d",
201 tb->tm_hour, tb->tm_min, tb->tm_sec);
203 *token = node->value.builtin == BT_DATE ? pfile->date: pfile->time;
207 cpp_ice (pfile, "invalid builtin macro \"%s\"", NODE_NAME (node));
211 token->flags = flags;
218 _cpp_lock_pool (&pfile->argument_pool);
225 _cpp_unlock_pool (&pfile->argument_pool);
228 /* Adds backslashes before all backslashes and double quotes appearing
229 in strings. Non-printable characters are converted to octal. */
231 quote_string (dest, src, len)
240 if (c == '\\' || c == '"')
251 sprintf ((char *) dest, "\\%03o", c);
260 /* Convert a token sequence to a single string token according to the
261 rules of the ISO C #-operator. */
263 stringify_arg (pfile, arg)
267 cpp_pool *pool = &pfile->ident_pool;
268 unsigned char *start = POOL_FRONT (pool);
269 unsigned int i, escape_it, total_len = 0, backslash_count = 0;
271 /* Loop, reading in the argument's tokens. */
272 for (i = 0; i < arg->count; i++)
275 const cpp_token *token = &arg->first[i];
276 unsigned int len = cpp_token_len (token);
278 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
279 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
282 /* Worst case is each char is octal. */
284 len += 2; /* Room for initial space and final NUL. */
286 dest = &start[total_len];
287 if (dest + len > POOL_LIMIT (pool))
289 _cpp_next_chunk (pool, len, (unsigned char **) &start);
290 dest = &start[total_len];
293 /* No leading white space. */
294 if (token->flags & PREV_WHITE && total_len > 0)
299 unsigned char *buf = (unsigned char *) xmalloc (len);
301 len = cpp_spell_token (pfile, token, buf) - buf;
302 dest = quote_string (dest, buf, len);
306 dest = cpp_spell_token (pfile, token, dest);
307 total_len = dest - start;
309 if (token->type == CPP_OTHER && token->val.c == '\\')
315 /* Ignore the final \ of invalid string literals. */
316 if (backslash_count & 1)
318 cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
322 /* Null terminate, and commit the memory. */
323 start[total_len] = '\0';
324 POOL_COMMIT (pool, total_len + 1);
326 arg->stringified = xnew (cpp_token);
327 arg->stringified->flags = 0;
328 arg->stringified->type = CPP_STRING;
329 arg->stringified->val.str.text = start;
330 arg->stringified->val.str.len = total_len;
333 /* Try to paste two tokens. On success, the LHS becomes the pasted
334 token, and 0 is returned. For failure, we update the flags of the
335 RHS appropriately and return non-zero. */
337 paste_tokens (pfile, lhs, rhs)
339 cpp_token *lhs, *rhs;
345 type = cpp_can_paste (pfile, lhs, rhs, &digraph);
349 /* Mandatory warning for all apart from assembler. */
350 if (CPP_OPTION (pfile, lang) != CLK_ASM)
352 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
353 cpp_token_as_text (pfile, lhs),
354 cpp_token_as_text (pfile, rhs));
356 /* The standard states that behaviour is undefined. By the
357 principle of least surpise, we step back before the RHS, and
358 mark it to prevent macro expansion. Tests in the testsuite
359 rely on clearing PREV_WHITE here, though you could argue we
360 should actually set it. Assembler can have '.' in labels and
361 so requires that we don't insert spaces there. Maybe we should
362 change this to put out a space unless it's assembler. */
363 rhs->flags &= ~PREV_WHITE;
364 rhs->flags |= NO_EXPAND;
368 flags = lhs->flags & ~DIGRAPH;
372 /* Identifiers and numbers need spellings to be pasted. */
373 if (type == CPP_NAME || type == CPP_NUMBER)
375 unsigned int total_len = cpp_token_len (lhs) + cpp_token_len (rhs);
376 unsigned char *result, *end;
378 result = _cpp_pool_alloc (&pfile->ident_pool, total_len + 1);
380 /* Paste the spellings and null terminate. */
381 end = cpp_spell_token (pfile, rhs, cpp_spell_token (pfile, lhs, result));
383 total_len = end - result;
385 if (type == CPP_NAME)
387 lhs->val.node = cpp_lookup (pfile, result, total_len);
388 if (lhs->val.node->flags & NODE_OPERATOR)
391 lhs->type = lhs->val.node->value.operator;
396 lhs->val.str.text = result;
397 lhs->val.str.len = total_len;
400 else if (type == CPP_WCHAR || type == CPP_WSTRING)
401 lhs->val.str = rhs->val.str;
403 /* Set type and flags after pasting spellings. */
410 /* Handles an arbitrarily long sequence of ## operators. This
411 implementation is left-associative, non-recursive, and finishes a
412 paste before handling succeeding ones. If the paste fails, we back
413 up a token to just after the ## operator, with the effect that it
414 appears in the output stream normally. */
416 paste_all_tokens (pfile, lhs)
421 unsigned char orig_flags = lhs->flags;
425 /* Take the token directly from the current context. We can do
426 this, because we are in the replacement list of either an
427 object-like macro, or a function-like macro with arguments
428 inserted. In either case, the constraints to #define
429 guarantee we have at least one more token. */
430 rhs = pfile->context->list.first++;
431 if (paste_tokens (pfile, lhs, rhs))
433 /* We failed. Step back so we read the RHS in next. */
434 pfile->context->list.first--;
438 while (rhs->flags & PASTE_LEFT);
440 /* The pasted token has the PREV_WHITE flag of the LHS, is no longer
441 PASTE_LEFT, and is subject to macro expansion. */
442 lhs->flags &= ~(PREV_WHITE | BOL | PASTE_LEFT | NO_EXPAND);
443 lhs->flags |= orig_flags & (PREV_WHITE | BOL | AVOID_LPASTE);
446 /* Reads the unexpanded tokens of a macro argument into ARG. VAR_ARGS
447 is non-zero if this is a variadic macro. Returns the type of the
448 token that caused reading to finish. */
449 static enum cpp_ttype
450 parse_arg (pfile, arg, variadic)
452 struct macro_arg *arg;
455 enum cpp_ttype result;
456 unsigned int paren = 0;
459 arg->first = (cpp_token *) POOL_FRONT (&pfile->argument_pool);
460 for (;; arg->count++)
462 cpp_token *token = &arg->first[arg->count];
463 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->argument_pool))
465 _cpp_next_chunk (&pfile->argument_pool, sizeof (cpp_token),
466 (unsigned char **) &arg->first);
467 token = &arg->first[arg->count];
470 /* Newlines in arguments are white space (6.10.3.10). */
472 cpp_get_token (pfile, token);
474 if (line != pfile->line)
475 token->flags |= PREV_WHITE;
477 result = token->type;
479 if (result == CPP_OPEN_PAREN)
481 else if (result == CPP_CLOSE_PAREN && paren-- == 0)
483 /* Commas are not terminators within parantheses or variadic. */
484 else if (result == CPP_COMMA && paren == 0 && !variadic)
486 else if (result == CPP_EOF)
488 /* We still need the EOF (added below) to end pre-expansion
490 if (pfile->context->prev || pfile->state.in_directive)
491 _cpp_backup_tokens (pfile, 1);
492 /* Error reported by caller. */
495 else if (result == CPP_HASH && token->flags & BOL)
497 /* 6.10.3 paragraph 11: If there are sequences of
498 preprocessing tokens within the list of arguments that
499 would otherwise act as preprocessing directives, the
500 behavior is undefined.
502 This implementation will report a hard error, terminate
503 the macro invocation, and proceed to process the
506 "directives may not be used inside a macro argument");
507 _cpp_backup_tokens (pfile, 1);
513 /* Commit the memory used to store the arguments. We make the last
514 argument a CPP_EOF, so that it terminates macro pre-expansion,
515 but it is not included in arg->count. */
516 arg->first[arg->count].type = CPP_EOF;
517 POOL_COMMIT (&pfile->argument_pool, (arg->count + 1) * sizeof (cpp_token));
522 /* Parse the arguments making up a macro invocation. */
524 parse_args (pfile, node)
526 const cpp_hashnode *node;
528 cpp_macro *macro = node->value.macro;
529 macro_arg *args, *cur;
533 /* Allocate room for at least one argument, and zero it out. */
534 argc = macro->paramc ? macro->paramc: 1;
535 args = xcnewvec (macro_arg, argc);
537 for (cur = args, argc = 0; ;)
541 type = parse_arg (pfile, cur, argc == macro->paramc && macro->variadic);
542 if (type == CPP_CLOSE_PAREN || type == CPP_EOF)
545 /* Re-use the last argument for excess arguments. */
546 if (argc < macro->paramc)
552 cpp_error (pfile, "unterminated argument list invoking macro \"%s\"",
556 else if (argc < macro->paramc)
558 /* As an extension, a rest argument is allowed to not appear in
559 the invocation at all.
560 e.g. #define debug(format, args...) something
563 This is exactly the same as if there had been an empty rest
564 argument - debug("string", ). */
566 if (argc + 1 == macro->paramc && macro->variadic)
568 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
569 cpp_pedwarn (pfile, "ISO C99 requires rest arguments to be used");
574 "macro \"%s\" requires %u arguments, but only %u given",
575 NODE_NAME (node), macro->paramc, argc);
579 else if (argc > macro->paramc)
581 /* Empty argument to a macro taking no arguments is OK. */
582 if (argc != 1 || cur->count)
585 "macro \"%s\" passed %u arguments, but takes just %u",
586 NODE_NAME (node), argc, macro->paramc);
601 funlike_invocation_p (pfile, node, list)
603 const cpp_hashnode *node;
604 struct toklist *list;
606 cpp_token maybe_paren;
609 pfile->state.parsing_args = 1;
610 pfile->state.prevent_expansion++;
612 pfile->keep_tokens++;
613 cpp_get_token (pfile, &maybe_paren);
614 pfile->state.parsing_args = 2;
616 if (maybe_paren.type == CPP_OPEN_PAREN)
617 args = parse_args (pfile, node);
620 _cpp_backup_tokens (pfile, 1);
621 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
623 "function-like macro \"%s\" must be used with arguments in traditional C",
627 pfile->state.prevent_expansion--;
628 pfile->state.parsing_args = 0;
629 pfile->keep_tokens--;
633 if (node->value.macro->paramc > 0)
634 replace_args (pfile, node->value.macro, args, list);
641 /* Push the context of a macro onto the context stack. TOKEN is the
642 macro name. If we can successfully start expanding the macro,
643 TOKEN is replaced with the first token of the expansion, and we
646 enter_macro_context (pfile, node)
650 cpp_context *context;
651 cpp_macro *macro = node->value.macro;
654 /* Save the position of the outermost macro invocation. */
655 if (!pfile->context->prev)
658 if (macro->fun_like && !funlike_invocation_p (pfile, node, &list))
660 if (!pfile->context->prev)
661 unlock_pools (pfile);
665 if (macro->paramc == 0)
667 list.first = macro->expansion;
668 list.limit = macro->expansion + macro->count;
671 context = next_context (pfile);
672 context->list = list;
673 context->macro = macro;
675 /* Disable the macro within its expansion. */
681 /* Move to the next context. Create one if there is none. */
686 cpp_context *prev = pfile->context;
687 cpp_context *result = prev->next;
691 result = xnew (cpp_context);
697 pfile->context = result;
702 replace_args (pfile, macro, args, list)
706 struct toklist *list;
708 unsigned char flags = 0;
709 unsigned int i, total;
710 const cpp_token *src, *limit;
714 src = macro->expansion;
715 limit = src + macro->count;
717 /* First, fully macro-expand arguments, calculating the number of
718 tokens in the final expansion as we go. This ensures that the
719 possible recursive use of argument_pool is fine. */
721 for (; src < limit; src++)
722 if (src->type == CPP_MACRO_ARG)
724 /* We have an argument. If it is not being stringified or
725 pasted it is macro-replaced before insertion. */
726 arg = &args[src->val.arg_no - 1];
728 if (src->flags & STRINGIFY_ARG)
730 if (!arg->stringified)
731 stringify_arg (pfile, arg);
733 else if ((src->flags & PASTE_LEFT)
734 || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
735 total += arg->count - 1;
740 arg->expanded_count = 0;
742 expand_arg (pfile, arg);
744 total += arg->expanded_count - 1;
748 dest = (cpp_token *) _cpp_pool_alloc (&pfile->argument_pool,
749 total * sizeof (cpp_token));
752 for (src = macro->expansion; src < limit; src++)
753 if (src->type == CPP_MACRO_ARG)
756 const cpp_token *from;
758 arg = &args[src->val.arg_no - 1];
759 if (src->flags & STRINGIFY_ARG)
761 from = arg->stringified, count = 1;
762 /* Ugh. Maintain position of original argument. */
763 arg->stringified->line = src->line;
764 arg->stringified->col = src->col;
766 else if (src->flags & PASTE_LEFT)
767 count = arg->count, from = arg->first;
768 else if (src > macro->expansion && (src[-1].flags & PASTE_LEFT))
770 count = arg->count, from = arg->first;
771 if (dest != list->first)
773 /* GCC has special semantics for , ## b where b is a
774 varargs parameter: the comma disappears if b was
775 given no actual arguments (not merely if b is an
776 empty argument); otherwise pasting is turned off. */
777 if (dest[-1].type == CPP_COMMA
779 && src->val.arg_no == macro->paramc)
784 dest[-1].flags &= ~PASTE_LEFT;
786 /* Count == 0 is the RHS a placemarker case. */
788 dest[-1].flags &= ~PASTE_LEFT;
792 count = arg->expanded_count, from = arg->expanded;
794 /* Count == 0 is the LHS a placemarker case. */
797 memcpy (dest, from, count * sizeof (cpp_token));
799 /* The first token gets PREV_WHITE of the CPP_MACRO_ARG. */
800 dest->flags &= ~(PREV_WHITE | BOL);
801 dest->flags |= src->flags & (PREV_WHITE | BOL);
802 dest->flags |= AVOID_LPASTE;
804 /* The last token gets the PASTE_LEFT of the CPP_MACRO_ARG. */
805 dest[count - 1].flags |= src->flags & PASTE_LEFT;
810 /* The token after the argument must avoid an accidental paste. */
811 flags = AVOID_LPASTE;
816 dest->flags |= flags;
823 /* Free the expanded arguments. */
824 for (i = 0; i < macro->paramc; i++)
826 if (args[i].expanded)
827 free (args[i].expanded);
828 if (args[i].stringified)
829 free (args[i].stringified);
833 /* Subroutine of expand_arg to put the unexpanded tokens on the
836 push_arg_context (pfile, arg)
840 cpp_context *context = next_context (pfile);
842 context->list.first = arg->first;
843 context->list.limit = arg->first + arg->count + 1;
849 expand_arg (pfile, arg)
854 unsigned int capacity = 256;
856 /* Loop, reading in the arguments. */
857 arg->expanded = (cpp_token *) xmalloc (capacity * sizeof (cpp_token));
859 push_arg_context (pfile, arg);
862 if (arg->expanded_count >= capacity)
865 arg->expanded = (cpp_token *)
866 xrealloc (arg->expanded, capacity * sizeof (cpp_token));
868 token = &arg->expanded[arg->expanded_count++];
869 cpp_get_token (pfile, token);
871 while (token->type != CPP_EOF);
873 arg->expanded_count--;
875 /* Pop the context we pushed. */
876 pfile->context = pfile->context->prev;
880 _cpp_pop_context (pfile)
883 cpp_context *context = pfile->context;
885 pfile->context = context->prev;
886 if (!pfile->context->prev && !pfile->state.parsing_args)
887 unlock_pools (pfile);
889 /* Re-enable a macro when leaving its expansion. */
890 context->macro->disabled = 0;
893 /* Eternal routine to get a token. Also used nearly everywhere
894 internally, except for places where we know we can safely call
895 the lexer directly, such as lexing a directive name.
897 Macro expansions and directives are transparently handled,
898 including entering included files. Thus tokens are post-macro
899 expansion, and after any intervening directives. External callers
900 see CPP_EOF only at EOF. Internal callers also see it when meeting
901 a directive inside a macro call, when at the end of a directive and
902 state.in_directive is still 1, and at the end of argument
905 cpp_get_token (pfile, token)
911 cpp_context *context = pfile->context;
913 /* Context->prev == 0 <=> base context. */
915 *token = *_cpp_lex_token (pfile);
916 else if (context->list.first != context->list.limit)
918 *token = *context->list.first++;
919 token->flags |= pfile->buffer->saved_flags;
920 pfile->buffer->saved_flags = 0;
921 /* PASTE_LEFT tokens can only appear in macro expansions. */
922 if (token->flags & PASTE_LEFT)
924 /* Maintains position of original token. */
925 paste_all_tokens (pfile, token);
926 pfile->buffer->saved_flags = AVOID_LPASTE;
932 cpp_ice (pfile, "context->macro == 0");
934 /* Avoid accidental paste at the end of a macro. */
935 pfile->buffer->saved_flags |= AVOID_LPASTE;
936 _cpp_pop_context (pfile);
940 if (token->type != CPP_NAME)
943 /* Handle macros and the _Pragma operator. */
944 if (token->val.node->type == NT_MACRO
945 && !pfile->state.prevent_expansion
946 && !(token->flags & NO_EXPAND))
948 cpp_hashnode *node = token->val.node;
950 /* Macros invalidate controlling macros. */
951 pfile->mi_valid = false;
953 if (node->flags & NODE_BUILTIN)
955 /* Maintains position of original token. */
956 builtin_macro (pfile, token);
957 pfile->buffer->saved_flags = AVOID_LPASTE;
961 if (node->value.macro->disabled)
962 token->flags |= NO_EXPAND;
963 else if (enter_macro_context (pfile, node))
965 /* Pass AVOID_LPASTE and our PREV_WHITE to next token. */
966 pfile->buffer->saved_flags = ((token->flags & (PREV_WHITE | BOL))
972 /* Don't interpret _Pragma within directives. The standard is
973 not clear on this, but to me this makes most sense. */
974 if (token->val.node != pfile->spec_nodes.n__Pragma
975 || pfile->state.in_directive)
978 /* Handle it, and loop back for another token. MI is cleared
979 since this token came from either the lexer or a macro. */
980 _cpp_do__Pragma (pfile);
984 /* Returns true if we're expanding an object-like macro that was
985 defined in a system header. Just checks the macro at the top of
986 the stack. Used for diagnostic suppression. */
988 cpp_sys_macro_p (pfile)
991 cpp_macro *macro = pfile->context->macro;
993 return macro && macro->syshdr;
996 /* Read each token in, until EOF. Directives are transparently
999 cpp_scan_nooutput (pfile)
1005 cpp_get_token (pfile, &token);
1006 while (token.type != CPP_EOF);
1009 /* Step back one (or more) tokens. Can only step mack more than 1 if
1010 they are from the lexer, and not from macro expansion. */
1012 _cpp_backup_tokens (pfile, count)
1016 if (pfile->context->prev == NULL)
1018 pfile->lookaheads += count;
1022 if (pfile->cur_token == pfile->cur_run->base)
1024 pfile->cur_run = pfile->cur_run->prev;
1025 pfile->cur_token = pfile->cur_run->limit;
1033 pfile->context->list.first--;
1037 /* #define directive parsing and handling. */
1039 /* Returns non-zero if a macro redefinition warning is required. */
1041 warn_of_redefinition (pfile, node, macro2)
1043 const cpp_hashnode *node;
1044 const cpp_macro *macro2;
1046 const cpp_macro *macro1;
1049 /* Some redefinitions need to be warned about regardless. */
1050 if (node->flags & NODE_WARN)
1053 if (! CPP_PEDANTIC (pfile))
1056 /* Redefinition of a macro is allowed if and only if the old and new
1057 definitions are the same. (6.10.3 paragraph 2). */
1058 macro1 = node->value.macro;
1060 /* The quick failures. */
1061 if (macro1->count != macro2->count
1062 || macro1->paramc != macro2->paramc
1063 || macro1->fun_like != macro2->fun_like
1064 || macro1->variadic != macro2->variadic)
1067 /* Check each token. */
1068 for (i = 0; i < macro1->count; i++)
1069 if (! _cpp_equiv_tokens (¯o1->expansion[i], ¯o2->expansion[i]))
1072 /* Check parameter spellings. */
1073 for (i = 0; i < macro1->paramc; i++)
1074 if (macro1->params[i] != macro2->params[i])
1080 /* Free the definition of hashnode H. */
1083 _cpp_free_definition (h)
1086 /* Macros and assertions no longer have anything to free. */
1088 /* Clear builtin flag in case of redefinition. */
1089 h->flags &= ~NODE_BUILTIN;
1093 save_parameter (pfile, macro, node)
1098 cpp_hashnode **dest;
1100 /* Constraint 6.10.3.6 - duplicate parameter names. */
1101 if (node->arg_index)
1103 cpp_error (pfile, "duplicate macro parameter \"%s\"", NODE_NAME (node));
1107 dest = ¯o->params[macro->paramc];
1109 /* Check we have room for the parameters. */
1110 if ((unsigned char *) (dest + 1) >= POOL_LIMIT (&pfile->macro_pool))
1112 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_hashnode *),
1113 (unsigned char **) ¯o->params);
1114 dest = ¯o->params[macro->paramc];
1118 node->arg_index = ++macro->paramc;
1123 parse_params (pfile, macro)
1127 unsigned int prev_ident = 0;
1129 macro->params = (cpp_hashnode **) POOL_FRONT (&pfile->macro_pool);
1132 const cpp_token *token = _cpp_lex_token (pfile);
1134 switch (token->type)
1137 cpp_error (pfile, "\"%s\" may not appear in macro parameter list",
1138 cpp_token_as_text (pfile, token));
1144 cpp_error (pfile, "macro parameters must be comma-separated");
1149 if (save_parameter (pfile, macro, token->val.node))
1153 case CPP_CLOSE_PAREN:
1154 if (prev_ident || macro->paramc == 0)
1157 /* Fall through to pick up the error. */
1161 cpp_error (pfile, "parameter name missing");
1168 macro->variadic = 1;
1171 save_parameter (pfile, macro, pfile->spec_nodes.n__VA_ARGS__);
1172 pfile->state.va_args_ok = 1;
1173 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1175 "anonymous variadic macros were introduced in C99");
1177 else if (CPP_OPTION (pfile, pedantic))
1178 cpp_pedwarn (pfile, "ISO C does not permit named variadic macros");
1180 /* We're at the end, and just expect a closing parenthesis. */
1181 token = _cpp_lex_token (pfile);
1182 if (token->type == CPP_CLOSE_PAREN)
1187 cpp_error (pfile, "missing ')' in macro parameter list");
1191 /* Success. Commit the parameter array. */
1192 POOL_COMMIT (&pfile->macro_pool,
1193 macro->paramc * sizeof (cpp_hashnode *));
1198 /* Lex a token from a macro's replacement list. Translate it to a
1199 CPP_MACRO_ARG if appropriate. */
1201 lex_expansion_token (pfile, macro)
1205 cpp_token *token = ¯o->expansion[macro->count];
1207 /* Check we have room for the token. */
1208 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->macro_pool))
1210 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_token),
1211 (unsigned char **) ¯o->expansion);
1212 token = ¯o->expansion[macro->count];
1216 *token = *_cpp_lex_token (pfile);
1218 /* Is this an argument? */
1219 if (token->type == CPP_NAME && token->val.node->arg_index)
1221 token->type = CPP_MACRO_ARG;
1222 token->val.arg_no = token->val.node->arg_index;
1224 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1225 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1226 check_trad_stringification (pfile, macro, &token->val.str);
1231 /* Parse a macro and save its expansion. Returns non-zero on success. */
1233 _cpp_create_definition (pfile, node)
1239 unsigned int i, ok = 1;
1241 macro = (cpp_macro *) _cpp_pool_alloc (&pfile->macro_pool,
1242 sizeof (cpp_macro));
1243 macro->line = pfile->directive_line;
1246 macro->fun_like = 0;
1247 macro->variadic = 0;
1249 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1251 /* Get the first token of the expansion (or the '(' of a
1252 function-like macro). */
1253 token = lex_expansion_token (pfile, macro);
1254 if (token->type == CPP_OPEN_PAREN && !(token->flags & PREV_WHITE))
1256 if (!(ok = parse_params (pfile, macro)))
1259 macro->fun_like = 1;
1260 /* Some of the pool may have been used for the parameter store. */
1261 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1262 token = lex_expansion_token (pfile, macro);
1264 else if (token->type != CPP_EOF && !(token->flags & PREV_WHITE))
1265 cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
1267 /* Setting it here means we don't catch leading comments. */
1268 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
1272 /* Check the stringifying # constraint 6.10.3.2.1 of
1273 function-like macros when lexing the subsequent token. */
1274 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1276 if (token->type == CPP_MACRO_ARG)
1278 token->flags &= ~PREV_WHITE;
1279 token->flags |= STRINGIFY_ARG;
1280 token->flags |= token[-1].flags & PREV_WHITE;
1281 token[-1] = token[0];
1284 /* Let assembler get away with murder. */
1285 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1288 cpp_error (pfile, "'#' is not followed by a macro parameter");
1293 if (token->type == CPP_EOF)
1296 /* Paste operator constraint 6.10.3.3.1. */
1297 if (token->type == CPP_PASTE)
1299 /* Token-paste ##, can appear in both object-like and
1300 function-like macros, but not at the ends. */
1301 if (--macro->count > 0)
1302 token = lex_expansion_token (pfile, macro);
1304 if (macro->count == 0 || token->type == CPP_EOF)
1308 "'##' cannot appear at either end of a macro expansion");
1312 token[-1].flags |= PASTE_LEFT;
1313 /* Give it a PREV_WHITE for -dM etc. */
1314 token->flags |= PREV_WHITE;
1317 token = lex_expansion_token (pfile, macro);
1320 /* Don't count the CPP_EOF. */
1323 /* Clear the whitespace flag from the leading token, but put a space
1324 in front of a leading # which might be used to fake a directive. */
1325 if (macro->expansion[0].type == CPP_HASH)
1326 macro->expansion[0].flags |= PREV_WHITE;
1328 macro->expansion[0].flags &= ~PREV_WHITE;
1330 /* Implement the macro-defined-to-itself optimisation. */
1331 macro->disabled = (macro->count == 1 && !macro->fun_like
1332 && macro->expansion[0].type == CPP_NAME
1333 && macro->expansion[0].val.node == node);
1335 /* To suppress some diagnostics. */
1336 macro->syshdr = pfile->map->sysp != 0;
1338 /* Commit the memory. */
1339 POOL_COMMIT (&pfile->macro_pool, macro->count * sizeof (cpp_token));
1341 if (node->type != NT_VOID)
1343 if (warn_of_redefinition (pfile, node, macro))
1345 cpp_pedwarn_with_line (pfile, pfile->directive_line, 0,
1346 "\"%s\" redefined", NODE_NAME (node));
1348 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1349 cpp_pedwarn_with_line (pfile, node->value.macro->line, 1,
1350 "this is the location of the previous definition");
1352 _cpp_free_definition (node);
1355 /* Enter definition in hash table. */
1356 node->type = NT_MACRO;
1357 node->value.macro = macro;
1358 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1359 node->flags |= NODE_WARN;
1363 /* Stop the lexer accepting __VA_ARGS__. */
1364 pfile->state.va_args_ok = 0;
1366 /* Clear the fast argument lookup indices. */
1367 for (i = macro->paramc; i-- > 0; )
1368 macro->params[i]->arg_index = 0;
1373 /* Warn if a token in `string' matches one of the function macro
1374 arguments in `info'. This function assumes that the macro is a
1375 function macro and not an object macro. */
1377 check_trad_stringification (pfile, macro, string)
1379 const cpp_macro *macro;
1380 const cpp_string *string;
1382 unsigned int i, len;
1383 const U_CHAR *p, *q, *limit = string->text + string->len;
1385 /* Loop over the string. */
1386 for (p = string->text; p < limit; p = q)
1388 /* Find the start of an identifier. */
1389 while (p < limit && !is_idstart (*p))
1392 /* Find the end of the identifier. */
1394 while (q < limit && is_idchar (*q))
1399 /* Loop over the function macro arguments to see if the
1400 identifier inside the string matches one of them. */
1401 for (i = 0; i < macro->paramc; i++)
1403 const cpp_hashnode *node = macro->params[i];
1405 if (NODE_LEN (node) == len
1406 && !memcmp (p, NODE_NAME (node), len))
1409 "macro argument \"%s\" would be stringified with -traditional.",
1417 /* Returns the name, arguments and expansion of a macro, in a format
1418 suitable to be read back in again, and therefore also for DWARF 2
1419 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1420 Caller is expected to generate the "#define" bit if needed. The
1421 returned text is temporary, and automatically freed later. */
1423 const unsigned char *
1424 cpp_macro_definition (pfile, node)
1426 const cpp_hashnode *node;
1428 unsigned int i, len;
1429 const cpp_macro *macro = node->value.macro;
1430 unsigned char *buffer;
1432 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1434 cpp_ice (pfile, "invalid hash type %d in cpp_macro_definition", node->type);
1438 /* Calculate length. */
1439 len = NODE_LEN (node) + 1; /* ' ' */
1440 if (macro->fun_like)
1442 len += 3; /* "()" plus possible final "." of named
1443 varargs (we have + 2 below). */
1444 for (i = 0; i < macro->paramc; i++)
1445 len += NODE_LEN (macro->params[i]) + 2; /* ", " */
1448 for (i = 0; i < macro->count; i++)
1450 cpp_token *token = ¯o->expansion[i];
1452 if (token->type == CPP_MACRO_ARG)
1453 len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1455 len += cpp_token_len (token); /* Includes room for ' '. */
1456 if (token->flags & STRINGIFY_ARG)
1458 if (token->flags & PASTE_LEFT)
1459 len += 3; /* " ##" */
1462 if (len > pfile->macro_buffer_len)
1464 pfile->macro_buffer = (U_CHAR *) xrealloc (pfile->macro_buffer, len);
1465 pfile->macro_buffer_len = len;
1468 /* Fill in the buffer. Start with the macro name. */
1469 buffer = pfile->macro_buffer;
1470 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1471 buffer += NODE_LEN (node);
1473 /* Parameter names. */
1474 if (macro->fun_like)
1477 for (i = 0; i < macro->paramc; i++)
1479 cpp_hashnode *param = macro->params[i];
1481 if (param != pfile->spec_nodes.n__VA_ARGS__)
1483 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1484 buffer += NODE_LEN (param);
1487 if (i + 1 < macro->paramc)
1488 *buffer++ = ',', *buffer++ = ' ';
1489 else if (macro->variadic)
1490 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1495 /* Expansion tokens. */
1499 for (i = 0; i < macro->count; i++)
1501 cpp_token *token = ¯o->expansion[i];
1503 if (token->flags & PREV_WHITE)
1505 if (token->flags & STRINGIFY_ARG)
1508 if (token->type == CPP_MACRO_ARG)
1510 len = NODE_LEN (macro->params[token->val.arg_no - 1]);
1512 NODE_NAME (macro->params[token->val.arg_no - 1]), len);
1516 buffer = cpp_spell_token (pfile, token, buffer);
1518 if (token->flags & PASTE_LEFT)
1523 /* Next has PREV_WHITE; see _cpp_create_definition. */
1529 return pfile->macro_buffer;