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 const cpp_token **first; /* First token in unexpanded argument. */
49 const cpp_token **expanded; /* Macro-expanded argument. */
50 const 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 int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
58 static const cpp_token *builtin_macro PARAMS ((cpp_reader *, cpp_hashnode *));
59 static void push_token_context
60 PARAMS ((cpp_reader *, cpp_macro *, const cpp_token *, unsigned int));
61 static void push_ptoken_context
62 PARAMS ((cpp_reader *, cpp_macro *, _cpp_buff *,
63 const cpp_token **, unsigned int));
64 static _cpp_buff *collect_args PARAMS ((cpp_reader *, const cpp_hashnode *));
65 static cpp_context *next_context PARAMS ((cpp_reader *));
66 static const cpp_token *padding_token
67 PARAMS ((cpp_reader *, const cpp_token *));
68 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
69 static unsigned char *quote_string PARAMS ((unsigned char *,
70 const unsigned char *,
72 static const cpp_token *new_string_token PARAMS ((cpp_reader *, U_CHAR *,
74 static const cpp_token *new_number_token PARAMS ((cpp_reader *, int));
75 static const cpp_token *stringify_arg PARAMS ((cpp_reader *, macro_arg *));
76 static void paste_all_tokens PARAMS ((cpp_reader *, const cpp_token *));
77 static int paste_tokens PARAMS ((cpp_reader *, cpp_token *,
79 static int funlike_invocation_p PARAMS ((cpp_reader *, const cpp_hashnode *));
80 static void replace_args PARAMS ((cpp_reader *, cpp_macro *, macro_arg *));
82 /* #define directive parsing and handling. */
84 static cpp_token *alloc_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
85 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
86 static int warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
88 static int save_parameter PARAMS ((cpp_reader *, cpp_macro *, cpp_hashnode *));
89 static int parse_params PARAMS ((cpp_reader *, cpp_macro *));
90 static void check_trad_stringification PARAMS ((cpp_reader *,
94 /* Allocates and returns a CPP_STRING token, containing TEXT of length
95 LEN, after null-terminating it. TEXT must be in permanent storage. */
96 static const cpp_token *
97 new_string_token (pfile, text, len)
102 cpp_token *token = _cpp_temp_token (pfile);
105 token->type = CPP_STRING;
106 token->val.str.len = len;
107 token->val.str.text = text;
112 /* Allocates and returns a CPP_NUMBER token evaluating to NUMBER. */
113 static const cpp_token *
114 new_number_token (pfile, number)
118 cpp_token *token = _cpp_temp_token (pfile);
119 unsigned char *buf = _cpp_pool_alloc (&pfile->ident_pool, 20);
121 sprintf ((char *) buf, "%d", number);
122 token->type = CPP_NUMBER;
123 token->val.str.text = buf;
124 token->val.str.len = ustrlen (buf);
129 static const char * const monthnames[] =
131 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
132 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
135 /* Handle builtin macros like __FILE__. */
136 static const cpp_token *
137 builtin_macro (pfile, node)
141 switch (node->value.builtin)
144 cpp_ice (pfile, "invalid builtin macro \"%s\"", NODE_NAME (node));
145 return new_number_token (pfile, 1);
153 const struct line_map *map = pfile->map;
155 if (node->value.builtin == BT_BASE_FILE)
156 while (! MAIN_FILE_P (map))
157 map = INCLUDED_FROM (&pfile->line_maps, map);
161 buf = _cpp_pool_alloc (&pfile->ident_pool, len * 4 + 1);
162 len = quote_string (buf, (const unsigned char *) name, len) - buf;
164 return new_string_token (pfile, buf, len);
167 case BT_INCLUDE_LEVEL:
168 /* The line map depth counts the primary source as level 1, but
169 historically __INCLUDE_DEPTH__ has called the primary source
171 return new_number_token (pfile, pfile->line_maps.depth - 1);
174 /* If __LINE__ is embedded in a macro, it must expand to the
175 line of the macro's invocation, not its definition.
176 Otherwise things like assert() will not work properly. */
177 return new_number_token (pfile, SOURCE_LINE (pfile->map,
178 pfile->cur_token[-1].line));
182 int stdc = (!CPP_IN_SYSTEM_HEADER (pfile)
183 || pfile->spec_nodes.n__STRICT_ANSI__->type != NT_VOID);
184 return new_number_token (pfile, stdc);
189 if (pfile->date.type == CPP_EOF)
191 /* Allocate __DATE__ and __TIME__ strings from permanent
192 storage. We only do this once, and don't generate them
193 at init time, because time() and localtime() are very
194 slow on some systems. */
195 time_t tt = time (NULL);
196 struct tm *tb = localtime (&tt);
198 pfile->date.val.str.text =
199 _cpp_pool_alloc (&pfile->ident_pool, sizeof ("Oct 11 1347"));
200 pfile->date.val.str.len = sizeof ("Oct 11 1347") - 1;
201 pfile->date.type = CPP_STRING;
202 pfile->date.flags = 0;
203 sprintf ((char *) pfile->date.val.str.text, "%s %2d %4d",
204 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
206 pfile->time.val.str.text =
207 _cpp_pool_alloc (&pfile->ident_pool, sizeof ("12:34:56"));
208 pfile->time.val.str.len = sizeof ("12:34:56") - 1;
209 pfile->time.type = CPP_STRING;
210 pfile->time.flags = 0;
211 sprintf ((char *) pfile->time.val.str.text, "%02d:%02d:%02d",
212 tb->tm_hour, tb->tm_min, tb->tm_sec);
215 return node->value.builtin == BT_DATE ? &pfile->date: &pfile->time;
219 /* Adds backslashes before all backslashes and double quotes appearing
220 in strings. Non-printable characters are converted to octal. */
222 quote_string (dest, src, len)
231 if (c == '\\' || c == '"')
242 sprintf ((char *) dest, "\\%03o", c);
251 /* Convert a token sequence to a single string token according to the
252 rules of the ISO C #-operator. */
253 static const cpp_token *
254 stringify_arg (pfile, arg)
258 cpp_pool *pool = &pfile->ident_pool;
259 unsigned char *start = POOL_FRONT (pool);
260 unsigned int i, escape_it, total_len = 0, backslash_count = 0;
261 const cpp_token *source = NULL;
263 /* Loop, reading in the argument's tokens. */
264 for (i = 0; i < arg->count; i++)
267 const cpp_token *token = arg->first[i];
270 if (token->type == CPP_PADDING)
273 source = token->val.source;
277 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
278 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
280 len = cpp_token_len (token);
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 /* Leading white space? */
298 if (source->flags & PREV_WHITE)
305 unsigned char *buf = (unsigned char *) xmalloc (len);
307 len = cpp_spell_token (pfile, token, buf) - buf;
308 dest = quote_string (dest, buf, len);
312 dest = cpp_spell_token (pfile, token, dest);
313 total_len = dest - start;
315 if (token->type == CPP_OTHER && token->val.c == '\\')
321 /* Ignore the final \ of invalid string literals. */
322 if (backslash_count & 1)
324 cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
328 /* Commit the memory, including NUL, and return the token. */
329 POOL_COMMIT (pool, total_len + 1);
330 return new_string_token (pfile, start, 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)
340 const cpp_token *rhs;
342 unsigned char flags = 0;
346 type = cpp_can_paste (pfile, lhs, rhs, &digraph);
350 /* Mandatory warning for all apart from assembler. */
351 if (CPP_OPTION (pfile, lang) != CLK_ASM)
353 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
354 cpp_token_as_text (pfile, lhs),
355 cpp_token_as_text (pfile, rhs));
362 /* Identifiers and numbers need spellings to be pasted. */
363 if (type == CPP_NAME || type == CPP_NUMBER)
365 unsigned int total_len = cpp_token_len (lhs) + cpp_token_len (rhs);
366 unsigned char *result, *end;
368 result = _cpp_pool_alloc (&pfile->ident_pool, total_len + 1);
370 /* Paste the spellings and null terminate. */
371 end = cpp_spell_token (pfile, rhs, cpp_spell_token (pfile, lhs, result));
373 total_len = end - result;
375 if (type == CPP_NAME)
377 lhs->val.node = cpp_lookup (pfile, result, total_len);
378 if (lhs->val.node->flags & NODE_OPERATOR)
381 lhs->type = lhs->val.node->value.operator;
386 lhs->val.str.text = result;
387 lhs->val.str.len = total_len;
390 else if (type == CPP_WCHAR || type == CPP_WSTRING)
391 lhs->val.str = rhs->val.str;
393 /* Set type and flags after pasting spellings. */
400 /* Handles an arbitrarily long sequence of ## operators. This
401 implementation is left-associative, non-recursive, and finishes a
402 paste before handling succeeding ones. If the paste fails, we back
403 up a token to just after the ## operator, with the effect that it
404 appears in the output stream normally. */
406 paste_all_tokens (pfile, lhs)
408 const cpp_token *lhs;
411 const cpp_token *rhs;
412 cpp_context *context = pfile->context;
414 /* Copy lhs to pasted, but preserve original line and column. */
415 pasted = _cpp_temp_token (pfile);
416 pasted->type = lhs->type;
417 pasted->flags = lhs->flags;
418 pasted->val.str = lhs->val.str;
422 /* Take the token directly from the current context. We can do
423 this, because we are in the replacement list of either an
424 object-like macro, or a function-like macro with arguments
425 inserted. In either case, the constraints to #define
426 guarantee we have at least one more token. */
427 if (context->direct_p)
428 rhs = context->first.token++;
430 rhs = *context->first.ptoken++;
432 if (rhs->type == CPP_PADDING)
435 if (paste_tokens (pfile, pasted, rhs))
437 _cpp_backup_tokens (pfile, 1);
441 while (rhs->flags & PASTE_LEFT);
443 /* Clear PASTE_LEFT flag, put the token in its own context. */
444 pasted->flags &= ~PASTE_LEFT;
445 push_token_context (pfile, NULL, pasted, 1);
448 /* Reads and returns the arguments to a function-like macro invocation.
449 Assumes the opening parenthesis has been processed. If there is an
450 error, emits an appropriate diagnostic and returns NULL. */
452 collect_args (pfile, node)
454 const cpp_hashnode *node;
456 _cpp_buff *buff, *base_buff;
458 macro_arg *args, *arg;
459 const cpp_token *token;
463 macro = node->value.macro;
465 argc = macro->paramc;
468 buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
469 + sizeof (macro_arg)));
471 args = (macro_arg *) buff->base;
472 memset (args, 0, argc * sizeof (macro_arg));
473 buff->cur = (char *) &args[argc];
474 arg = args, argc = 0;
476 /* Collect the tokens making up each argument. We don't yet know
477 how many arguments have been supplied, whether too many or too
478 few. Hence the slightly bizarre usage of "argc" and "arg". */
481 unsigned int paren_depth = 0;
482 unsigned int ntokens = 0;
485 arg->first = (const cpp_token **) buff->cur;
489 /* Require space for 2 new tokens (including a CPP_EOF). */
490 if ((char *) &arg->first[ntokens + 2] > buff->limit)
492 buff = _cpp_extend_buff (pfile, buff,
493 1000 * sizeof (cpp_token *));
494 arg->first = (const cpp_token **) buff->cur;
497 token = cpp_get_token (pfile);
499 if (token->type == CPP_PADDING)
501 /* Drop leading padding. */
505 else if (token->type == CPP_OPEN_PAREN)
507 else if (token->type == CPP_CLOSE_PAREN)
509 if (paren_depth-- == 0)
512 else if (token->type == CPP_COMMA)
514 /* A comma does not terminate an argument within
515 parentheses or as part of a variable argument. */
517 && ! (macro->variadic && argc == macro->paramc))
520 else if (token->type == CPP_EOF
521 || (token->type == CPP_HASH && token->flags & BOL))
524 arg->first[ntokens++] = token;
527 /* Drop trailing padding. */
528 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
531 arg->count = ntokens;
532 arg->first[ntokens] = &pfile->eof;
534 /* Terminate the argument. Excess arguments loop back and
535 overwrite the final legitimate argument, before failing. */
536 if (argc <= macro->paramc)
538 buff->cur = (char *) &arg->first[ntokens + 1];
539 if (argc != macro->paramc)
543 while (token->type != CPP_CLOSE_PAREN
544 && token->type != CPP_EOF
545 && token->type != CPP_HASH);
547 if (token->type == CPP_EOF || token->type == CPP_HASH)
549 bool step_back = false;
551 /* 6.10.3 paragraph 11: If there are sequences of preprocessing
552 tokens within the list of arguments that would otherwise act
553 as preprocessing directives, the behavior is undefined.
555 This implementation will report a hard error, terminate the
556 macro invocation, and proceed to process the directive. */
557 if (token->type == CPP_HASH)
560 "directives may not be used inside a macro argument");
564 /* We still need the CPP_EOF to end directives, and to end
565 pre-expansion of a macro argument. */
566 step_back = (pfile->context->prev || pfile->state.in_directive);
569 _cpp_backup_tokens (pfile, 1);
570 cpp_error (pfile, "unterminated argument list invoking macro \"%s\"",
574 else if (argc < macro->paramc)
576 /* As an extension, a rest argument is allowed to not appear in
577 the invocation at all.
578 e.g. #define debug(format, args...) something
581 This is exactly the same as if there had been an empty rest
582 argument - debug("string", ). */
584 if (argc + 1 == macro->paramc && macro->variadic)
586 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
587 cpp_pedwarn (pfile, "ISO C99 requires rest arguments to be used");
592 "macro \"%s\" requires %u arguments, but only %u given",
593 NODE_NAME (node), macro->paramc, argc);
597 else if (argc > macro->paramc)
599 /* Empty argument to a macro taking no arguments is OK. */
600 if (argc != 1 || arg->count)
603 "macro \"%s\" passed %u arguments, but takes just %u",
604 NODE_NAME (node), argc, macro->paramc);
612 _cpp_release_buff (pfile, base_buff);
617 funlike_invocation_p (pfile, node)
619 const cpp_hashnode *node;
621 const cpp_token *maybe_paren;
622 _cpp_buff *buff = NULL;
624 pfile->state.prevent_expansion++;
625 pfile->keep_tokens++;
627 pfile->state.parsing_args = 1;
629 maybe_paren = cpp_get_token (pfile);
630 while (maybe_paren->type == CPP_PADDING);
631 pfile->state.parsing_args = 2;
633 if (maybe_paren->type == CPP_OPEN_PAREN)
634 buff = collect_args (pfile, node);
637 _cpp_backup_tokens (pfile, 1);
638 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
640 "function-like macro \"%s\" must be used with arguments in traditional C",
644 pfile->state.parsing_args = 0;
645 pfile->keep_tokens--;
646 pfile->state.prevent_expansion--;
650 if (node->value.macro->paramc > 0)
651 replace_args (pfile, node->value.macro, (macro_arg *) buff->base);
652 _cpp_release_buff (pfile, buff);
658 /* Push the context of a macro onto the context stack. TOKEN is the
659 macro name. If we can successfully start expanding the macro,
660 TOKEN is replaced with the first token of the expansion, and we
663 enter_macro_context (pfile, node)
667 if (node->flags & NODE_BUILTIN)
668 push_token_context (pfile, NULL, builtin_macro (pfile, node), 1);
671 cpp_macro *macro = node->value.macro;
673 if (macro->fun_like && !funlike_invocation_p (pfile, node))
676 /* Disable the macro within its expansion. */
679 if (macro->paramc == 0)
680 push_token_context (pfile, macro, macro->expansion, macro->count);
686 /* Take the expansion of a function-like MACRO, replacing parameters
687 with the actual arguments. Each argument is macro-expanded before
688 replacement, unless operated upon by the # or ## operators. */
690 replace_args (pfile, macro, args)
695 unsigned int i, total;
696 const cpp_token *src, *limit;
697 const cpp_token **dest, **first;
701 /* First, fully macro-expand arguments, calculating the number of
702 tokens in the final expansion as we go. The ordering of the if
703 statements below is subtle; we must handle stringification before
705 total = macro->count;
706 limit = macro->expansion + macro->count;
708 for (src = macro->expansion; src < limit; src++)
709 if (src->type == CPP_MACRO_ARG)
711 /* Leading and trailing padding tokens. */
714 /* We have an argument. If it is not being stringified or
715 pasted it is macro-replaced before insertion. */
716 arg = &args[src->val.arg_no - 1];
718 if (src->flags & STRINGIFY_ARG)
720 if (!arg->stringified)
721 arg->stringified = stringify_arg (pfile, arg);
723 else if ((src->flags & PASTE_LEFT)
724 || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
725 total += arg->count - 1;
729 expand_arg (pfile, arg);
730 total += arg->expanded_count - 1;
734 /* Now allocate space for the expansion, copy the tokens and replace
736 buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
737 first = (const cpp_token **) buff->base;
740 for (src = macro->expansion; src < limit; src++)
743 const cpp_token **from, **paste_flag;
745 if (src->type != CPP_MACRO_ARG)
752 arg = &args[src->val.arg_no - 1];
753 if (src->flags & STRINGIFY_ARG)
754 count = 1, from = &arg->stringified;
755 else if (src->flags & PASTE_LEFT)
756 count = arg->count, from = arg->first;
757 else if (src != macro->expansion && (src[-1].flags & PASTE_LEFT))
759 count = arg->count, from = arg->first;
762 /* GCC has special semantics for , ## b where b is a
763 varargs parameter: the comma disappears if b was
764 given no actual arguments (not merely if b is an
765 empty argument); otherwise the paste flag is removed. */
766 if (dest[-1]->type == CPP_COMMA
768 && src->val.arg_no == macro->paramc)
773 paste_flag = dest - 1;
775 /* Remove the paste flag if the RHS is a placemarker. */
777 paste_flag = dest - 1;
781 count = arg->expanded_count, from = arg->expanded;
783 /* Padding on the left of an argument (unless RHS of ##). */
784 if (!pfile->state.in_directive
785 && src != macro->expansion && !(src[-1].flags & PASTE_LEFT))
786 *dest++ = padding_token (pfile, src);
790 memcpy (dest, from, count * sizeof (cpp_token *));
793 /* With a non-empty argument on the LHS of ##, the last
794 token should be flagged PASTE_LEFT. */
795 if (src->flags & PASTE_LEFT)
796 paste_flag = dest - 1;
799 /* Avoid paste on RHS (even case count == 0). */
800 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
801 *dest++ = &pfile->avoid_paste;
803 /* Add a new paste flag, or remove an unwanted one. */
806 cpp_token *token = _cpp_temp_token (pfile);
807 token->type = (*paste_flag)->type;
808 token->val.str = (*paste_flag)->val.str;
809 if (src->flags & PASTE_LEFT)
810 token->flags = (*paste_flag)->flags | PASTE_LEFT;
812 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
817 /* Free the expanded arguments. */
818 for (i = 0; i < macro->paramc; i++)
819 if (args[i].expanded)
820 free (args[i].expanded);
822 push_ptoken_context (pfile, macro, buff, first, dest - first);
825 /* Return a special padding token, with padding inherited from SOURCE. */
826 static const cpp_token *
827 padding_token (pfile, source)
829 const cpp_token *source;
831 cpp_token *result = _cpp_temp_token (pfile);
833 result->type = CPP_PADDING;
834 result->val.source = source;
839 /* Move to the next context. Create one if there is none. */
844 cpp_context *result = pfile->context->next;
848 result = xnew (cpp_context);
849 result->prev = pfile->context;
851 pfile->context->next = result;
854 pfile->context = result;
858 /* Push a list of pointers to tokens. */
860 push_ptoken_context (pfile, macro, buff, first, count)
864 const cpp_token **first;
867 cpp_context *context = next_context (pfile);
869 context->direct_p = false;
870 context->macro = macro;
871 context->buff = buff;
872 context->first.ptoken = first;
873 context->last.ptoken = first + count;
876 /* Push a list of tokens. */
878 push_token_context (pfile, macro, first, count)
881 const cpp_token *first;
884 cpp_context *context = next_context (pfile);
886 context->direct_p = true;
887 context->macro = macro;
888 context->buff = NULL;
889 context->first.token = first;
890 context->last.token = first + count;
894 expand_arg (pfile, arg)
898 unsigned int capacity;
903 /* Loop, reading in the arguments. */
905 arg->expanded = (const cpp_token **)
906 xmalloc (capacity * sizeof (cpp_token *));
908 push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
911 const cpp_token *token;
913 if (arg->expanded_count + 1 >= capacity)
916 arg->expanded = (const cpp_token **)
917 xrealloc (arg->expanded, capacity * sizeof (cpp_token *));
920 token = cpp_get_token (pfile);
922 if (token->type == CPP_EOF)
925 arg->expanded[arg->expanded_count++] = token;
928 _cpp_pop_context (pfile);
932 _cpp_pop_context (pfile)
935 cpp_context *context = pfile->context;
937 /* Re-enable a macro when leaving its expansion. */
939 context->macro->disabled = 0;
942 _cpp_release_buff (pfile, context->buff);
944 pfile->context = context->prev;
947 /* Eternal routine to get a token. Also used nearly everywhere
948 internally, except for places where we know we can safely call
949 the lexer directly, such as lexing a directive name.
951 Macro expansions and directives are transparently handled,
952 including entering included files. Thus tokens are post-macro
953 expansion, and after any intervening directives. External callers
954 see CPP_EOF only at EOF. Internal callers also see it when meeting
955 a directive inside a macro call, when at the end of a directive and
956 state.in_directive is still 1, and at the end of argument
959 cpp_get_token (pfile)
962 const cpp_token *result;
967 cpp_context *context = pfile->context;
969 /* Context->prev == 0 <=> base context. */
971 result = _cpp_lex_token (pfile);
972 else if (context->first.token != context->last.token)
974 if (context->direct_p)
975 result = context->first.token++;
977 result = *context->first.ptoken++;
979 if (result->flags & PASTE_LEFT)
981 paste_all_tokens (pfile, result);
982 if (pfile->state.in_directive)
984 return padding_token (pfile, result);
989 _cpp_pop_context (pfile);
990 if (pfile->state.in_directive)
992 return &pfile->avoid_paste;
995 if (result->type != CPP_NAME)
998 node = result->val.node;
1000 /* Handle macros and the _Pragma operator. */
1001 if (node->type == NT_MACRO && !(result->flags & NO_EXPAND))
1003 /* Macros invalidate controlling macros. */
1004 pfile->mi_valid = false;
1006 if (!(node->flags & NODE_BUILTIN) && node->value.macro->disabled)
1008 /* Flag this token as always unexpandable. */
1009 cpp_token *t = _cpp_temp_token (pfile);
1010 t->type = result->type;
1011 t->flags = result->flags | NO_EXPAND;
1012 t->val.str = result->val.str;
1015 else if (!pfile->state.prevent_expansion
1016 && enter_macro_context (pfile, node))
1018 if (pfile->state.in_directive)
1020 return padding_token (pfile, result);
1024 /* Don't interpret _Pragma within directives. The standard is
1025 not clear on this, but to me this makes most sense. */
1026 if (node != pfile->spec_nodes.n__Pragma
1027 || pfile->state.in_directive)
1030 /* Handle it, and loop back for another token. MI is cleared
1031 since this token came from either the lexer or a macro. */
1032 _cpp_do__Pragma (pfile);
1038 /* Returns true if we're expanding an object-like macro that was
1039 defined in a system header. Just checks the macro at the top of
1040 the stack. Used for diagnostic suppression. */
1042 cpp_sys_macro_p (pfile)
1045 cpp_macro *macro = pfile->context->macro;
1047 return macro && macro->syshdr;
1050 /* Read each token in, until EOF. Directives are transparently
1053 cpp_scan_nooutput (pfile)
1056 while (cpp_get_token (pfile)->type != CPP_EOF)
1060 /* Step back one (or more) tokens. Can only step mack more than 1 if
1061 they are from the lexer, and not from macro expansion. */
1063 _cpp_backup_tokens (pfile, count)
1067 if (pfile->context->prev == NULL)
1069 pfile->lookaheads += count;
1073 if (pfile->cur_token == pfile->cur_run->base)
1075 pfile->cur_run = pfile->cur_run->prev;
1076 pfile->cur_token = pfile->cur_run->limit;
1084 if (pfile->context->direct_p)
1085 pfile->context->first.token--;
1087 pfile->context->first.ptoken--;
1091 /* #define directive parsing and handling. */
1093 /* Returns non-zero if a macro redefinition warning is required. */
1095 warn_of_redefinition (pfile, node, macro2)
1097 const cpp_hashnode *node;
1098 const cpp_macro *macro2;
1100 const cpp_macro *macro1;
1103 /* Some redefinitions need to be warned about regardless. */
1104 if (node->flags & NODE_WARN)
1107 if (! CPP_PEDANTIC (pfile))
1110 /* Redefinition of a macro is allowed if and only if the old and new
1111 definitions are the same. (6.10.3 paragraph 2). */
1112 macro1 = node->value.macro;
1114 /* The quick failures. */
1115 if (macro1->count != macro2->count
1116 || macro1->paramc != macro2->paramc
1117 || macro1->fun_like != macro2->fun_like
1118 || macro1->variadic != macro2->variadic)
1121 /* Check each token. */
1122 for (i = 0; i < macro1->count; i++)
1123 if (! _cpp_equiv_tokens (¯o1->expansion[i], ¯o2->expansion[i]))
1126 /* Check parameter spellings. */
1127 for (i = 0; i < macro1->paramc; i++)
1128 if (macro1->params[i] != macro2->params[i])
1134 /* Free the definition of hashnode H. */
1137 _cpp_free_definition (h)
1140 /* Macros and assertions no longer have anything to free. */
1142 /* Clear builtin flag in case of redefinition. */
1143 h->flags &= ~NODE_BUILTIN;
1146 /* Save parameter NODE to the parameter list of macro MACRO. Returns
1147 zero on success, non-zero if the paramter is a duplicate. */
1149 save_parameter (pfile, macro, node)
1154 cpp_hashnode **dest;
1156 /* Constraint 6.10.3.6 - duplicate parameter names. */
1157 if (node->arg_index)
1159 cpp_error (pfile, "duplicate macro parameter \"%s\"", NODE_NAME (node));
1163 dest = ¯o->params[macro->paramc];
1165 /* Check we have room for the parameters. */
1166 if ((unsigned char *) (dest + 1) >= POOL_LIMIT (&pfile->macro_pool))
1168 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_hashnode *),
1169 (unsigned char **) ¯o->params);
1170 dest = ¯o->params[macro->paramc];
1174 node->arg_index = ++macro->paramc;
1178 /* Check the syntax of the paramters in a MACRO definition. */
1180 parse_params (pfile, macro)
1184 unsigned int prev_ident = 0;
1186 macro->params = (cpp_hashnode **) POOL_FRONT (&pfile->macro_pool);
1189 const cpp_token *token = _cpp_lex_token (pfile);
1191 switch (token->type)
1194 cpp_error (pfile, "\"%s\" may not appear in macro parameter list",
1195 cpp_token_as_text (pfile, token));
1201 cpp_error (pfile, "macro parameters must be comma-separated");
1206 if (save_parameter (pfile, macro, token->val.node))
1210 case CPP_CLOSE_PAREN:
1211 if (prev_ident || macro->paramc == 0)
1214 /* Fall through to pick up the error. */
1218 cpp_error (pfile, "parameter name missing");
1225 macro->variadic = 1;
1228 save_parameter (pfile, macro, pfile->spec_nodes.n__VA_ARGS__);
1229 pfile->state.va_args_ok = 1;
1230 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1232 "anonymous variadic macros were introduced in C99");
1234 else if (CPP_OPTION (pfile, pedantic))
1235 cpp_pedwarn (pfile, "ISO C does not permit named variadic macros");
1237 /* We're at the end, and just expect a closing parenthesis. */
1238 token = _cpp_lex_token (pfile);
1239 if (token->type == CPP_CLOSE_PAREN)
1244 cpp_error (pfile, "missing ')' in macro parameter list");
1248 /* Success. Commit the parameter array. */
1249 POOL_COMMIT (&pfile->macro_pool,
1250 macro->paramc * sizeof (cpp_hashnode *));
1255 /* Allocate room for a token from a macro's replacement list. */
1257 alloc_expansion_token (pfile, macro)
1261 cpp_token *token = ¯o->expansion[macro->count];
1263 /* Check we have room for the token. */
1264 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->macro_pool))
1266 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_token),
1267 (unsigned char **) ¯o->expansion);
1268 token = ¯o->expansion[macro->count];
1276 lex_expansion_token (pfile, macro)
1282 pfile->cur_token = alloc_expansion_token (pfile, macro);
1283 token = _cpp_lex_direct (pfile);
1285 /* Is this an argument? */
1286 if (token->type == CPP_NAME && token->val.node->arg_index)
1288 token->type = CPP_MACRO_ARG;
1289 token->val.arg_no = token->val.node->arg_index;
1291 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1292 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1293 check_trad_stringification (pfile, macro, &token->val.str);
1298 /* Parse a macro and save its expansion. Returns non-zero on success. */
1300 _cpp_create_definition (pfile, node)
1305 cpp_token *token, *saved_cur_token;
1306 const cpp_token *ctoken;
1307 unsigned int i, ok = 1;
1309 macro = (cpp_macro *) _cpp_pool_alloc (&pfile->macro_pool,
1310 sizeof (cpp_macro));
1311 macro->line = pfile->directive_line;
1314 macro->variadic = 0;
1316 macro->fun_like = 0;
1318 /* Get the first token of the expansion (or the '(' of a
1319 function-like macro). */
1320 ctoken = _cpp_lex_token (pfile);
1322 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1324 if (!(ok = parse_params (pfile, macro)))
1326 macro->fun_like = 1;
1328 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1329 cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
1331 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
1332 saved_cur_token = pfile->cur_token;
1333 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1335 if (macro->fun_like)
1336 token = lex_expansion_token (pfile, macro);
1339 token = alloc_expansion_token (pfile, macro);
1345 /* Check the stringifying # constraint 6.10.3.2.1 of
1346 function-like macros when lexing the subsequent token. */
1347 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1349 if (token->type == CPP_MACRO_ARG)
1351 token->flags &= ~PREV_WHITE;
1352 token->flags |= STRINGIFY_ARG;
1353 token->flags |= token[-1].flags & PREV_WHITE;
1354 token[-1] = token[0];
1357 /* Let assembler get away with murder. */
1358 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1361 cpp_error (pfile, "'#' is not followed by a macro parameter");
1366 if (token->type == CPP_EOF)
1369 /* Paste operator constraint 6.10.3.3.1. */
1370 if (token->type == CPP_PASTE)
1372 /* Token-paste ##, can appear in both object-like and
1373 function-like macros, but not at the ends. */
1374 if (--macro->count > 0)
1375 token = lex_expansion_token (pfile, macro);
1377 if (macro->count == 0 || token->type == CPP_EOF)
1381 "'##' cannot appear at either end of a macro expansion");
1385 token[-1].flags |= PASTE_LEFT;
1388 token = lex_expansion_token (pfile, macro);
1391 /* Don't count the CPP_EOF. */
1394 /* Implement the macro-defined-to-itself optimisation. */
1395 macro->disabled = (macro->count == 1 && !macro->fun_like
1396 && macro->expansion[0].type == CPP_NAME
1397 && macro->expansion[0].val.node == node);
1399 /* To suppress some diagnostics. */
1400 macro->syshdr = pfile->map->sysp != 0;
1402 /* Commit the memory. */
1403 POOL_COMMIT (&pfile->macro_pool, macro->count * sizeof (cpp_token));
1405 if (node->type != NT_VOID)
1407 if (warn_of_redefinition (pfile, node, macro))
1409 cpp_pedwarn_with_line (pfile, pfile->directive_line, 0,
1410 "\"%s\" redefined", NODE_NAME (node));
1412 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1413 cpp_pedwarn_with_line (pfile, node->value.macro->line, 0,
1414 "this is the location of the previous definition");
1416 _cpp_free_definition (node);
1419 /* Enter definition in hash table. */
1420 node->type = NT_MACRO;
1421 node->value.macro = macro;
1422 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1423 node->flags |= NODE_WARN;
1427 /* Set type for SEEN_EOL() in cpplib.c, restore the lexer position. */
1428 saved_cur_token[-1].type = pfile->cur_token[-1].type;
1429 pfile->cur_token = saved_cur_token;
1433 /* Stop the lexer accepting __VA_ARGS__. */
1434 pfile->state.va_args_ok = 0;
1436 /* Clear the fast argument lookup indices. */
1437 for (i = macro->paramc; i-- > 0; )
1438 macro->params[i]->arg_index = 0;
1443 /* Warn if a token in `string' matches one of the function macro
1444 arguments in `info'. This function assumes that the macro is a
1445 function macro and not an object macro. */
1447 check_trad_stringification (pfile, macro, string)
1449 const cpp_macro *macro;
1450 const cpp_string *string;
1452 unsigned int i, len;
1453 const U_CHAR *p, *q, *limit = string->text + string->len;
1455 /* Loop over the string. */
1456 for (p = string->text; p < limit; p = q)
1458 /* Find the start of an identifier. */
1459 while (p < limit && !is_idstart (*p))
1462 /* Find the end of the identifier. */
1464 while (q < limit && is_idchar (*q))
1469 /* Loop over the function macro arguments to see if the
1470 identifier inside the string matches one of them. */
1471 for (i = 0; i < macro->paramc; i++)
1473 const cpp_hashnode *node = macro->params[i];
1475 if (NODE_LEN (node) == len
1476 && !memcmp (p, NODE_NAME (node), len))
1479 "macro argument \"%s\" would be stringified with -traditional.",
1487 /* Returns the name, arguments and expansion of a macro, in a format
1488 suitable to be read back in again, and therefore also for DWARF 2
1489 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1490 Caller is expected to generate the "#define" bit if needed. The
1491 returned text is temporary, and automatically freed later. */
1493 const unsigned char *
1494 cpp_macro_definition (pfile, node)
1496 const cpp_hashnode *node;
1498 unsigned int i, len;
1499 const cpp_macro *macro = node->value.macro;
1500 unsigned char *buffer;
1502 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1504 cpp_ice (pfile, "invalid hash type %d in cpp_macro_definition", node->type);
1508 /* Calculate length. */
1509 len = NODE_LEN (node) + 1; /* ' ' */
1510 if (macro->fun_like)
1512 len += 3; /* "()" plus possible final "." of named
1513 varargs (we have + 2 below). */
1514 for (i = 0; i < macro->paramc; i++)
1515 len += NODE_LEN (macro->params[i]) + 2; /* ", " */
1518 for (i = 0; i < macro->count; i++)
1520 cpp_token *token = ¯o->expansion[i];
1522 if (token->type == CPP_MACRO_ARG)
1523 len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1525 len += cpp_token_len (token); /* Includes room for ' '. */
1526 if (token->flags & STRINGIFY_ARG)
1528 if (token->flags & PASTE_LEFT)
1529 len += 3; /* " ##" */
1532 if (len > pfile->macro_buffer_len)
1534 pfile->macro_buffer = (U_CHAR *) xrealloc (pfile->macro_buffer, len);
1535 pfile->macro_buffer_len = len;
1538 /* Fill in the buffer. Start with the macro name. */
1539 buffer = pfile->macro_buffer;
1540 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1541 buffer += NODE_LEN (node);
1543 /* Parameter names. */
1544 if (macro->fun_like)
1547 for (i = 0; i < macro->paramc; i++)
1549 cpp_hashnode *param = macro->params[i];
1551 if (param != pfile->spec_nodes.n__VA_ARGS__)
1553 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1554 buffer += NODE_LEN (param);
1557 if (i + 1 < macro->paramc)
1558 *buffer++ = ',', *buffer++ = ' ';
1559 else if (macro->variadic)
1560 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1565 /* Expansion tokens. */
1569 for (i = 0; i < macro->count; i++)
1571 cpp_token *token = ¯o->expansion[i];
1573 if (token->flags & PREV_WHITE)
1575 if (token->flags & STRINGIFY_ARG)
1578 if (token->type == CPP_MACRO_ARG)
1580 len = NODE_LEN (macro->params[token->val.arg_no - 1]);
1582 NODE_NAME (macro->params[token->val.arg_no - 1]), len);
1586 buffer = cpp_spell_token (pfile, token, buffer);
1588 if (token->flags & PASTE_LEFT)
1593 /* Next has PREV_WHITE; see _cpp_create_definition. */
1599 return pfile->macro_buffer;