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, 2002 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! */
31 typedef struct macro_arg macro_arg;
34 const cpp_token **first; /* First token in unexpanded argument. */
35 const cpp_token **expanded; /* Macro-expanded argument. */
36 const cpp_token *stringified; /* Stringified argument. */
37 unsigned int count; /* # of tokens in argument. */
38 unsigned int expanded_count; /* # of tokens in expanded argument. */
41 /* Macro expansion. */
43 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
44 static int builtin_macro PARAMS ((cpp_reader *, cpp_hashnode *));
45 static void push_token_context
46 PARAMS ((cpp_reader *, cpp_hashnode *, const cpp_token *, unsigned int));
47 static void push_ptoken_context
48 PARAMS ((cpp_reader *, cpp_hashnode *, _cpp_buff *,
49 const cpp_token **, unsigned int));
50 static _cpp_buff *collect_args PARAMS ((cpp_reader *, const cpp_hashnode *));
51 static cpp_context *next_context PARAMS ((cpp_reader *));
52 static const cpp_token *padding_token
53 PARAMS ((cpp_reader *, const cpp_token *));
54 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
55 static const cpp_token *new_string_token PARAMS ((cpp_reader *, uchar *,
57 static const cpp_token *stringify_arg PARAMS ((cpp_reader *, macro_arg *));
58 static void paste_all_tokens PARAMS ((cpp_reader *, const cpp_token *));
59 static bool paste_tokens PARAMS ((cpp_reader *, const cpp_token **,
61 static void replace_args PARAMS ((cpp_reader *, cpp_hashnode *, cpp_macro *,
63 static _cpp_buff *funlike_invocation_p PARAMS ((cpp_reader *, cpp_hashnode *));
64 static bool create_iso_definition PARAMS ((cpp_reader *, cpp_macro *));
66 /* #define directive parsing and handling. */
68 static cpp_token *alloc_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
69 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
70 static bool warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
72 static bool parse_params PARAMS ((cpp_reader *, cpp_macro *));
73 static void check_trad_stringification PARAMS ((cpp_reader *,
77 /* Emits a warning if NODE is a macro defined in the main file that
80 _cpp_warn_if_unused_macro (pfile, node, v)
83 void *v ATTRIBUTE_UNUSED;
85 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
87 cpp_macro *macro = node->value.macro;
90 /* Skip front-end built-ins and command line macros. */
91 && macro->line >= pfile->first_unused_line
92 && MAIN_FILE_P (lookup_line (&pfile->line_maps, macro->line)))
93 cpp_error_with_line (pfile, DL_WARNING, macro->line, 0,
94 "macro \"%s\" is not used", NODE_NAME (node));
100 /* Allocates and returns a CPP_STRING token, containing TEXT of length
101 LEN, after null-terminating it. TEXT must be in permanent storage. */
102 static const cpp_token *
103 new_string_token (pfile, text, len)
108 cpp_token *token = _cpp_temp_token (pfile);
111 token->type = CPP_STRING;
112 token->val.str.len = len;
113 token->val.str.text = text;
118 static const char * const monthnames[] =
120 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
121 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
124 /* Handle builtin macros like __FILE__, and push the resulting token
125 on the context stack. Also handles _Pragma, for which no new token
126 is created. Returns 1 if it generates a new token context, 0 to
127 return the token to the caller. */
129 _cpp_builtin_macro_text (pfile, node)
133 const uchar *result = NULL;
134 unsigned int number = 1;
136 switch (node->value.builtin)
139 cpp_error (pfile, DL_ICE, "invalid built-in macro \"%s\"",
149 const struct line_map *map = pfile->map;
151 if (node->value.builtin == BT_BASE_FILE)
152 while (! MAIN_FILE_P (map))
153 map = INCLUDED_FROM (&pfile->line_maps, map);
157 buf = _cpp_unaligned_alloc (pfile, len * 4 + 3);
160 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
166 case BT_INCLUDE_LEVEL:
167 /* The line map depth counts the primary source as level 1, but
168 historically __INCLUDE_DEPTH__ has called the primary source
170 number = 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 if (CPP_OPTION (pfile, traditional))
178 number = pfile->line;
180 number = pfile->cur_token[-1].line;
181 number = SOURCE_LINE (pfile->map, number);
184 /* __STDC__ has the value 1 under normal circumstances.
185 However, if (a) we are in a system header, (b) the option
186 stdc_0_in_system_headers is true (set by target config), and
187 (c) we are not in strictly conforming mode, then it has the
191 enum c_lang lang = CPP_OPTION (pfile, lang);
192 if (CPP_IN_SYSTEM_HEADER (pfile)
193 && CPP_OPTION (pfile, stdc_0_in_system_headers)
194 && !(lang == CLK_STDC89 || lang == CLK_STDC94
195 || lang == CLK_STDC99)) /* || lang == CLK_CXX98 ? */
204 if (pfile->date == NULL)
206 /* Allocate __DATE__ and __TIME__ strings from permanent
207 storage. We only do this once, and don't generate them
208 at init time, because time() and localtime() are very
209 slow on some systems. */
211 struct tm *tb = NULL;
213 /* (time_t) -1 is a legitimate value for "number of seconds
214 since the Epoch", so we have to do a little dance to
215 distinguish that from a genuine error. */
218 if (tt != (time_t)-1 || errno == 0)
219 tb = localtime (&tt);
223 pfile->date = _cpp_unaligned_alloc (pfile,
224 sizeof ("\"Oct 11 1347\""));
225 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
226 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
228 pfile->time = _cpp_unaligned_alloc (pfile,
229 sizeof ("\"12:34:56\""));
230 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
231 tb->tm_hour, tb->tm_min, tb->tm_sec);
235 cpp_errno (pfile, DL_WARNING,
236 "could not determine date and time");
238 pfile->date = U"\"??? ?? ????\"";
239 pfile->time = U"\"??:??:??\"";
243 if (node->value.builtin == BT_DATE)
244 result = pfile->date;
246 result = pfile->time;
252 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
253 result = _cpp_unaligned_alloc (pfile, 21);
254 sprintf ((char *) result, "%u", number);
260 /* Convert builtin macros like __FILE__ to a token and push it on the
261 context stack. Also handles _Pragma, for which no new token is
262 created. Returns 1 if it generates a new token context, 0 to
263 return the token to the caller. */
265 builtin_macro (pfile, node)
271 if (node->value.builtin == BT_PRAGMA)
273 /* Don't interpret _Pragma within directives. The standard is
274 not clear on this, but to me this makes most sense. */
275 if (pfile->state.in_directive)
278 _cpp_do__Pragma (pfile);
282 buf = _cpp_builtin_macro_text (pfile, node);
284 cpp_push_buffer (pfile, buf, ustrlen (buf), /* from_stage3 */ true, 1);
286 /* Tweak the column number the lexer will report. */
287 pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
289 /* We don't want a leading # to be interpreted as a directive. */
290 pfile->buffer->saved_flags = 0;
292 /* Set pfile->cur_token as required by _cpp_lex_direct. */
293 pfile->cur_token = _cpp_temp_token (pfile);
294 push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
295 if (pfile->buffer->cur != pfile->buffer->rlimit)
296 cpp_error (pfile, DL_ICE, "invalid built-in macro \"%s\"",
298 _cpp_pop_buffer (pfile);
303 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
304 backslashes and double quotes. Non-printable characters are
305 converted to octal. DEST must be of sufficient size. Returns
306 a pointer to the end of the string. */
308 cpp_quote_string (dest, src, len)
317 if (c == '\\' || c == '"')
328 sprintf ((char *) dest, "\\%03o", c);
337 /* Convert a token sequence ARG to a single string token according to
338 the rules of the ISO C #-operator. */
339 static const cpp_token *
340 stringify_arg (pfile, arg)
344 unsigned char *dest = BUFF_FRONT (pfile->u_buff);
345 unsigned int i, escape_it, backslash_count = 0;
346 const cpp_token *source = NULL;
349 /* Loop, reading in the argument's tokens. */
350 for (i = 0; i < arg->count; i++)
352 const cpp_token *token = arg->first[i];
354 if (token->type == CPP_PADDING)
357 source = token->val.source;
361 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
362 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
364 /* Room for each char being written in octal, initial space and
366 len = cpp_token_len (token);
371 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
373 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
374 _cpp_extend_buff (pfile, &pfile->u_buff, len);
375 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
378 /* Leading white space? */
379 if (dest != BUFF_FRONT (pfile->u_buff))
383 if (source->flags & PREV_WHITE)
390 _cpp_buff *buff = _cpp_get_buff (pfile, len);
391 unsigned char *buf = BUFF_FRONT (buff);
392 len = cpp_spell_token (pfile, token, buf) - buf;
393 dest = cpp_quote_string (dest, buf, len);
394 _cpp_release_buff (pfile, buff);
397 dest = cpp_spell_token (pfile, token, dest);
399 if (token->type == CPP_OTHER && token->val.c == '\\')
405 /* Ignore the final \ of invalid string literals. */
406 if (backslash_count & 1)
408 cpp_error (pfile, DL_WARNING,
409 "invalid string literal, ignoring final '\\'");
413 /* Commit the memory, including NUL, and return the token. */
414 len = dest - BUFF_FRONT (pfile->u_buff);
415 BUFF_FRONT (pfile->u_buff) = dest + 1;
416 return new_string_token (pfile, dest - len, len);
419 /* Try to paste two tokens. On success, return non-zero. In any
420 case, PLHS is updated to point to the pasted token, which is
421 guaranteed to not have the PASTE_LEFT flag set. */
423 paste_tokens (pfile, plhs, rhs)
425 const cpp_token **plhs, *rhs;
427 unsigned char *buf, *end;
428 const cpp_token *lhs;
433 len = cpp_token_len (lhs) + cpp_token_len (rhs) + 1;
434 buf = (unsigned char *) alloca (len);
435 end = cpp_spell_token (pfile, lhs, buf);
437 /* Avoid comment headers, since they are still processed in stage 3.
438 It is simpler to insert a space here, rather than modifying the
439 lexer to ignore comments in some circumstances. Simply returning
440 false doesn't work, since we want to clear the PASTE_LEFT flag. */
441 if (lhs->type == CPP_DIV
442 && (rhs->type == CPP_MULT || rhs->type == CPP_DIV))
444 end = cpp_spell_token (pfile, rhs, end);
447 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true, 1);
449 /* Tweak the column number the lexer will report. */
450 pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
452 /* We don't want a leading # to be interpreted as a directive. */
453 pfile->buffer->saved_flags = 0;
455 /* Set pfile->cur_token as required by _cpp_lex_direct. */
456 pfile->cur_token = _cpp_temp_token (pfile);
457 *plhs = _cpp_lex_direct (pfile);
458 valid = pfile->buffer->cur == pfile->buffer->rlimit;
459 _cpp_pop_buffer (pfile);
464 /* Handles an arbitrarily long sequence of ## operators, with initial
465 operand LHS. This implementation is left-associative,
466 non-recursive, and finishes a paste before handling succeeding
467 ones. If a paste fails, we back up to the RHS of the failing ##
468 operator before pushing the context containing the result of prior
469 successful pastes, with the effect that the RHS appears in the
470 output stream after the pasted LHS normally. */
472 paste_all_tokens (pfile, lhs)
474 const cpp_token *lhs;
476 const cpp_token *rhs;
477 cpp_context *context = pfile->context;
481 /* Take the token directly from the current context. We can do
482 this, because we are in the replacement list of either an
483 object-like macro, or a function-like macro with arguments
484 inserted. In either case, the constraints to #define
485 guarantee we have at least one more token. */
486 if (context->direct_p)
487 rhs = FIRST (context).token++;
489 rhs = *FIRST (context).ptoken++;
491 if (rhs->type == CPP_PADDING)
494 if (!paste_tokens (pfile, &lhs, rhs))
496 _cpp_backup_tokens (pfile, 1);
498 /* Mandatory error for all apart from assembler. */
499 if (CPP_OPTION (pfile, lang) != CLK_ASM)
500 cpp_error (pfile, DL_ERROR,
501 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
502 cpp_token_as_text (pfile, lhs),
503 cpp_token_as_text (pfile, rhs));
507 while (rhs->flags & PASTE_LEFT);
509 /* Put the resulting token in its own context. */
510 push_token_context (pfile, NULL, lhs, 1);
513 /* Returns TRUE if the number of arguments ARGC supplied in an
514 invocation of the MACRO referenced by NODE is valid. An empty
515 invocation to a macro with no parameters should pass ARGC as zero.
517 Note that MACRO cannot necessarily be deduced from NODE, in case
518 NODE was redefined whilst collecting arguments. */
520 _cpp_arguments_ok (pfile, macro, node, argc)
523 const cpp_hashnode *node;
526 if (argc == macro->paramc)
529 if (argc < macro->paramc)
531 /* As an extension, a rest argument is allowed to not appear in
532 the invocation at all.
533 e.g. #define debug(format, args...) something
536 This is exactly the same as if there had been an empty rest
537 argument - debug("string", ). */
539 if (argc + 1 == macro->paramc && macro->variadic)
541 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
542 cpp_error (pfile, DL_PEDWARN,
543 "ISO C99 requires rest arguments to be used");
547 cpp_error (pfile, DL_ERROR,
548 "macro \"%s\" requires %u arguments, but only %u given",
549 NODE_NAME (node), macro->paramc, argc);
552 cpp_error (pfile, DL_ERROR,
553 "macro \"%s\" passed %u arguments, but takes just %u",
554 NODE_NAME (node), argc, macro->paramc);
559 /* Reads and returns the arguments to a function-like macro
560 invocation. Assumes the opening parenthesis has been processed.
561 If there is an error, emits an appropriate diagnostic and returns
562 NULL. Each argument is terminated by a CPP_EOF token, for the
563 future benefit of expand_arg(). */
565 collect_args (pfile, node)
567 const cpp_hashnode *node;
569 _cpp_buff *buff, *base_buff;
571 macro_arg *args, *arg;
572 const cpp_token *token;
575 macro = node->value.macro;
577 argc = macro->paramc;
580 buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
581 + sizeof (macro_arg)));
583 args = (macro_arg *) buff->base;
584 memset (args, 0, argc * sizeof (macro_arg));
585 buff->cur = (unsigned char *) &args[argc];
586 arg = args, argc = 0;
588 /* Collect the tokens making up each argument. We don't yet know
589 how many arguments have been supplied, whether too many or too
590 few. Hence the slightly bizarre usage of "argc" and "arg". */
593 unsigned int paren_depth = 0;
594 unsigned int ntokens = 0;
597 arg->first = (const cpp_token **) buff->cur;
601 /* Require space for 2 new tokens (including a CPP_EOF). */
602 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
604 buff = _cpp_append_extend_buff (pfile, buff,
605 1000 * sizeof (cpp_token *));
606 arg->first = (const cpp_token **) buff->cur;
609 token = cpp_get_token (pfile);
611 if (token->type == CPP_PADDING)
613 /* Drop leading padding. */
617 else if (token->type == CPP_OPEN_PAREN)
619 else if (token->type == CPP_CLOSE_PAREN)
621 if (paren_depth-- == 0)
624 else if (token->type == CPP_COMMA)
626 /* A comma does not terminate an argument within
627 parentheses or as part of a variable argument. */
629 && ! (macro->variadic && argc == macro->paramc))
632 else if (token->type == CPP_EOF
633 || (token->type == CPP_HASH && token->flags & BOL))
636 arg->first[ntokens++] = token;
639 /* Drop trailing padding. */
640 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
643 arg->count = ntokens;
644 arg->first[ntokens] = &pfile->eof;
646 /* Terminate the argument. Excess arguments loop back and
647 overwrite the final legitimate argument, before failing. */
648 if (argc <= macro->paramc)
650 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
651 if (argc != macro->paramc)
655 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
657 if (token->type == CPP_EOF)
659 /* We still need the CPP_EOF to end directives, and to end
660 pre-expansion of a macro argument. Step back is not
661 unconditional, since we don't want to return a CPP_EOF to our
662 callers at the end of an -include-d file. */
663 if (pfile->context->prev || pfile->state.in_directive)
664 _cpp_backup_tokens (pfile, 1);
665 cpp_error (pfile, DL_ERROR,
666 "unterminated argument list invoking macro \"%s\"",
671 /* A single empty argument is counted as no argument. */
672 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
674 if (_cpp_arguments_ok (pfile, macro, node, argc))
678 /* An error occurred. */
679 _cpp_release_buff (pfile, base_buff);
683 /* Search for an opening parenthesis to the macro of NODE, in such a
684 way that, if none is found, we don't lose the information in any
685 intervening padding tokens. If we find the parenthesis, collect
686 the arguments and return the buffer containing them. */
688 funlike_invocation_p (pfile, node)
692 const cpp_token *token, *padding = NULL;
696 token = cpp_get_token (pfile);
697 if (token->type != CPP_PADDING)
700 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
704 if (token->type == CPP_OPEN_PAREN)
706 pfile->state.parsing_args = 2;
707 return collect_args (pfile, node);
710 /* CPP_EOF can be the end of macro arguments, or the end of the
711 file. We mustn't back up over the latter. Ugh. */
712 if (token->type != CPP_EOF || token == &pfile->eof)
714 /* Back up. We may have skipped padding, in which case backing
715 up more than one token when expanding macros is in general
716 too difficult. We re-insert it in its own context. */
717 _cpp_backup_tokens (pfile, 1);
719 push_token_context (pfile, NULL, padding, 1);
725 /* Push the context of a macro with hash entry NODE onto the context
726 stack. If we can successfully expand the macro, we push a context
727 containing its yet-to-be-rescanned replacement list and return one.
728 Otherwise, we don't push a context and return zero. */
730 enter_macro_context (pfile, node)
734 /* The presence of a macro invalidates a file's controlling macro. */
735 pfile->mi_valid = false;
737 pfile->state.angled_headers = false;
739 /* Handle standard macros. */
740 if (! (node->flags & NODE_BUILTIN))
742 cpp_macro *macro = node->value.macro;
748 pfile->state.prevent_expansion++;
749 pfile->keep_tokens++;
750 pfile->state.parsing_args = 1;
751 buff = funlike_invocation_p (pfile, node);
752 pfile->state.parsing_args = 0;
753 pfile->keep_tokens--;
754 pfile->state.prevent_expansion--;
758 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
759 cpp_error (pfile, DL_WARNING,
760 "function-like macro \"%s\" must be used with arguments in traditional C",
766 if (macro->paramc > 0)
767 replace_args (pfile, node, macro, (macro_arg *) buff->base);
768 _cpp_release_buff (pfile, buff);
771 /* Disable the macro within its expansion. */
772 node->flags |= NODE_DISABLED;
776 if (macro->paramc == 0)
777 push_token_context (pfile, node, macro->exp.tokens, macro->count);
782 /* Handle built-in macros and the _Pragma operator. */
783 return builtin_macro (pfile, node);
786 /* Replace the parameters in a function-like macro of NODE with the
787 actual ARGS, and place the result in a newly pushed token context.
788 Expand each argument before replacing, unless it is operated upon
789 by the # or ## operators. */
791 replace_args (pfile, node, macro, args)
797 unsigned int i, total;
798 const cpp_token *src, *limit;
799 const cpp_token **dest, **first;
803 /* First, fully macro-expand arguments, calculating the number of
804 tokens in the final expansion as we go. The ordering of the if
805 statements below is subtle; we must handle stringification before
807 total = macro->count;
808 limit = macro->exp.tokens + macro->count;
810 for (src = macro->exp.tokens; src < limit; src++)
811 if (src->type == CPP_MACRO_ARG)
813 /* Leading and trailing padding tokens. */
816 /* We have an argument. If it is not being stringified or
817 pasted it is macro-replaced before insertion. */
818 arg = &args[src->val.arg_no - 1];
820 if (src->flags & STRINGIFY_ARG)
822 if (!arg->stringified)
823 arg->stringified = stringify_arg (pfile, arg);
825 else if ((src->flags & PASTE_LEFT)
826 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
827 total += arg->count - 1;
831 expand_arg (pfile, arg);
832 total += arg->expanded_count - 1;
836 /* Now allocate space for the expansion, copy the tokens and replace
838 buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
839 first = (const cpp_token **) buff->base;
842 for (src = macro->exp.tokens; src < limit; src++)
845 const cpp_token **from, **paste_flag;
847 if (src->type != CPP_MACRO_ARG)
854 arg = &args[src->val.arg_no - 1];
855 if (src->flags & STRINGIFY_ARG)
856 count = 1, from = &arg->stringified;
857 else if (src->flags & PASTE_LEFT)
858 count = arg->count, from = arg->first;
859 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
861 count = arg->count, from = arg->first;
864 /* GCC has special semantics for , ## b where b is a
865 varargs parameter: the comma disappears if b was
866 given no actual arguments (not merely if b is an
867 empty argument); otherwise the paste flag is removed. */
868 if (dest[-1]->type == CPP_COMMA
870 && src->val.arg_no == macro->paramc)
875 paste_flag = dest - 1;
877 /* Remove the paste flag if the RHS is a placemarker. */
879 paste_flag = dest - 1;
883 count = arg->expanded_count, from = arg->expanded;
885 /* Padding on the left of an argument (unless RHS of ##). */
886 if (!pfile->state.in_directive
887 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
888 *dest++ = padding_token (pfile, src);
892 memcpy (dest, from, count * sizeof (cpp_token *));
895 /* With a non-empty argument on the LHS of ##, the last
896 token should be flagged PASTE_LEFT. */
897 if (src->flags & PASTE_LEFT)
898 paste_flag = dest - 1;
901 /* Avoid paste on RHS (even case count == 0). */
902 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
903 *dest++ = &pfile->avoid_paste;
905 /* Add a new paste flag, or remove an unwanted one. */
908 cpp_token *token = _cpp_temp_token (pfile);
909 token->type = (*paste_flag)->type;
910 token->val.str = (*paste_flag)->val.str;
911 if (src->flags & PASTE_LEFT)
912 token->flags = (*paste_flag)->flags | PASTE_LEFT;
914 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
919 /* Free the expanded arguments. */
920 for (i = 0; i < macro->paramc; i++)
921 if (args[i].expanded)
922 free (args[i].expanded);
924 push_ptoken_context (pfile, node, buff, first, dest - first);
927 /* Return a special padding token, with padding inherited from SOURCE. */
928 static const cpp_token *
929 padding_token (pfile, source)
931 const cpp_token *source;
933 cpp_token *result = _cpp_temp_token (pfile);
935 result->type = CPP_PADDING;
936 result->val.source = source;
941 /* Get a new uninitialized context. Create a new one if we cannot
942 re-use an old one. */
947 cpp_context *result = pfile->context->next;
951 result = xnew (cpp_context);
952 result->prev = pfile->context;
954 pfile->context->next = result;
957 pfile->context = result;
961 /* Push a list of pointers to tokens. */
963 push_ptoken_context (pfile, macro, buff, first, count)
967 const cpp_token **first;
970 cpp_context *context = next_context (pfile);
972 context->direct_p = false;
973 context->macro = macro;
974 context->buff = buff;
975 FIRST (context).ptoken = first;
976 LAST (context).ptoken = first + count;
979 /* Push a list of tokens. */
981 push_token_context (pfile, macro, first, count)
984 const cpp_token *first;
987 cpp_context *context = next_context (pfile);
989 context->direct_p = true;
990 context->macro = macro;
991 context->buff = NULL;
992 FIRST (context).token = first;
993 LAST (context).token = first + count;
996 /* Push a traditional macro's replacement text. */
998 _cpp_push_text_context (pfile, macro, start, len)
1000 cpp_hashnode *macro;
1004 cpp_context *context = next_context (pfile);
1006 context->direct_p = true;
1007 context->macro = macro;
1008 context->buff = NULL;
1009 CUR (context) = start;
1010 RLIMIT (context) = start + len;
1011 macro->flags |= NODE_DISABLED;
1014 /* Expand an argument ARG before replacing parameters in a
1015 function-like macro. This works by pushing a context with the
1016 argument's tokens, and then expanding that into a temporary buffer
1017 as if it were a normal part of the token stream. collect_args()
1018 has terminated the argument's tokens with a CPP_EOF so that we know
1019 when we have fully expanded the argument. */
1021 expand_arg (pfile, arg)
1025 unsigned int capacity;
1027 if (arg->count == 0)
1030 /* Loop, reading in the arguments. */
1032 arg->expanded = (const cpp_token **)
1033 xmalloc (capacity * sizeof (cpp_token *));
1035 push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
1038 const cpp_token *token;
1040 if (arg->expanded_count + 1 >= capacity)
1043 arg->expanded = (const cpp_token **)
1044 xrealloc (arg->expanded, capacity * sizeof (cpp_token *));
1047 token = cpp_get_token (pfile);
1049 if (token->type == CPP_EOF)
1052 arg->expanded[arg->expanded_count++] = token;
1055 _cpp_pop_context (pfile);
1058 /* Pop the current context off the stack, re-enabling the macro if the
1059 context represented a macro's replacement list. The context
1060 structure is not freed so that we can re-use it later. */
1062 _cpp_pop_context (pfile)
1065 cpp_context *context = pfile->context;
1068 context->macro->flags &= ~NODE_DISABLED;
1071 _cpp_release_buff (pfile, context->buff);
1073 pfile->context = context->prev;
1076 /* Eternal routine to get a token. Also used nearly everywhere
1077 internally, except for places where we know we can safely call
1078 the lexer directly, such as lexing a directive name.
1080 Macro expansions and directives are transparently handled,
1081 including entering included files. Thus tokens are post-macro
1082 expansion, and after any intervening directives. External callers
1083 see CPP_EOF only at EOF. Internal callers also see it when meeting
1084 a directive inside a macro call, when at the end of a directive and
1085 state.in_directive is still 1, and at the end of argument
1088 cpp_get_token (pfile)
1091 const cpp_token *result;
1096 cpp_context *context = pfile->context;
1098 /* Context->prev == 0 <=> base context. */
1100 result = _cpp_lex_token (pfile);
1101 else if (FIRST (context).token != LAST (context).token)
1103 if (context->direct_p)
1104 result = FIRST (context).token++;
1106 result = *FIRST (context).ptoken++;
1108 if (result->flags & PASTE_LEFT)
1110 paste_all_tokens (pfile, result);
1111 if (pfile->state.in_directive)
1113 return padding_token (pfile, result);
1118 _cpp_pop_context (pfile);
1119 if (pfile->state.in_directive)
1121 return &pfile->avoid_paste;
1124 if (pfile->state.in_directive && result->type == CPP_COMMENT)
1127 if (result->type != CPP_NAME)
1130 node = result->val.node;
1132 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1135 if (!(node->flags & NODE_DISABLED))
1137 if (!pfile->state.prevent_expansion
1138 && enter_macro_context (pfile, node))
1140 if (pfile->state.in_directive)
1142 return padding_token (pfile, result);
1147 /* Flag this token as always unexpandable. FIXME: move this
1148 to collect_args()?. */
1149 cpp_token *t = _cpp_temp_token (pfile);
1150 t->type = result->type;
1151 t->flags = result->flags | NO_EXPAND;
1152 t->val.str = result->val.str;
1162 /* Returns true if we're expanding an object-like macro that was
1163 defined in a system header. Just checks the macro at the top of
1164 the stack. Used for diagnostic suppression. */
1166 cpp_sys_macro_p (pfile)
1169 cpp_hashnode *node = pfile->context->macro;
1171 return node && node->value.macro && node->value.macro->syshdr;
1174 /* Read each token in, until end of the current file. Directives are
1175 transparently processed. */
1177 cpp_scan_nooutput (pfile)
1180 /* Request a CPP_EOF token at the end of this file, rather than
1181 transparently continuing with the including file. */
1182 pfile->buffer->return_at_eof = true;
1184 if (CPP_OPTION (pfile, traditional))
1185 while (_cpp_read_logical_line_trad (pfile))
1188 while (cpp_get_token (pfile)->type != CPP_EOF)
1192 /* Step back one (or more) tokens. Can only step mack more than 1 if
1193 they are from the lexer, and not from macro expansion. */
1195 _cpp_backup_tokens (pfile, count)
1199 if (pfile->context->prev == NULL)
1201 pfile->lookaheads += count;
1205 if (pfile->cur_token == pfile->cur_run->base
1206 /* Possible with -fpreprocessed and no leading #line. */
1207 && pfile->cur_run->prev != NULL)
1209 pfile->cur_run = pfile->cur_run->prev;
1210 pfile->cur_token = pfile->cur_run->limit;
1218 if (pfile->context->direct_p)
1219 FIRST (pfile->context).token--;
1221 FIRST (pfile->context).ptoken--;
1225 /* #define directive parsing and handling. */
1227 /* Returns non-zero if a macro redefinition warning is required. */
1229 warn_of_redefinition (pfile, node, macro2)
1231 const cpp_hashnode *node;
1232 const cpp_macro *macro2;
1234 const cpp_macro *macro1;
1237 /* Some redefinitions need to be warned about regardless. */
1238 if (node->flags & NODE_WARN)
1241 /* Redefinition of a macro is allowed if and only if the old and new
1242 definitions are the same. (6.10.3 paragraph 2). */
1243 macro1 = node->value.macro;
1245 /* Don't check count here as it can be different in valid
1246 traditional redefinitions with just whitespace differences. */
1247 if (macro1->paramc != macro2->paramc
1248 || macro1->fun_like != macro2->fun_like
1249 || macro1->variadic != macro2->variadic)
1252 /* Check parameter spellings. */
1253 for (i = 0; i < macro1->paramc; i++)
1254 if (macro1->params[i] != macro2->params[i])
1257 /* Check the replacement text or tokens. */
1258 if (CPP_OPTION (pfile, traditional))
1259 return _cpp_expansions_different_trad (macro1, macro2);
1261 if (macro1->count == macro2->count)
1262 for (i = 0; i < macro1->count; i++)
1263 if (!_cpp_equiv_tokens (¯o1->exp.tokens[i], ¯o2->exp.tokens[i]))
1269 /* Free the definition of hashnode H. */
1271 _cpp_free_definition (h)
1274 /* Macros and assertions no longer have anything to free. */
1276 /* Clear builtin flag in case of redefinition. */
1277 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1280 /* Save parameter NODE to the parameter list of macro MACRO. Returns
1281 zero on success, non-zero if the parameter is a duplicate. */
1283 _cpp_save_parameter (pfile, macro, node)
1288 /* Constraint 6.10.3.6 - duplicate parameter names. */
1289 if (node->arg_index)
1291 cpp_error (pfile, DL_ERROR, "duplicate macro parameter \"%s\"",
1296 if (BUFF_ROOM (pfile->a_buff)
1297 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1298 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1300 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1301 node->arg_index = macro->paramc;
1305 /* Check the syntax of the parameters in a MACRO definition. Returns
1306 false if an error occurs. */
1308 parse_params (pfile, macro)
1312 unsigned int prev_ident = 0;
1316 const cpp_token *token = _cpp_lex_token (pfile);
1318 switch (token->type)
1321 /* Allow/ignore comments in parameter lists if we are
1322 preserving comments in macro expansions. */
1323 if (token->type == CPP_COMMENT
1324 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
1327 cpp_error (pfile, DL_ERROR,
1328 "\"%s\" may not appear in macro parameter list",
1329 cpp_token_as_text (pfile, token));
1335 cpp_error (pfile, DL_ERROR,
1336 "macro parameters must be comma-separated");
1341 if (_cpp_save_parameter (pfile, macro, token->val.node))
1345 case CPP_CLOSE_PAREN:
1346 if (prev_ident || macro->paramc == 0)
1349 /* Fall through to pick up the error. */
1353 cpp_error (pfile, DL_ERROR, "parameter name missing");
1360 macro->variadic = 1;
1363 _cpp_save_parameter (pfile, macro,
1364 pfile->spec_nodes.n__VA_ARGS__);
1365 pfile->state.va_args_ok = 1;
1366 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1367 cpp_error (pfile, DL_PEDWARN,
1368 "anonymous variadic macros were introduced in C99");
1370 else if (CPP_OPTION (pfile, pedantic))
1371 cpp_error (pfile, DL_PEDWARN,
1372 "ISO C does not permit named variadic macros");
1374 /* We're at the end, and just expect a closing parenthesis. */
1375 token = _cpp_lex_token (pfile);
1376 if (token->type == CPP_CLOSE_PAREN)
1381 cpp_error (pfile, DL_ERROR, "missing ')' in macro parameter list");
1387 /* Allocate room for a token from a macro's replacement list. */
1389 alloc_expansion_token (pfile, macro)
1393 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1394 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1396 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1399 /* Lex a token from the expansion of MACRO, but mark parameters as we
1400 find them and warn of traditional stringification. */
1402 lex_expansion_token (pfile, macro)
1408 pfile->cur_token = alloc_expansion_token (pfile, macro);
1409 token = _cpp_lex_direct (pfile);
1411 /* Is this a parameter? */
1412 if (token->type == CPP_NAME && token->val.node->arg_index)
1414 token->type = CPP_MACRO_ARG;
1415 token->val.arg_no = token->val.node->arg_index;
1417 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1418 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1419 check_trad_stringification (pfile, macro, &token->val.str);
1425 create_iso_definition (pfile, macro)
1430 const cpp_token *ctoken;
1432 /* Get the first token of the expansion (or the '(' of a
1433 function-like macro). */
1434 ctoken = _cpp_lex_token (pfile);
1436 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1438 bool ok = parse_params (pfile, macro);
1439 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1443 /* Success. Commit the parameter array. */
1444 BUFF_FRONT (pfile->a_buff) = (uchar *) ¯o->params[macro->paramc];
1445 macro->fun_like = 1;
1447 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1448 cpp_error (pfile, DL_PEDWARN,
1449 "ISO C requires whitespace after the macro name");
1451 if (macro->fun_like)
1452 token = lex_expansion_token (pfile, macro);
1455 token = alloc_expansion_token (pfile, macro);
1461 /* Check the stringifying # constraint 6.10.3.2.1 of
1462 function-like macros when lexing the subsequent token. */
1463 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1465 if (token->type == CPP_MACRO_ARG)
1467 token->flags &= ~PREV_WHITE;
1468 token->flags |= STRINGIFY_ARG;
1469 token->flags |= token[-1].flags & PREV_WHITE;
1470 token[-1] = token[0];
1473 /* Let assembler get away with murder. */
1474 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1476 cpp_error (pfile, DL_ERROR,
1477 "'#' is not followed by a macro parameter");
1482 if (token->type == CPP_EOF)
1485 /* Paste operator constraint 6.10.3.3.1. */
1486 if (token->type == CPP_PASTE)
1488 /* Token-paste ##, can appear in both object-like and
1489 function-like macros, but not at the ends. */
1490 if (--macro->count > 0)
1491 token = lex_expansion_token (pfile, macro);
1493 if (macro->count == 0 || token->type == CPP_EOF)
1495 cpp_error (pfile, DL_ERROR,
1496 "'##' cannot appear at either end of a macro expansion");
1500 token[-1].flags |= PASTE_LEFT;
1503 token = lex_expansion_token (pfile, macro);
1506 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1508 /* Don't count the CPP_EOF. */
1511 /* Clear whitespace on first token for warn_of_redefinition(). */
1513 macro->exp.tokens[0].flags &= ~PREV_WHITE;
1515 /* Commit the memory. */
1516 BUFF_FRONT (pfile->a_buff) = (uchar *) ¯o->exp.tokens[macro->count];
1521 /* Parse a macro and save its expansion. Returns non-zero on success. */
1523 _cpp_create_definition (pfile, node)
1531 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1532 macro->line = pfile->directive_line;
1535 macro->variadic = 0;
1538 macro->fun_like = 0;
1539 /* To suppress some diagnostics. */
1540 macro->syshdr = pfile->map->sysp != 0;
1542 if (CPP_OPTION (pfile, traditional))
1543 ok = _cpp_create_trad_definition (pfile, macro);
1546 cpp_token *saved_cur_token = pfile->cur_token;
1548 ok = create_iso_definition (pfile, macro);
1550 /* Restore lexer position because of games lex_expansion_token()
1551 plays lexing the macro. We set the type for SEEN_EOL() in
1554 Longer term we should lex the whole line before coming here,
1555 and just copy the expansion. */
1556 saved_cur_token[-1].type = pfile->cur_token[-1].type;
1557 pfile->cur_token = saved_cur_token;
1559 /* Stop the lexer accepting __VA_ARGS__. */
1560 pfile->state.va_args_ok = 0;
1563 /* Clear the fast argument lookup indices. */
1564 for (i = macro->paramc; i-- > 0; )
1565 macro->params[i]->arg_index = 0;
1570 if (node->type == NT_MACRO)
1572 if (CPP_OPTION (pfile, warn_unused_macros))
1573 _cpp_warn_if_unused_macro (pfile, node, NULL);
1575 if (warn_of_redefinition (pfile, node, macro))
1577 cpp_error_with_line (pfile, DL_PEDWARN, pfile->directive_line, 0,
1578 "\"%s\" redefined", NODE_NAME (node));
1580 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1581 cpp_error_with_line (pfile, DL_PEDWARN,
1582 node->value.macro->line, 0,
1583 "this is the location of the previous definition");
1587 if (node->type != NT_VOID)
1588 _cpp_free_definition (node);
1590 /* Enter definition in hash table. */
1591 node->type = NT_MACRO;
1592 node->value.macro = macro;
1593 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1594 node->flags |= NODE_WARN;
1599 /* Warn if a token in STRING matches one of a function-like MACRO's
1602 check_trad_stringification (pfile, macro, string)
1604 const cpp_macro *macro;
1605 const cpp_string *string;
1607 unsigned int i, len;
1608 const uchar *p, *q, *limit = string->text + string->len;
1610 /* Loop over the string. */
1611 for (p = string->text; p < limit; p = q)
1613 /* Find the start of an identifier. */
1614 while (p < limit && !is_idstart (*p))
1617 /* Find the end of the identifier. */
1619 while (q < limit && is_idchar (*q))
1624 /* Loop over the function macro arguments to see if the
1625 identifier inside the string matches one of them. */
1626 for (i = 0; i < macro->paramc; i++)
1628 const cpp_hashnode *node = macro->params[i];
1630 if (NODE_LEN (node) == len
1631 && !memcmp (p, NODE_NAME (node), len))
1633 cpp_error (pfile, DL_WARNING,
1634 "macro argument \"%s\" would be stringified in traditional C",
1642 /* Returns the name, arguments and expansion of a macro, in a format
1643 suitable to be read back in again, and therefore also for DWARF 2
1644 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1645 Caller is expected to generate the "#define" bit if needed. The
1646 returned text is temporary, and automatically freed later. */
1647 const unsigned char *
1648 cpp_macro_definition (pfile, node)
1650 const cpp_hashnode *node;
1652 unsigned int i, len;
1653 const cpp_macro *macro = node->value.macro;
1654 unsigned char *buffer;
1656 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1658 cpp_error (pfile, DL_ICE,
1659 "invalid hash type %d in cpp_macro_definition", node->type);
1663 /* Calculate length. */
1664 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
1665 if (macro->fun_like)
1667 len += 4; /* "()" plus possible final ".." of named
1668 varargs (we have + 1 below). */
1669 for (i = 0; i < macro->paramc; i++)
1670 len += NODE_LEN (macro->params[i]) + 1; /* "," */
1673 if (CPP_OPTION (pfile, traditional))
1674 len += _cpp_replacement_text_len (macro);
1677 for (i = 0; i < macro->count; i++)
1679 cpp_token *token = ¯o->exp.tokens[i];
1681 if (token->type == CPP_MACRO_ARG)
1682 len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1684 len += cpp_token_len (token); /* Includes room for ' '. */
1685 if (token->flags & STRINGIFY_ARG)
1687 if (token->flags & PASTE_LEFT)
1688 len += 3; /* " ##" */
1692 if (len > pfile->macro_buffer_len)
1694 pfile->macro_buffer = (uchar *) xrealloc (pfile->macro_buffer, len);
1695 pfile->macro_buffer_len = len;
1698 /* Fill in the buffer. Start with the macro name. */
1699 buffer = pfile->macro_buffer;
1700 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1701 buffer += NODE_LEN (node);
1703 /* Parameter names. */
1704 if (macro->fun_like)
1707 for (i = 0; i < macro->paramc; i++)
1709 cpp_hashnode *param = macro->params[i];
1711 if (param != pfile->spec_nodes.n__VA_ARGS__)
1713 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1714 buffer += NODE_LEN (param);
1717 if (i + 1 < macro->paramc)
1718 /* Don't emit a space after the comma here; we're trying
1719 to emit a Dwarf-friendly definition, and the Dwarf spec
1720 forbids spaces in the argument list. */
1722 else if (macro->variadic)
1723 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1728 /* The Dwarf spec requires a space after the macro name, even if the
1729 definition is the empty string. */
1732 if (CPP_OPTION (pfile, traditional))
1733 buffer = _cpp_copy_replacement_text (macro, buffer);
1734 else if (macro->count)
1735 /* Expansion tokens. */
1737 for (i = 0; i < macro->count; i++)
1739 cpp_token *token = ¯o->exp.tokens[i];
1741 if (token->flags & PREV_WHITE)
1743 if (token->flags & STRINGIFY_ARG)
1746 if (token->type == CPP_MACRO_ARG)
1748 len = NODE_LEN (macro->params[token->val.arg_no - 1]);
1750 NODE_NAME (macro->params[token->val.arg_no - 1]), len);
1754 buffer = cpp_spell_token (pfile, token, buffer);
1756 if (token->flags & PASTE_LEFT)
1761 /* Next has PREV_WHITE; see _cpp_create_definition. */
1767 return pfile->macro_buffer;