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 const char *file; /* Defined in file name. */
37 unsigned int line; /* Starting line number. */
38 unsigned int count; /* Number of tokens in expansion. */
39 unsigned short paramc; /* Number of parameters. */
40 unsigned int fun_like : 1; /* If a function-like macro. */
41 unsigned int variadic : 1; /* If a variadic macro. */
42 unsigned int disabled : 1; /* If macro is disabled. */
43 unsigned int syshdr : 1; /* If macro defined in system header. */
46 typedef struct macro_arg macro_arg;
49 cpp_token *first; /* First token in unexpanded argument. */
50 cpp_token *expanded; /* Macro-expanded argument. */
51 cpp_token *stringified; /* Stringified argument. */
52 unsigned int count; /* # of tokens in argument. */
53 unsigned int expanded_count; /* # of tokens in expanded argument. */
56 /* Macro expansion. */
58 static void lock_pools PARAMS ((cpp_reader *));
59 static void unlock_pools PARAMS ((cpp_reader *));
60 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
61 static void builtin_macro PARAMS ((cpp_reader *, cpp_token *));
62 static cpp_context *push_arg_context PARAMS ((cpp_reader *, macro_arg *));
63 static enum cpp_ttype parse_arg PARAMS ((cpp_reader *, macro_arg *, int));
64 static macro_arg *parse_args PARAMS ((cpp_reader *, const cpp_hashnode *));
65 static cpp_context *next_context PARAMS ((cpp_reader *));
66 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
67 static unsigned char *quote_string PARAMS ((unsigned char *,
68 const unsigned char *,
70 static void make_string_token PARAMS ((cpp_pool *, cpp_token *,
71 const U_CHAR *, unsigned int));
72 static void make_number_token PARAMS ((cpp_reader *, cpp_token *, int));
73 static void stringify_arg PARAMS ((cpp_reader *, macro_arg *));
74 static void paste_all_tokens PARAMS ((cpp_reader *, cpp_token *));
75 static int paste_tokens PARAMS ((cpp_reader *, cpp_token *, cpp_token *));
76 static int funlike_invocation_p PARAMS ((cpp_reader *, const cpp_hashnode *,
78 static void replace_args PARAMS ((cpp_reader *, cpp_macro *, macro_arg *,
83 static void save_lookahead_token PARAMS ((cpp_reader *, const cpp_token *));
84 static void take_lookahead_token PARAMS ((cpp_reader *, cpp_token *));
85 static cpp_lookahead *alloc_lookahead PARAMS ((cpp_reader *));
86 static void free_lookahead PARAMS ((cpp_lookahead *));
88 /* #define directive parsing and handling. */
90 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
91 static int warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
93 static int save_parameter PARAMS ((cpp_reader *, cpp_macro *, cpp_hashnode *));
94 static int parse_params PARAMS ((cpp_reader *, cpp_macro *));
95 static void check_trad_stringification PARAMS ((cpp_reader *,
99 /* Allocates a buffer to hold a token's TEXT, and converts TOKEN to a
100 CPP_STRING token containing TEXT in quoted form. */
102 make_string_token (pool, token, text, len)
108 U_CHAR *buf = _cpp_pool_alloc (pool, len * 4);
110 token->type = CPP_STRING;
111 token->val.str.text = buf;
112 token->val.str.len = quote_string (buf, text, len) - buf;
116 /* Allocates and converts a temporary token to a CPP_NUMBER token,
117 evaluating to NUMBER. */
119 make_number_token (pfile, token, number)
124 unsigned char *buf = _cpp_pool_alloc (&pfile->ident_pool, 20);
126 sprintf ((char *) buf, "%d", number);
127 token->type = CPP_NUMBER;
128 token->val.str.text = buf;
129 token->val.str.len = ustrlen (buf);
133 static const char * const monthnames[] =
135 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
136 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
139 /* Handle builtin macros like __FILE__. */
141 builtin_macro (pfile, token)
145 unsigned char flags = ((token->flags & PREV_WHITE) | AVOID_LPASTE);
146 cpp_hashnode *node = token->val.node;
148 switch (node->value.builtin)
154 cpp_buffer *buffer = pfile->buffer;
156 if (node->value.builtin == BT_BASE_FILE)
158 buffer = buffer->prev;
160 name = buffer->nominal_fname;
161 make_string_token (&pfile->ident_pool, token,
162 (const unsigned char *) name, strlen (name));
166 case BT_INCLUDE_LEVEL:
167 /* pfile->include_depth counts the primary source as level 1,
168 but historically __INCLUDE_DEPTH__ has called the primary
170 make_number_token (pfile, token, pfile->include_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 make_number_token (pfile, token, cpp_get_line (pfile)->line);
182 int stdc = (!CPP_IN_SYSTEM_HEADER (pfile)
183 || pfile->spec_nodes.n__STRICT_ANSI__->type != NT_VOID);
184 make_number_token (pfile, token, stdc);
190 if (pfile->date.type == CPP_EOF)
192 /* Allocate __DATE__ and __TIME__ from permanent storage,
193 and save them in pfile so we don't have to do this again.
194 We don't generate these strings at init time because
195 time() and localtime() are very slow on some systems. */
196 time_t tt = time (NULL);
197 struct tm *tb = localtime (&tt);
199 make_string_token (&pfile->ident_pool, &pfile->date,
201 make_string_token (&pfile->ident_pool, &pfile->time,
204 sprintf ((char *) pfile->date.val.str.text, "%s %2d %4d",
205 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
206 sprintf ((char *) pfile->time.val.str.text, "%02d:%02d:%02d",
207 tb->tm_hour, tb->tm_min, tb->tm_sec);
209 *token = node->value.builtin == BT_DATE ? pfile->date: pfile->time;
213 cpp_ice (pfile, "invalid builtin macro \"%s\"", node->name);
217 token->flags = flags;
220 /* Used by cpperror.c to obtain the correct line and column to report
222 const cpp_lexer_pos *
226 return &pfile->lexer_pos;
233 _cpp_lock_pool (&pfile->argument_pool);
240 _cpp_unlock_pool (&pfile->argument_pool);
243 /* Adds backslashes before all backslashes and double quotes appearing
244 in strings. Non-printable characters are converted to octal. */
246 quote_string (dest, src, len)
255 if (c == '\\' || c == '"')
266 sprintf ((char *) dest, "\\%03o", c);
275 /* Convert a token sequence to a single string token according to the
276 rules of the ISO C #-operator. */
278 stringify_arg (pfile, arg)
282 cpp_pool *pool = &pfile->ident_pool;
283 unsigned char *start = POOL_FRONT (pool);
284 unsigned int i, escape_it, total_len = 0, backslash_count = 0;
286 /* Loop, reading in the argument's tokens. */
287 for (i = 0; i < arg->count; i++)
290 const cpp_token *token = &arg->first[i];
291 unsigned int len = cpp_token_len (token);
293 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
294 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
297 /* Worst case is each char is octal. */
299 len++; /* Room for initial space. */
301 dest = &start[total_len];
302 if (dest + len > POOL_LIMIT (pool))
304 _cpp_next_chunk (pool, len, (unsigned char **) &start);
305 dest = &start[total_len];
308 /* No leading white space. */
309 if (token->flags & PREV_WHITE && total_len > 0)
314 unsigned char *buf = (unsigned char *) xmalloc (len);
316 len = cpp_spell_token (pfile, token, buf) - buf;
317 dest = quote_string (dest, buf, len);
321 dest = cpp_spell_token (pfile, token, dest);
322 total_len = dest - start;
324 if (token->type == CPP_OTHER && token->val.c == '\\')
330 /* Ignore the final \ of invalid string literals. */
331 if (backslash_count & 1)
333 cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
337 POOL_COMMIT (pool, total_len);
339 arg->stringified = xnew (cpp_token);
340 arg->stringified->flags = 0;
341 arg->stringified->type = CPP_STRING;
342 arg->stringified->val.str.text = start;
343 arg->stringified->val.str.len = total_len;
346 /* Try to paste two tokens. On success, the LHS becomes the pasted
347 token, and 0 is returned. For failure, we update the flags of the
348 RHS appropriately and return non-zero. */
350 paste_tokens (pfile, lhs, rhs)
352 cpp_token *lhs, *rhs;
358 type = cpp_can_paste (pfile, lhs, rhs, &digraph);
362 /* Mandatory warning for all apart from assembler. */
363 if (CPP_OPTION (pfile, lang) != CLK_ASM)
365 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
366 cpp_token_as_text (pfile, lhs),
367 cpp_token_as_text (pfile, rhs));
369 /* The standard states that behaviour is undefined. By the
370 principle of least surpise, we step back before the RHS, and
371 mark it to prevent macro expansion. Tests in the testsuite
372 rely on clearing PREV_WHITE here, though you could argue we
373 should actually set it. Assembler can have '.' in labels and
374 so requires that we don't insert spaces there. Maybe we should
375 change this to put out a space unless it's assembler. */
376 rhs->flags &= ~PREV_WHITE;
377 rhs->flags |= NO_EXPAND;
381 flags = lhs->flags & ~DIGRAPH;
385 /* Identifiers and numbers need spellings to be pasted. */
386 if (type == CPP_NAME || type == CPP_NUMBER)
388 unsigned int total_len = cpp_token_len (lhs) + cpp_token_len (rhs);
389 unsigned char *result, *end;
391 result = _cpp_pool_alloc (&pfile->ident_pool, total_len + 1);
393 /* Paste the spellings and null terminate. */
394 end = cpp_spell_token (pfile, rhs, cpp_spell_token (pfile, lhs, result));
396 total_len = end - result;
398 if (type == CPP_NAME)
400 lhs->val.node = cpp_lookup (pfile, result, total_len);
401 if (lhs->val.node->flags & NODE_OPERATOR)
404 lhs->type = lhs->val.node->value.operator;
409 lhs->val.str.text = result;
410 lhs->val.str.len = total_len;
413 else if (type == CPP_WCHAR || type == CPP_WSTRING)
414 lhs->val.str = rhs->val.str;
416 /* Set type and flags after pasting spellings. */
423 /* Handles an arbitrarily long sequence of ## operators. This
424 implementation is left-associative, non-recursive, and finishes a
425 paste before handling succeeding ones. If the paste fails, we back
426 up a token to just after the ## operator, with the effect that it
427 appears in the output stream normally. */
429 paste_all_tokens (pfile, lhs)
434 unsigned char orig_flags = lhs->flags;
438 /* Take the token directly from the current context. We can do
439 this, because we are in the replacement list of either an
440 object-like macro, or a function-like macro with arguments
441 inserted. In either case, the constraints to #define
442 guarantee we have at least one more token. */
443 rhs = pfile->context->list.first++;
444 if (paste_tokens (pfile, lhs, rhs))
446 /* We failed. Step back so we read the RHS in next. */
447 pfile->context->list.first--;
451 while (rhs->flags & PASTE_LEFT);
453 /* The pasted token has the PREV_WHITE flag of the LHS, is no longer
454 PASTE_LEFT, and is subject to macro expansion. */
455 lhs->flags &= ~(PREV_WHITE | PASTE_LEFT | NO_EXPAND);
456 lhs->flags |= orig_flags & (PREV_WHITE | AVOID_LPASTE);
459 /* Reads the unexpanded tokens of a macro argument into ARG. VAR_ARGS
460 is non-zero if this is a variadic macro. Returns the type of the
461 token that caused reading to finish. */
462 static enum cpp_ttype
463 parse_arg (pfile, arg, variadic)
465 struct macro_arg *arg;
468 enum cpp_ttype result;
469 unsigned int paren = 0;
472 arg->first = (cpp_token *) POOL_FRONT (&pfile->argument_pool);
473 for (;; arg->count++)
475 cpp_token *token = &arg->first[arg->count];
476 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->argument_pool))
478 _cpp_next_chunk (&pfile->argument_pool, sizeof (cpp_token),
479 (unsigned char **) &arg->first);
480 token = &arg->first[arg->count];
483 /* Newlines in arguments are white space (6.10.3.10). */
484 line = pfile->lexer_pos.output_line;
485 cpp_get_token (pfile, token);
486 if (line != pfile->lexer_pos.output_line)
487 token->flags |= PREV_WHITE;
489 result = token->type;
490 if (result == CPP_OPEN_PAREN)
492 else if (result == CPP_CLOSE_PAREN && paren-- == 0)
494 /* Commas are not terminators within parantheses or variadic. */
495 else if (result == CPP_COMMA && paren == 0 && !variadic)
497 else if (result == CPP_EOF)
498 break; /* Error reported by caller. */
501 /* Commit the memory used to store the arguments. */
502 POOL_COMMIT (&pfile->argument_pool, arg->count * sizeof (cpp_token));
507 /* Parse the arguments making up a macro invocation. */
509 parse_args (pfile, node)
511 const cpp_hashnode *node;
513 cpp_macro *macro = node->value.macro;
514 macro_arg *args, *cur;
518 /* Allocate room for at least one argument, and zero it out. */
519 argc = macro->paramc ? macro->paramc: 1;
520 args = xcnewvec (macro_arg, argc);
522 for (cur = args, argc = 0; ;)
526 type = parse_arg (pfile, cur, argc == macro->paramc && macro->variadic);
527 if (type == CPP_CLOSE_PAREN || type == CPP_EOF)
530 /* Re-use the last argument for excess arguments. */
531 if (argc < macro->paramc)
537 cpp_error (pfile, "unterminated argument list invoking macro \"%s\"",
541 else if (argc < macro->paramc)
543 /* As an extension, a rest argument is allowed to not appear in
544 the invocation at all.
545 e.g. #define debug(format, args...) something
548 This is exactly the same as if there had been an empty rest
549 argument - debug("string", ). */
551 if (argc + 1 == macro->paramc && macro->variadic)
553 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
554 cpp_pedwarn (pfile, "ISO C99 requires rest arguments to be used");
559 "macro \"%s\" requires %u arguments, but only %u given",
560 node->name, macro->paramc, argc);
564 else if (argc > macro->paramc)
566 /* Empty argument to a macro taking no arguments is OK. */
567 if (argc != 1 || cur->count)
570 "macro \"%s\" passed %u arguments, but takes just %u",
571 node->name, argc, macro->paramc);
586 funlike_invocation_p (pfile, node, list)
588 const cpp_hashnode *node;
589 struct toklist *list;
592 cpp_token maybe_paren;
594 cpp_lexer_pos macro_pos;
596 macro_pos = pfile->lexer_pos;
597 pfile->state.parsing_args = 1;
598 pfile->state.prevent_expansion++;
599 orig = pfile->context;
601 cpp_start_lookahead (pfile);
602 cpp_get_token (pfile, &maybe_paren);
603 cpp_stop_lookahead (pfile, maybe_paren.type == CPP_OPEN_PAREN);
604 pfile->state.parsing_args = 2;
606 if (maybe_paren.type == CPP_OPEN_PAREN)
607 args = parse_args (pfile, node);
608 else if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
610 "function-like macro \"%s\" must be used with arguments in traditional C",
613 /* Restore original context. */
614 pfile->context = orig;
615 pfile->state.prevent_expansion--;
616 pfile->state.parsing_args = 0;
618 /* Reset the position in case of failure. If success, the macro's
619 expansion appears where the name would have. */
620 pfile->lexer_pos = macro_pos;
624 if (node->value.macro->paramc > 0)
626 /* Don't save tokens during pre-expansion. */
627 struct cpp_lookahead *la_saved = pfile->la_write;
629 replace_args (pfile, node->value.macro, args, list);
630 pfile->la_write = la_saved;
638 /* Push the context of a macro onto the context stack. TOKEN is the
639 macro name. If we can successfully start expanding the macro,
640 TOKEN is replaced with the first token of the expansion, and we
643 enter_macro_context (pfile, node)
647 cpp_context *context;
648 cpp_macro *macro = node->value.macro;
651 /* Save the position of the outermost macro invocation. */
652 if (!pfile->context->prev)
655 if (macro->fun_like && !funlike_invocation_p (pfile, node, &list))
657 if (!pfile->context->prev)
658 unlock_pools (pfile);
662 if (macro->paramc == 0)
664 list.first = macro->expansion;
665 list.limit = macro->expansion + macro->count;
668 /* Only push a macro context for non-empty replacement lists. */
669 if (list.first != list.limit)
671 context = next_context (pfile);
672 context->list = list;
673 context->macro = macro;
675 /* Disable the macro within its expansion. */
682 /* Move to the next context. Create one if there is none. */
687 cpp_context *prev = pfile->context;
688 cpp_context *result = prev->next;
692 result = xnew (cpp_context);
698 pfile->context = result;
703 replace_args (pfile, macro, args, list)
707 struct toklist *list;
709 unsigned char flags = 0;
710 unsigned int i, total;
711 const cpp_token *src, *limit;
715 src = macro->expansion;
716 limit = src + macro->count;
718 /* First, fully macro-expand arguments, calculating the number of
719 tokens in the final expansion as we go. This ensures that the
720 possible recursive use of argument_pool is fine. */
722 for (; src < limit; src++)
723 if (src->type == CPP_MACRO_ARG)
725 /* We have an argument. If it is not being stringified or
726 pasted it is macro-replaced before insertion. */
727 arg = &args[src->val.arg_no - 1];
729 if (src->flags & STRINGIFY_ARG)
731 if (!arg->stringified)
732 stringify_arg (pfile, arg);
734 else if ((src->flags & PASTE_LEFT)
735 || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
736 total += arg->count - 1;
741 arg->expanded_count = 0;
743 expand_arg (pfile, arg);
745 total += arg->expanded_count - 1;
749 dest = (cpp_token *) _cpp_pool_alloc (&pfile->argument_pool,
750 total * sizeof (cpp_token));
753 for (src = macro->expansion; src < limit; src++)
754 if (src->type == CPP_MACRO_ARG)
757 const cpp_token *from;
759 arg = &args[src->val.arg_no - 1];
760 if (src->flags & STRINGIFY_ARG)
761 from = arg->stringified, count = 1;
762 else if (src->flags & PASTE_LEFT)
763 count = arg->count, from = arg->first;
764 else if (src > macro->expansion && (src[-1].flags & PASTE_LEFT))
766 count = arg->count, from = arg->first;
767 if (dest != list->first)
769 /* GCC has special semantics for , ## b where b is a
770 varargs parameter: the comma disappears if b was
771 given no actual arguments (not merely if b is an
772 empty argument); otherwise pasting is turned off. */
773 if (dest[-1].type == CPP_COMMA
775 && src->val.arg_no == macro->paramc)
780 dest[-1].flags &= ~PASTE_LEFT;
782 /* Count == 0 is the RHS a placemarker case. */
784 dest[-1].flags &= ~PASTE_LEFT;
788 count = arg->expanded_count, from = arg->expanded;
790 /* Count == 0 is the LHS a placemarker case. */
793 memcpy (dest, from, count * sizeof (cpp_token));
795 /* The first token gets PREV_WHITE of the CPP_MACRO_ARG. */
796 dest->flags &= ~PREV_WHITE;
797 dest->flags |= src->flags & PREV_WHITE;
798 dest->flags |= AVOID_LPASTE;
800 /* The last token gets the PASTE_LEFT of the CPP_MACRO_ARG. */
801 dest[count - 1].flags |= src->flags & PASTE_LEFT;
806 /* The token after the argument must avoid an accidental paste. */
807 flags = AVOID_LPASTE;
812 dest->flags |= flags;
819 /* Free the expanded arguments. */
820 for (i = 0; i < macro->paramc; i++)
822 if (args[i].expanded)
823 free (args[i].expanded);
824 if (args[i].stringified)
825 free (args[i].stringified);
829 /* Subroutine of expand_arg to put the unexpanded tokens on the
832 push_arg_context (pfile, arg)
836 cpp_context *context = next_context (pfile);
838 context->list.first = arg->first;
839 context->list.limit = arg->first + arg->count;
845 expand_arg (pfile, arg)
850 unsigned int capacity = 256;
852 /* Loop, reading in the arguments. */
853 arg->expanded = (cpp_token *) xmalloc (capacity * sizeof (cpp_token));
855 push_arg_context (pfile, arg);
858 if (arg->expanded_count >= capacity)
861 arg->expanded = (cpp_token *)
862 xrealloc (arg->expanded, capacity * sizeof (cpp_token));
864 token = &arg->expanded[arg->expanded_count++];
865 cpp_get_token (pfile, token);
867 while (token->type != CPP_EOF);
869 arg->expanded_count--;
871 /* Pop the context we pushed. */
872 pfile->context = pfile->context->prev;
876 _cpp_pop_context (pfile)
879 cpp_context *context = pfile->context;
881 pfile->context = context->prev;
882 if (!pfile->context->prev && !pfile->state.parsing_args)
883 unlock_pools (pfile);
885 /* Re-enable a macro, temporarily if parsing_args, when leaving its
887 context->macro->disabled = 0;
890 /* Eternal routine to get a token. Also used nearly everywhere
891 internally, except for places where we know we can safely call
892 the lexer directly, such as lexing a directive name.
894 Macro expansions and directives are transparently handled,
895 including entering included files. Thus tokens are post-macro
896 expansion, and after any intervening directives. External callers
897 see CPP_EOF only at EOF. Internal callers also see it when meeting
898 a directive inside a macro call, when at the end of a directive and
899 state.in_directive is still 1, and at the end of argument
902 cpp_get_token (pfile, token)
908 cpp_context *context = pfile->context;
911 take_lookahead_token (pfile, token);
912 /* Context->prev == 0 <=> base context. */
913 else if (!context->prev)
914 _cpp_lex_token (pfile, token);
915 else if (context->list.first != context->list.limit)
917 *token = *context->list.first++;
918 token->flags |= pfile->buffer->saved_flags;
919 pfile->buffer->saved_flags = 0;
920 /* PASTE_LEFT tokens can only appear in macro expansions. */
921 if (token->flags & PASTE_LEFT)
923 paste_all_tokens (pfile, token);
924 pfile->buffer->saved_flags = AVOID_LPASTE;
931 /* Avoid accidental paste at the end of a macro. */
932 pfile->buffer->saved_flags |= AVOID_LPASTE;
933 _cpp_pop_context (pfile);
936 /* End of argument pre-expansion. */
937 token->type = CPP_EOF;
942 if (token->type != CPP_NAME)
945 /* Handle macros and the _Pragma operator. */
946 if (token->val.node->type == NT_MACRO
947 && !pfile->state.prevent_expansion
948 && !(token->flags & NO_EXPAND))
950 cpp_hashnode *node = token->val.node;
952 /* Macros invalidate controlling macros. */
953 pfile->mi_state = MI_FAILED;
955 if (node->flags & NODE_BUILTIN)
957 builtin_macro (pfile, token);
958 pfile->buffer->saved_flags = AVOID_LPASTE;
962 if (node->value.macro->disabled)
963 token->flags |= NO_EXPAND;
964 else if (enter_macro_context (pfile, node))
966 /* Pass AVOID_LPASTE and our PREV_WHITE to next token. */
967 pfile->buffer->saved_flags = ((token->flags & PREV_WHITE)
973 /* Don't interpret _Pragma within directives. The standard is
974 not clear on this, but to me this makes most sense. */
975 if (token->val.node != pfile->spec_nodes.n__Pragma
976 || pfile->state.in_directive)
979 /* Handle it, and loop back for another token. MI is cleared
980 since this token came from either the lexer or a macro. */
981 _cpp_do__Pragma (pfile);
985 save_lookahead_token (pfile, token);
988 /* Returns true if we're expanding an object-like macro that was
989 defined in a system header. Just checks the macro at the top of
990 the stack. Used for diagnostic suppression. */
992 cpp_sys_macro_p (pfile)
995 cpp_macro *macro = pfile->context->macro;
997 return macro && macro->syshdr;
1000 /* Read each token in, until EOF. Directives are transparently
1003 cpp_scan_buffer_nooutput (pfile, all_buffers)
1008 cpp_buffer *buffer = all_buffers ? 0: pfile->buffer->prev;
1012 cpp_get_token (pfile, &token);
1013 while (token.type != CPP_EOF);
1014 while (cpp_pop_buffer (pfile) != buffer);
1017 /* Lookahead handling. */
1020 save_lookahead_token (pfile, token)
1022 const cpp_token *token;
1024 if (token->type != CPP_EOF)
1026 cpp_lookahead *la = pfile->la_write;
1027 cpp_token_with_pos *twp;
1029 if (la->count == la->cap)
1031 la->cap += la->cap + 8;
1032 la->tokens = (cpp_token_with_pos *)
1033 xrealloc (la->tokens, la->cap * sizeof (cpp_token_with_pos));
1036 twp = &la->tokens[la->count++];
1037 twp->token = *token;
1038 twp->pos = *cpp_get_line (pfile);
1043 take_lookahead_token (pfile, token)
1047 cpp_lookahead *la = pfile->la_read;
1048 cpp_token_with_pos *twp = &la->tokens[la->cur];
1050 *token = twp->token;
1051 pfile->lexer_pos = twp->pos;
1053 if (++la->cur == la->count)
1054 _cpp_release_lookahead (pfile);
1057 /* Moves the lookahead at the front of the read list to the free store. */
1059 _cpp_release_lookahead (pfile)
1062 cpp_lookahead *la = pfile->la_read;
1064 pfile->la_read = la->next;
1065 la->next = pfile->la_unused;
1066 pfile->la_unused = la;
1067 unlock_pools (pfile);
1070 /* Take a new lookahead from the free store, or allocate one if none. */
1071 static cpp_lookahead *
1072 alloc_lookahead (pfile)
1075 cpp_lookahead *la = pfile->la_unused;
1078 pfile->la_unused = la->next;
1081 la = xnew (cpp_lookahead);
1086 la->cur = la->count = 0;
1090 /* Free memory associated with a lookahead list. */
1096 free ((PTR) la->tokens);
1100 /* Free all the lookaheads of a cpp_reader. */
1102 _cpp_free_lookaheads (pfile)
1105 cpp_lookahead *la, *lan;
1108 free_lookahead (pfile->la_read);
1109 if (pfile->la_write)
1110 free_lookahead (pfile->la_write);
1112 for (la = pfile->la_unused; la; la = lan)
1115 free_lookahead (la);
1119 /* Allocate a lookahead and move it to the front of the write list. */
1121 cpp_start_lookahead (pfile)
1124 cpp_lookahead *la = alloc_lookahead (pfile);
1126 la->next = pfile->la_write;
1127 pfile->la_write = la;
1129 la->pos = *cpp_get_line (pfile);
1131 /* Don't allow memory pools to be re-used whilst we're reading ahead. */
1135 /* Stop reading ahead - either step back, or drop the read ahead. */
1137 cpp_stop_lookahead (pfile, drop)
1141 cpp_lookahead *la = pfile->la_write;
1143 pfile->la_write = la->next;
1144 la->next = pfile->la_read;
1145 pfile->la_read = la;
1147 if (drop || la->count == 0)
1148 _cpp_release_lookahead (pfile);
1150 pfile->lexer_pos = la->pos;
1153 /* Push a single token back to the front of the queue. Only to be
1154 used by cpplib, and only then when necessary. POS is the position
1155 to report for the preceding token. */
1157 _cpp_push_token (pfile, token, pos)
1159 const cpp_token *token;
1160 const cpp_lexer_pos *pos;
1162 cpp_start_lookahead (pfile);
1163 save_lookahead_token (pfile, token);
1164 cpp_stop_lookahead (pfile, 0);
1165 pfile->lexer_pos = *pos;
1168 /* #define directive parsing and handling. */
1170 /* Returns non-zero if a macro redefinition warning is required. */
1172 warn_of_redefinition (pfile, node, macro2)
1174 const cpp_hashnode *node;
1175 const cpp_macro *macro2;
1177 const cpp_macro *macro1;
1180 /* Some redefinitions need to be warned about regardless. */
1181 if (node->flags & NODE_WARN)
1184 if (! CPP_PEDANTIC (pfile))
1187 /* Redefinition of a macro is allowed if and only if the old and new
1188 definitions are the same. (6.10.3 paragraph 2). */
1189 macro1 = node->value.macro;
1191 /* The quick failures. */
1192 if (macro1->count != macro2->count
1193 || macro1->paramc != macro2->paramc
1194 || macro1->fun_like != macro2->fun_like
1195 || macro1->variadic != macro2->variadic)
1198 /* Check each token. */
1199 for (i = 0; i < macro1->count; i++)
1200 if (! _cpp_equiv_tokens (¯o1->expansion[i], ¯o2->expansion[i]))
1203 /* Check parameter spellings. */
1204 for (i = 0; i < macro1->paramc; i++)
1205 if (macro1->params[i] != macro2->params[i])
1211 /* Free the definition of hashnode H. */
1214 _cpp_free_definition (h)
1217 /* Macros and assertions no longer have anything to free. */
1219 /* Clear builtin flag in case of redefinition. */
1220 h->flags &= ~NODE_BUILTIN;
1224 save_parameter (pfile, macro, node)
1229 cpp_hashnode **dest;
1231 /* Constraint 6.10.3.6 - duplicate parameter names. */
1232 if (node->arg_index)
1234 cpp_error (pfile, "duplicate macro parameter \"%s\"", node->name);
1238 dest = ¯o->params[macro->paramc];
1240 /* Check we have room for the parameters. */
1241 if ((unsigned char *) (dest + 1) >= POOL_LIMIT (&pfile->macro_pool))
1243 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_hashnode *),
1244 (unsigned char **) ¯o->params);
1245 dest = ¯o->params[macro->paramc];
1249 node->arg_index = ++macro->paramc;
1254 parse_params (pfile, macro)
1259 unsigned int prev_ident = 0;
1261 macro->params = (cpp_hashnode **) POOL_FRONT (&pfile->macro_pool);
1264 _cpp_lex_token (pfile, &token);
1269 cpp_error (pfile, "\"%s\" may not appear in macro parameter list",
1270 cpp_token_as_text (pfile, &token));
1276 cpp_error (pfile, "macro parameters must be comma-separated");
1281 if (save_parameter (pfile, macro, token.val.node))
1285 case CPP_CLOSE_PAREN:
1286 if (prev_ident || macro->paramc == 0)
1289 /* Fall through to pick up the error. */
1293 cpp_error (pfile, "parameter name missing");
1300 macro->variadic = 1;
1303 save_parameter (pfile, macro, pfile->spec_nodes.n__VA_ARGS__);
1304 pfile->state.va_args_ok = 1;
1305 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1307 "anonymous variadic macros were introduced in C99");
1309 else if (CPP_OPTION (pfile, pedantic))
1310 cpp_pedwarn (pfile, "ISO C does not permit named variadic macros");
1312 /* We're at the end, and just expect a closing parenthesis. */
1313 _cpp_lex_token (pfile, &token);
1314 if (token.type == CPP_CLOSE_PAREN)
1319 cpp_error (pfile, "missing ')' in macro parameter list");
1323 /* Success. Commit the parameter array. */
1324 POOL_COMMIT (&pfile->macro_pool,
1325 macro->paramc * sizeof (cpp_hashnode *));
1330 /* Lex a token from a macro's replacement list. Translate it to a
1331 CPP_MACRO_ARG if appropriate. */
1333 lex_expansion_token (pfile, macro)
1337 cpp_token *token = ¯o->expansion[macro->count];
1339 /* Check we have room for the token. */
1340 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->macro_pool))
1342 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_token),
1343 (unsigned char **) ¯o->expansion);
1344 token = ¯o->expansion[macro->count];
1348 _cpp_lex_token (pfile, token);
1350 /* Is this an argument? */
1351 if (token->type == CPP_NAME && token->val.node->arg_index)
1353 token->type = CPP_MACRO_ARG;
1354 token->val.arg_no = token->val.node->arg_index;
1356 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1357 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1358 check_trad_stringification (pfile, macro, &token->val.str);
1363 /* Parse a macro and save its expansion. Returns non-zero on success. */
1365 _cpp_create_definition (pfile, node)
1371 unsigned int i, ok = 1;
1373 macro = (cpp_macro *) _cpp_pool_alloc (&pfile->macro_pool,
1374 sizeof (cpp_macro));
1375 macro->file = pfile->buffer->nominal_fname;
1376 macro->line = pfile->directive_pos.line;
1379 macro->fun_like = 0;
1380 macro->variadic = 0;
1382 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1384 /* Get the first token of the expansion (or the '(' of a
1385 function-like macro). */
1386 token = lex_expansion_token (pfile, macro);
1387 if (token->type == CPP_OPEN_PAREN && !(token->flags & PREV_WHITE))
1389 if (!(ok = parse_params (pfile, macro)))
1392 macro->fun_like = 1;
1393 /* Some of the pool may have been used for the parameter store. */
1394 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1395 token = lex_expansion_token (pfile, macro);
1397 else if (token->type != CPP_EOF && !(token->flags & PREV_WHITE))
1398 cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
1400 /* Setting it here means we don't catch leading comments. */
1401 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
1405 /* Check the stringifying # constraint 6.10.3.2.1 of
1406 function-like macros when lexing the subsequent token. */
1407 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1409 if (token->type == CPP_MACRO_ARG)
1411 token->flags &= ~PREV_WHITE;
1412 token->flags |= STRINGIFY_ARG;
1413 token->flags |= token[-1].flags & PREV_WHITE;
1414 token[-1] = token[0];
1417 /* Let assembler get away with murder. */
1418 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1421 cpp_error (pfile, "'#' is not followed by a macro parameter");
1426 if (token->type == CPP_EOF)
1429 /* Paste operator constraint 6.10.3.3.1. */
1430 if (token->type == CPP_PASTE)
1432 /* Token-paste ##, can appear in both object-like and
1433 function-like macros, but not at the ends. */
1434 if (--macro->count > 0)
1435 token = lex_expansion_token (pfile, macro);
1437 if (macro->count == 0 || token->type == CPP_EOF)
1441 "'##' cannot appear at either end of a macro expansion");
1445 token[-1].flags |= PASTE_LEFT;
1446 /* Give it a PREV_WHITE for -dM etc. */
1447 token->flags |= PREV_WHITE;
1450 token = lex_expansion_token (pfile, macro);
1453 /* Don't count the CPP_EOF. */
1456 /* Clear the whitespace flag from the leading token. */
1457 macro->expansion[0].flags &= ~PREV_WHITE;
1459 /* Implement the macro-defined-to-itself optimisation. */
1460 macro->disabled = (macro->count == 1 && !macro->fun_like
1461 && macro->expansion[0].type == CPP_NAME
1462 && macro->expansion[0].val.node == node);
1464 /* To suppress some diagnostics. */
1465 macro->syshdr = pfile->buffer->sysp != 0;
1467 /* Commit the memory. */
1468 POOL_COMMIT (&pfile->macro_pool, macro->count * sizeof (cpp_token));
1470 if (node->type != NT_VOID)
1472 if (warn_of_redefinition (pfile, node, macro))
1474 cpp_pedwarn_with_line (pfile, pfile->directive_pos.line,
1475 pfile->directive_pos.col,
1476 "\"%s\" redefined", node->name);
1478 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1479 cpp_pedwarn_with_file_and_line (pfile,
1480 node->value.macro->file,
1481 node->value.macro->line, 1,
1482 "this is the location of the previous definition");
1484 _cpp_free_definition (node);
1487 /* Enter definition in hash table. */
1488 node->type = NT_MACRO;
1489 node->value.macro = macro;
1490 if (! ustrncmp (node->name, DSC ("__STDC_")))
1491 node->flags |= NODE_WARN;
1495 /* Stop the lexer accepting __VA_ARGS__. */
1496 pfile->state.va_args_ok = 0;
1498 /* Clear the fast argument lookup indices. */
1499 for (i = macro->paramc; i-- > 0; )
1500 macro->params[i]->arg_index = 0;
1505 /* Warn if a token in `string' matches one of the function macro
1506 arguments in `info'. This function assumes that the macro is a
1507 function macro and not an object macro. */
1509 check_trad_stringification (pfile, macro, string)
1511 const cpp_macro *macro;
1512 const cpp_string *string;
1514 unsigned int i, len;
1515 const U_CHAR *p, *q, *limit = string->text + string->len;
1517 /* Loop over the string. */
1518 for (p = string->text; p < limit; p = q)
1520 /* Find the start of an identifier. */
1521 while (p < limit && !is_idstart (*p))
1524 /* Find the end of the identifier. */
1526 while (q < limit && is_idchar (*q))
1531 /* Loop over the function macro arguments to see if the
1532 identifier inside the string matches one of them. */
1533 for (i = 0; i < macro->paramc; i++)
1535 const cpp_hashnode *node = macro->params[i];
1537 if (node->length == len && !memcmp (p, node->name, len))
1540 "macro argument \"%s\" would be stringified with -traditional.",
1548 /* Returns the expansion of a macro, in a format suitable to be read
1549 back in again, and therefore also for DWARF 2 debugging info.
1550 Caller is expected to generate the "#define NAME" bit. The
1551 returned text is temporary, and automatically freed later. */
1553 const unsigned char *
1554 cpp_macro_definition (pfile, node)
1556 const cpp_hashnode *node;
1558 unsigned int i, len;
1559 const cpp_macro *macro = node->value.macro;
1560 unsigned char *buffer;
1562 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1564 cpp_ice (pfile, "invalid hash type %d in dump_definition", node->type);
1568 /* Calculate length. */
1570 if (macro->fun_like)
1572 len += 3; /* "()" plus possible final "." of ellipsis. */
1573 for (i = 0; i < macro->paramc; i++)
1574 len += macro->params[i]->length + 2; /* ", " */
1577 for (i = 0; i < macro->count; i++)
1579 cpp_token *token = ¯o->expansion[i];
1581 if (token->type == CPP_MACRO_ARG)
1582 len += macro->params[token->val.arg_no - 1]->length;
1584 len += cpp_token_len (token); /* Includes room for ' '. */
1585 if (token->flags & STRINGIFY_ARG)
1587 if (token->flags & PASTE_LEFT)
1588 len += 3; /* " ##" */
1591 if (len > pfile->macro_buffer_len)
1593 pfile->macro_buffer = (U_CHAR *) xrealloc (pfile->macro_buffer, len);
1594 pfile->macro_buffer_len = len;
1596 buffer = pfile->macro_buffer;
1598 /* Parameter names. */
1599 if (macro->fun_like)
1602 for (i = 0; i < macro->paramc; i++)
1604 cpp_hashnode *param = macro->params[i];
1606 if (param != pfile->spec_nodes.n__VA_ARGS__)
1608 memcpy (buffer, param->name, param->length);
1609 buffer += param->length;
1612 if (i + 1 < macro->paramc)
1613 *buffer++ = ',', *buffer++ = ' ';
1614 else if (macro->variadic)
1615 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1620 /* Expansion tokens. */
1624 for (i = 0; i < macro->count; i++)
1626 cpp_token *token = ¯o->expansion[i];
1628 if (token->flags & PREV_WHITE)
1630 if (token->flags & STRINGIFY_ARG)
1633 if (token->type == CPP_MACRO_ARG)
1635 len = macro->params[token->val.arg_no - 1]->length;
1636 memcpy (buffer, macro->params[token->val.arg_no - 1]->name, len);
1640 buffer = cpp_spell_token (pfile, token, buffer);
1642 if (token->flags & PASTE_LEFT)
1647 /* Next has PREV_WHITE; see _cpp_create_definition. */
1653 return pfile->macro_buffer;