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. */
32 #ifndef STDC_0_IN_SYSTEM_HEADERS
33 #define STDC_0_IN_SYSTEM_HEADERS 0 /* Boolean macro. */
38 cpp_hashnode **params; /* Parameters, if any. */
39 cpp_token *expansion; /* First token of replacement list. */
40 const char *file; /* Defined in file name. */
41 unsigned int line; /* Starting line number. */
42 unsigned int count; /* Number of tokens in expansion. */
43 unsigned short paramc; /* Number of parameters. */
44 unsigned int fun_like : 1; /* If a function-like macro. */
45 unsigned int variadic : 1; /* If a variadic macro. */
46 unsigned int disabled : 1; /* If macro is disabled. */
49 typedef struct macro_arg macro_arg;
52 cpp_token *first; /* First token in unexpanded argument. */
53 cpp_token *expanded; /* Macro-expanded argument. */
54 cpp_token *stringified; /* Stringified argument. */
55 unsigned int count; /* # of tokens in argument. */
56 unsigned int expanded_count; /* # of tokens in expanded argument. */
59 /* Macro expansion. */
61 static void lock_pools PARAMS ((cpp_reader *));
62 static void unlock_pools PARAMS ((cpp_reader *));
63 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
64 static void builtin_macro PARAMS ((cpp_reader *, cpp_token *));
65 static cpp_context *push_arg_context PARAMS ((cpp_reader *, macro_arg *));
66 static enum cpp_ttype parse_arg PARAMS ((cpp_reader *, macro_arg *, int));
67 static macro_arg *parse_args PARAMS ((cpp_reader *, const cpp_hashnode *));
68 static cpp_context *next_context PARAMS ((cpp_reader *));
69 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
70 static unsigned char *quote_string PARAMS ((unsigned char *,
71 const unsigned char *,
73 static void make_string_token PARAMS ((cpp_pool *, cpp_token *,
74 const U_CHAR *, unsigned int));
75 static void make_number_token PARAMS ((cpp_reader *, cpp_token *, int));
76 static void stringify_arg PARAMS ((cpp_reader *, macro_arg *));
77 static void paste_all_tokens PARAMS ((cpp_reader *, cpp_token *));
78 static int paste_tokens PARAMS ((cpp_reader *, cpp_token *, cpp_token *));
79 static int funlike_invocation_p PARAMS ((cpp_reader *, const cpp_hashnode *,
81 static void replace_args PARAMS ((cpp_reader *, cpp_macro *, macro_arg *,
86 static void save_lookahead_token PARAMS ((cpp_reader *, const cpp_token *));
87 static void take_lookahead_token PARAMS ((cpp_reader *, cpp_token *));
88 static cpp_lookahead *alloc_lookahead PARAMS ((cpp_reader *));
89 static void free_lookahead PARAMS ((cpp_lookahead *));
91 /* #define directive parsing and handling. */
93 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
94 static int check_macro_redefinition PARAMS ((cpp_reader *,
97 static int save_parameter PARAMS ((cpp_reader *, cpp_macro *, cpp_hashnode *));
98 static int parse_params PARAMS ((cpp_reader *, cpp_macro *));
99 static void check_trad_stringification PARAMS ((cpp_reader *,
101 const cpp_string *));
103 /* Allocates a buffer to hold a token's TEXT, and converts TOKEN to a
104 CPP_STRING token containing TEXT in quoted form. */
106 make_string_token (pool, token, text, len)
112 U_CHAR *buf = _cpp_pool_alloc (pool, len * 4);
114 token->type = CPP_STRING;
115 token->val.str.text = buf;
116 token->val.str.len = quote_string (buf, text, len) - buf;
120 /* Allocates and converts a temporary token to a CPP_NUMBER token,
121 evaluating to NUMBER. */
123 make_number_token (pfile, token, number)
128 unsigned char *buf = _cpp_pool_alloc (&pfile->ident_pool, 20);
130 sprintf ((char *) buf, "%d", number);
131 token->type = CPP_NUMBER;
132 token->val.str.text = buf;
133 token->val.str.len = ustrlen (buf);
137 static const char * const monthnames[] =
139 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
140 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
143 /* Handle builtin macros like __FILE__. */
145 builtin_macro (pfile, token)
149 unsigned char flags = ((token->flags & PREV_WHITE) | AVOID_LPASTE);
150 cpp_hashnode *node = token->val.node;
152 switch (node->value.builtin)
158 cpp_buffer *buffer = pfile->buffer;
160 if (node->value.builtin == BT_BASE_FILE)
162 buffer = buffer->prev;
164 name = buffer->nominal_fname;
165 make_string_token (&pfile->ident_pool, token,
166 (const unsigned char *) name, strlen (name));
170 case BT_INCLUDE_LEVEL:
171 /* pfile->include_depth counts the primary source as level 1,
172 but historically __INCLUDE_DEPTH__ has called the primary
174 make_number_token (pfile, token, pfile->include_depth - 1);
178 /* If __LINE__ is embedded in a macro, it must expand to the
179 line of the macro's invocation, not its definition.
180 Otherwise things like assert() will not work properly. */
181 make_number_token (pfile, token, cpp_get_line (pfile)->line);
188 if (STDC_0_IN_SYSTEM_HEADERS && CPP_IN_SYSTEM_HEADER (pfile)
189 && pfile->spec_nodes.n__STRICT_ANSI__->type == NT_VOID)
191 make_number_token (pfile, token, stdc);
197 if (pfile->date.type == CPP_EOF)
199 /* Allocate __DATE__ and __TIME__ from permanent storage,
200 and save them in pfile so we don't have to do this again.
201 We don't generate these strings at init time because
202 time() and localtime() are very slow on some systems. */
203 time_t tt = time (NULL);
204 struct tm *tb = localtime (&tt);
206 make_string_token (&pfile->ident_pool, &pfile->date,
208 make_string_token (&pfile->ident_pool, &pfile->time,
211 sprintf ((char *) pfile->date.val.str.text, "%s %2d %4d",
212 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
213 sprintf ((char *) pfile->time.val.str.text, "%02d:%02d:%02d",
214 tb->tm_hour, tb->tm_min, tb->tm_sec);
216 *token = node->value.builtin == BT_DATE ? pfile->date: pfile->time;
220 make_number_token (pfile, token, SUPPORTS_ONE_ONLY);
224 cpp_ice (pfile, "invalid builtin macro \"%s\"", node->name);
228 token->flags = flags;
231 /* Used by cpperror.c to obtain the correct line and column to report
233 const cpp_lexer_pos *
237 return &pfile->lexer_pos;
244 _cpp_lock_pool (&pfile->argument_pool);
251 _cpp_unlock_pool (&pfile->argument_pool);
254 /* Adds backslashes before all backslashes and double quotes appearing
255 in strings. Non-printable characters are converted to octal. */
257 quote_string (dest, src, len)
266 if (c == '\\' || c == '"')
277 sprintf ((char *) dest, "\\%03o", c);
286 /* Convert a token sequence to a single string token according to the
287 rules of the ISO C #-operator. */
289 stringify_arg (pfile, arg)
293 cpp_pool *pool = &pfile->ident_pool;
294 unsigned char *start = POOL_FRONT (pool);
295 unsigned int i, escape_it, total_len = 0, backslash_count = 0;
297 /* Loop, reading in the argument's tokens. */
298 for (i = 0; i < arg->count; i++)
301 const cpp_token *token = &arg->first[i];
302 unsigned int len = cpp_token_len (token);
304 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
305 || token->type == CPP_CHAR || token->type == CPP_WCHAR
306 || token->type == CPP_OSTRING);
309 /* Worst case is each char is octal. */
311 len++; /* Room for initial space. */
313 dest = &start[total_len];
314 if (dest + len > POOL_LIMIT (pool))
316 _cpp_next_chunk (pool, len, (unsigned char **) &start);
317 dest = &start[total_len];
320 /* No leading white space. */
321 if (token->flags & PREV_WHITE && total_len > 0)
326 unsigned char *buf = (unsigned char *) xmalloc (len);
328 len = cpp_spell_token (pfile, token, buf) - buf;
329 dest = quote_string (dest, buf, len);
333 dest = cpp_spell_token (pfile, token, dest);
334 total_len = dest - start;
336 if (token->type == CPP_OTHER && token->val.c == '\\')
342 /* Ignore the final \ of invalid string literals. */
343 if (backslash_count & 1)
345 cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
349 POOL_COMMIT (pool, total_len);
351 arg->stringified = xnew (cpp_token);
352 arg->stringified->flags = 0;
353 arg->stringified->type = CPP_STRING;
354 arg->stringified->val.str.text = start;
355 arg->stringified->val.str.len = total_len;
358 /* Try to paste two tokens. On success, the LHS becomes the pasted
359 token, and 0 is returned. For failure, we update the flags of the
360 RHS appropriately and return non-zero. */
362 paste_tokens (pfile, lhs, rhs)
364 cpp_token *lhs, *rhs;
370 type = cpp_can_paste (pfile, lhs, rhs, &digraph);
374 /* Mandatory warning for all apart from assembler. */
375 if (CPP_OPTION (pfile, lang) != CLK_ASM)
377 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
378 cpp_token_as_text (pfile, lhs),
379 cpp_token_as_text (pfile, rhs));
381 /* The standard states that behaviour is undefined. By the
382 principle of least surpise, we step back before the RHS, and
383 mark it to prevent macro expansion. Tests in the testsuite
384 rely on clearing PREV_WHITE here, though you could argue we
385 should actually set it. Assembler can have '.' in labels and
386 so requires that we don't insert spaces there. Maybe we should
387 change this to put out a space unless it's assembler. */
388 rhs->flags &= ~PREV_WHITE;
389 rhs->flags |= NO_EXPAND;
393 flags = lhs->flags & ~DIGRAPH;
397 /* Identifiers and numbers need spellings to be pasted. */
398 if (type == CPP_NAME || type == CPP_NUMBER)
400 unsigned int total_len = cpp_token_len (lhs) + cpp_token_len (rhs);
401 unsigned char *result, *end;
403 result = _cpp_pool_alloc (&pfile->ident_pool, total_len + 1);
405 /* Paste the spellings and null terminate. */
406 end = cpp_spell_token (pfile, rhs, cpp_spell_token (pfile, lhs, result));
408 total_len = end - result;
410 if (type == CPP_NAME)
412 lhs->val.node = cpp_lookup (pfile, result, total_len);
413 if (lhs->val.node->flags & NODE_OPERATOR)
416 lhs->type = lhs->val.node->value.operator;
421 lhs->val.str.text = result;
422 lhs->val.str.len = total_len;
425 else if (type == CPP_WCHAR || type == CPP_WSTRING)
426 lhs->val.str = rhs->val.str;
428 /* Set type and flags after pasting spellings. */
435 /* Handles an arbitrarily long sequence of ## operators. This
436 implementation is left-associative, non-recursive, and finishes a
437 paste before handling succeeding ones. If the paste fails, we back
438 up a token to just after the ## operator, with the effect that it
439 appears in the output stream normally. */
441 paste_all_tokens (pfile, lhs)
446 unsigned char orig_flags = lhs->flags;
450 /* Take the token directly from the current context. We can do
451 this, because we are in the replacement list of either an
452 object-like macro, or a function-like macro with arguments
453 inserted. In either case, the constraints to #define
454 guarantee we have at least one more token. */
455 rhs = pfile->context->list.first++;
456 if (paste_tokens (pfile, lhs, rhs))
458 /* We failed. Step back so we read the RHS in next. */
459 pfile->context->list.first--;
463 while (rhs->flags & PASTE_LEFT);
465 /* The pasted token has the PREV_WHITE flag of the LHS, is no longer
466 PASTE_LEFT, and is subject to macro expansion. */
467 lhs->flags &= ~(PREV_WHITE | PASTE_LEFT | NO_EXPAND);
468 lhs->flags |= orig_flags & (PREV_WHITE | AVOID_LPASTE);
471 /* Reads the unexpanded tokens of a macro argument into ARG. VAR_ARGS
472 is non-zero if this is a variadic macro. Returns the type of the
473 token that caused reading to finish. */
474 static enum cpp_ttype
475 parse_arg (pfile, arg, variadic)
477 struct macro_arg *arg;
480 enum cpp_ttype result;
481 unsigned int paren = 0;
484 arg->first = (cpp_token *) POOL_FRONT (&pfile->argument_pool);
485 for (;; arg->count++)
487 cpp_token *token = &arg->first[arg->count];
488 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->argument_pool))
490 _cpp_next_chunk (&pfile->argument_pool, sizeof (cpp_token),
491 (unsigned char **) &arg->first);
492 token = &arg->first[arg->count];
495 /* Newlines in arguments are white space (6.10.3.10). */
496 line = pfile->lexer_pos.output_line;
497 cpp_get_token (pfile, token);
498 if (line != pfile->lexer_pos.output_line)
499 token->flags |= PREV_WHITE;
501 result = token->type;
502 if (result == CPP_OPEN_PAREN)
504 else if (result == CPP_CLOSE_PAREN && paren-- == 0)
506 /* Commas are not terminators within parantheses or variadic. */
507 else if (result == CPP_COMMA && paren == 0 && !variadic)
509 else if (result == CPP_EOF)
510 break; /* Error reported by caller. */
513 /* Commit the memory used to store the arguments. */
514 POOL_COMMIT (&pfile->argument_pool, arg->count * sizeof (cpp_token));
519 /* Parse the arguments making up a macro invocation. */
521 parse_args (pfile, node)
523 const cpp_hashnode *node;
525 cpp_macro *macro = node->value.macro;
526 macro_arg *args, *cur;
530 /* Allocate room for at least one argument, and zero it out. */
531 argc = macro->paramc ? macro->paramc: 1;
532 args = xcnewvec (macro_arg, argc);
534 for (cur = args, argc = 0; ;)
538 type = parse_arg (pfile, cur, argc == macro->paramc && macro->variadic);
539 if (type == CPP_CLOSE_PAREN || type == CPP_EOF)
542 /* Re-use the last argument for excess arguments. */
543 if (argc < macro->paramc)
549 cpp_error (pfile, "unterminated argument list invoking macro \"%s\"",
553 else if (argc < macro->paramc)
555 /* As an extension, a rest argument is allowed to not appear in
556 the invocation at all.
557 e.g. #define debug(format, args...) something
560 This is exactly the same as if there had been an empty rest
561 argument - debug("string", ). */
563 if (argc + 1 == macro->paramc && macro->variadic)
565 if (CPP_PEDANTIC (pfile))
566 cpp_pedwarn (pfile, "ISO C99 requires rest arguments to be used");
571 "macro \"%s\" requires %u arguments, but only %u given",
572 node->name, macro->paramc, argc);
576 else if (argc > macro->paramc)
578 /* Empty argument to a macro taking no arguments is OK. */
579 if (argc != 1 || cur->count)
582 "macro \"%s\" passed %u arguments, but takes just %u",
583 node->name, argc, macro->paramc);
598 funlike_invocation_p (pfile, node, list)
600 const cpp_hashnode *node;
601 struct toklist *list;
604 cpp_token maybe_paren;
606 cpp_lexer_pos macro_pos;
608 macro_pos = pfile->lexer_pos;
609 pfile->state.parsing_args = 1;
610 pfile->state.prevent_expansion++;
611 orig = pfile->context;
613 cpp_start_lookahead (pfile);
614 cpp_get_token (pfile, &maybe_paren);
615 cpp_stop_lookahead (pfile, maybe_paren.type == CPP_OPEN_PAREN);
617 if (maybe_paren.type == CPP_OPEN_PAREN)
618 args = parse_args (pfile, node);
619 else if (CPP_WTRADITIONAL (pfile))
621 "function-like macro \"%s\" must be used with arguments in traditional C",
624 /* Restore original context. */
625 pfile->context = orig;
626 pfile->state.prevent_expansion--;
627 pfile->state.parsing_args = 0;
631 /* The macro's expansion appears where the name would have. */
632 pfile->lexer_pos = macro_pos;
634 if (node->value.macro->paramc > 0)
636 /* Don't save tokens during pre-expansion. */
637 struct cpp_lookahead *la_saved = pfile->la_write;
639 replace_args (pfile, node->value.macro, args, list);
640 pfile->la_write = la_saved;
648 /* Push the context of a macro onto the context stack. TOKEN is the
649 macro name. If we can successfully start expanding the macro,
650 TOKEN is replaced with the first token of the expansion, and we
653 enter_macro_context (pfile, node)
657 cpp_context *context;
658 cpp_macro *macro = node->value.macro;
661 /* Save the position of the outermost macro invocation. */
662 if (!pfile->context->prev)
665 if (macro->fun_like && !funlike_invocation_p (pfile, node, &list))
667 if (!pfile->context->prev)
668 unlock_pools (pfile);
672 if (macro->paramc == 0)
674 list.first = macro->expansion;
675 list.limit = macro->expansion + macro->count;
678 /* Only push a macro context for non-empty replacement lists. */
679 if (list.first != list.limit)
681 context = next_context (pfile);
682 context->list = list;
683 context->macro = macro;
685 /* Disable the macro within its expansion. */
692 /* Move to the next context. Create one if there is none. */
697 cpp_context *prev = pfile->context;
698 cpp_context *result = prev->next;
702 result = xnew (cpp_context);
708 pfile->context = result;
713 replace_args (pfile, macro, args, list)
717 struct toklist *list;
719 unsigned char flags = 0;
720 unsigned int i, total;
721 const cpp_token *src, *limit;
725 src = macro->expansion;
726 limit = src + macro->count;
728 /* First, fully macro-expand arguments, calculating the number of
729 tokens in the final expansion as we go. This ensures that the
730 possible recursive use of argument_pool is fine. */
732 for (; src < limit; src++)
733 if (src->type == CPP_MACRO_ARG)
735 /* We have an argument. If it is not being stringified or
736 pasted it is macro-replaced before insertion. */
737 arg = &args[src->val.arg_no - 1];
739 if (src->flags & STRINGIFY_ARG)
741 if (!arg->stringified)
742 stringify_arg (pfile, arg);
744 else if ((src->flags & PASTE_LEFT)
745 || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
746 total += arg->count - 1;
751 arg->expanded_count = 0;
753 expand_arg (pfile, arg);
755 total += arg->expanded_count - 1;
759 dest = (cpp_token *) _cpp_pool_alloc (&pfile->argument_pool,
760 total * sizeof (cpp_token));
763 for (src = macro->expansion; src < limit; src++)
764 if (src->type == CPP_MACRO_ARG)
767 const cpp_token *from;
769 arg = &args[src->val.arg_no - 1];
770 if (src->flags & STRINGIFY_ARG)
771 from = arg->stringified, count = 1;
772 else if (src->flags & PASTE_LEFT)
773 count = arg->count, from = arg->first;
774 else if (src > macro->expansion && (src[-1].flags & PASTE_LEFT))
776 count = arg->count, from = arg->first;
777 if (dest != list->first)
779 /* GCC has special semantics for , ## b where b is a
780 varargs parameter: the comma disappears if b was
781 given no actual arguments (not merely if b is an
782 empty argument); otherwise pasting is turned off. */
783 if (dest[-1].type == CPP_COMMA
785 && src->val.arg_no == macro->paramc)
790 dest[-1].flags &= ~PASTE_LEFT;
792 /* Count == 0 is the RHS a placemarker case. */
794 dest[-1].flags &= ~PASTE_LEFT;
798 count = arg->expanded_count, from = arg->expanded;
800 /* Count == 0 is the LHS a placemarker case. */
803 memcpy (dest, from, count * sizeof (cpp_token));
805 /* The first token gets PREV_WHITE of the CPP_MACRO_ARG. */
806 dest->flags &= ~PREV_WHITE;
807 dest->flags |= src->flags & PREV_WHITE;
808 dest->flags |= AVOID_LPASTE;
810 /* The last token gets the PASTE_LEFT of the CPP_MACRO_ARG. */
811 dest[count - 1].flags |= src->flags & PASTE_LEFT;
816 /* The token after the argument must avoid an accidental paste. */
817 flags = AVOID_LPASTE;
822 dest->flags |= flags;
829 /* Free the expanded arguments. */
830 for (i = 0; i < macro->paramc; i++)
832 if (args[i].expanded)
833 free (args[i].expanded);
834 if (args[i].stringified)
835 free (args[i].stringified);
839 /* Subroutine of expand_arg to put the unexpanded tokens on the
842 push_arg_context (pfile, arg)
846 cpp_context *context = next_context (pfile);
848 context->list.first = arg->first;
849 context->list.limit = arg->first + arg->count;
855 expand_arg (pfile, arg)
860 unsigned int capacity = 256;
862 /* Loop, reading in the arguments. */
863 arg->expanded = (cpp_token *) xmalloc (capacity * sizeof (cpp_token));
865 push_arg_context (pfile, arg);
868 if (arg->expanded_count >= capacity)
871 arg->expanded = (cpp_token *)
872 xrealloc (arg->expanded, capacity * sizeof (cpp_token));
874 token = &arg->expanded[arg->expanded_count++];
875 cpp_get_token (pfile, token);
877 while (token->type != CPP_EOF);
879 arg->expanded_count--;
881 /* Pop the context we pushed. */
882 pfile->context = pfile->context->prev;
886 _cpp_pop_context (pfile)
889 cpp_context *context = pfile->context;
891 pfile->context = context->prev;
892 if (!pfile->context->prev && !pfile->state.parsing_args)
893 unlock_pools (pfile);
895 /* Re-enable a macro, temporarily if parsing_args, when leaving its
897 context->macro->disabled = 0;
900 /* Eternal routine to get a token. Also used nearly everywhere
901 internally, except for places where we know we can safely call
902 the lexer directly, such as lexing a directive name.
904 Macro expansions and directives are transparently handled,
905 including entering included files. Thus tokens are post-macro
906 expansion, and after any intervening directives. External callers
907 see CPP_EOF only at EOF. Internal callers also see it when meeting
908 a directive inside a macro call, when at the end of a directive and
909 state.in_directive is still 1, and at the end of argument
912 cpp_get_token (pfile, token)
918 cpp_context *context = pfile->context;
921 take_lookahead_token (pfile, token);
922 /* Context->prev == 0 <=> base context. */
923 else if (!context->prev)
924 _cpp_lex_token (pfile, token);
925 else if (context->list.first != context->list.limit)
927 *token = *context->list.first++;
928 token->flags |= pfile->buffer->saved_flags;
929 pfile->buffer->saved_flags = 0;
930 /* PASTE_LEFT tokens can only appear in macro expansions. */
931 if (token->flags & PASTE_LEFT)
933 paste_all_tokens (pfile, token);
934 pfile->buffer->saved_flags = AVOID_LPASTE;
941 /* Avoid accidental paste at the end of a macro. */
942 pfile->buffer->saved_flags |= AVOID_LPASTE;
943 _cpp_pop_context (pfile);
946 /* End of argument pre-expansion. */
947 token->type = CPP_EOF;
952 if (token->type != CPP_NAME)
955 /* Handle macros and the _Pragma operator. */
956 if (token->val.node->type == NT_MACRO
957 && !pfile->state.prevent_expansion
958 && !(token->flags & NO_EXPAND))
960 cpp_hashnode *node = token->val.node;
962 /* Macros invalidate controlling macros. */
963 pfile->mi_state = MI_FAILED;
965 if (node->flags & NODE_BUILTIN)
967 builtin_macro (pfile, token);
971 if (node->value.macro->disabled)
972 token->flags |= NO_EXPAND;
973 else if (enter_macro_context (pfile, node))
975 /* Pass AVOID_LPASTE and our PREV_WHITE to next token. */
976 pfile->buffer->saved_flags = ((token->flags & PREV_WHITE)
982 /* Don't interpret _Pragma within directives. The standard is
983 not clear on this, but to me this makes most sense. */
984 if (token->val.node != pfile->spec_nodes.n__Pragma
985 || pfile->state.in_directive)
988 /* Handle it, and loop back for another token. MI is cleared
989 since this token came from either the lexer or a macro. */
990 _cpp_do__Pragma (pfile);
994 save_lookahead_token (pfile, token);
997 /* Read each token in, until EOF. Directives are transparently
1000 cpp_scan_buffer_nooutput (pfile, all_buffers)
1005 cpp_buffer *buffer = all_buffers ? 0: pfile->buffer->prev;
1009 cpp_get_token (pfile, &token);
1010 while (token.type != CPP_EOF);
1011 while (cpp_pop_buffer (pfile) != buffer);
1014 /* Lookahead handling. */
1017 save_lookahead_token (pfile, token)
1019 const cpp_token *token;
1021 if (token->type != CPP_EOF)
1023 cpp_lookahead *la = pfile->la_write;
1024 cpp_token_with_pos *twp;
1026 if (la->count == la->cap)
1028 la->cap += la->cap + 8;
1029 la->tokens = (cpp_token_with_pos *)
1030 xrealloc (la->tokens, la->cap * sizeof (cpp_token_with_pos));
1033 twp = &la->tokens[la->count++];
1034 twp->token = *token;
1035 twp->pos = *cpp_get_line (pfile);
1040 take_lookahead_token (pfile, token)
1044 cpp_lookahead *la = pfile->la_read;
1045 cpp_token_with_pos *twp = &la->tokens[la->cur];
1047 *token = twp->token;
1048 pfile->lexer_pos = twp->pos;
1050 if (++la->cur == la->count)
1051 _cpp_release_lookahead (pfile);
1054 /* Moves the lookahead at the front of the read list to the free store. */
1056 _cpp_release_lookahead (pfile)
1059 cpp_lookahead *la = pfile->la_read;
1061 pfile->la_read = la->next;
1062 la->next = pfile->la_unused;
1063 pfile->la_unused = la;
1064 unlock_pools (pfile);
1067 /* Take a new lookahead from the free store, or allocate one if none. */
1068 static cpp_lookahead *
1069 alloc_lookahead (pfile)
1072 cpp_lookahead *la = pfile->la_unused;
1075 pfile->la_unused = la->next;
1078 la = xnew (cpp_lookahead);
1083 la->cur = la->count = 0;
1087 /* Free memory associated with a lookahead list. */
1093 free ((PTR) la->tokens);
1097 /* Free all the lookaheads of a cpp_reader. */
1099 _cpp_free_lookaheads (pfile)
1102 cpp_lookahead *la, *lan;
1105 free_lookahead (pfile->la_read);
1106 if (pfile->la_write)
1107 free_lookahead (pfile->la_write);
1109 for (la = pfile->la_unused; la; la = lan)
1112 free_lookahead (la);
1116 /* Allocate a lookahead and move it to the front of the write list. */
1118 cpp_start_lookahead (pfile)
1121 cpp_lookahead *la = alloc_lookahead (pfile);
1123 la->next = pfile->la_write;
1124 pfile->la_write = la;
1126 la->pos = *cpp_get_line (pfile);
1128 /* Don't allow memory pools to be re-used whilst we're reading ahead. */
1132 /* Stop reading ahead - either step back, or drop the read ahead. */
1134 cpp_stop_lookahead (pfile, drop)
1138 cpp_lookahead *la = pfile->la_write;
1140 pfile->la_write = la->next;
1141 la->next = pfile->la_read;
1142 pfile->la_read = la;
1144 if (drop || la->count == 0)
1145 _cpp_release_lookahead (pfile);
1147 pfile->lexer_pos = la->pos;
1150 /* Push a single token back to the front of the queue. Only to be
1151 used by cpplib, and only then when necessary. POS is the position
1152 to report for the preceding token. */
1154 _cpp_push_token (pfile, token, pos)
1156 const cpp_token *token;
1157 const cpp_lexer_pos *pos;
1159 cpp_start_lookahead (pfile);
1160 save_lookahead_token (pfile, token);
1161 cpp_stop_lookahead (pfile, 0);
1162 pfile->lexer_pos = *pos;
1165 /* #define directive parsing and handling. */
1167 /* Returns non-zero if a macro redefinition is trivial. */
1169 check_macro_redefinition (pfile, node, macro2)
1171 const cpp_hashnode *node;
1172 const cpp_macro *macro2;
1174 const cpp_macro *macro1;
1177 if (node->type != NT_MACRO || node->flags & NODE_BUILTIN)
1178 return ! pfile->done_initializing;
1180 macro1 = node->value.macro;
1182 /* The quick failures. */
1183 if (macro1->count != macro2->count
1184 || macro1->paramc != macro2->paramc
1185 || macro1->fun_like != macro2->fun_like
1186 || macro1->variadic != macro2->variadic)
1189 /* Check each token. */
1190 for (i = 0; i < macro1->count; i++)
1191 if (! _cpp_equiv_tokens (¯o1->expansion[i], ¯o2->expansion[i]))
1194 /* Check parameter spellings. */
1195 for (i = 0; i < macro1->paramc; i++)
1196 if (macro1->params[i] != macro2->params[i])
1202 /* Free the definition of hashnode H. */
1205 _cpp_free_definition (h)
1208 /* Macros and assertions no longer have anything to free. */
1210 /* Clear builtin flag in case of redefinition. */
1211 h->flags &= ~NODE_BUILTIN;
1215 save_parameter (pfile, macro, node)
1220 cpp_hashnode **dest;
1222 /* Constraint 6.10.3.6 - duplicate parameter names. */
1223 if (node->arg_index)
1225 cpp_error (pfile, "duplicate macro parameter \"%s\"", node->name);
1229 dest = ¯o->params[macro->paramc];
1231 /* Check we have room for the parameters. */
1232 if ((unsigned char *) (dest + 1) >= POOL_LIMIT (&pfile->macro_pool))
1234 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_hashnode *),
1235 (unsigned char **) ¯o->params);
1236 dest = ¯o->params[macro->paramc];
1240 node->arg_index = ++macro->paramc;
1245 parse_params (pfile, macro)
1250 unsigned int prev_ident = 0;
1252 macro->params = (cpp_hashnode **) POOL_FRONT (&pfile->macro_pool);
1255 _cpp_lex_token (pfile, &token);
1260 cpp_error (pfile, "\"%s\" may not appear in macro parameter list",
1261 cpp_token_as_text (pfile, &token));
1267 cpp_error (pfile, "macro parameters must be comma-separated");
1272 if (save_parameter (pfile, macro, token.val.node))
1276 case CPP_CLOSE_PAREN:
1277 if (prev_ident || macro->paramc == 0)
1280 /* Fall through to pick up the error. */
1284 cpp_error (pfile, "parameter name missing");
1291 macro->variadic = 1;
1294 save_parameter (pfile, macro, pfile->spec_nodes.n__VA_ARGS__);
1295 pfile->state.va_args_ok = 1;
1296 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1298 "anonymous variadic macros were introduced in C99");
1300 else if (CPP_OPTION (pfile, pedantic))
1301 cpp_pedwarn (pfile, "ISO C does not permit named variadic macros");
1303 /* We're at the end, and just expect a closing parenthesis. */
1304 _cpp_lex_token (pfile, &token);
1305 if (token.type == CPP_CLOSE_PAREN)
1310 cpp_error (pfile, "missing ')' in macro parameter list");
1314 /* Success. Commit the parameter array. */
1315 POOL_COMMIT (&pfile->macro_pool,
1316 macro->paramc * sizeof (cpp_hashnode *));
1321 /* Lex a token from a macro's replacement list. Translate it to a
1322 CPP_MACRO_ARG if appropriate. */
1324 lex_expansion_token (pfile, macro)
1328 cpp_token *token = ¯o->expansion[macro->count];
1330 /* Check we have room for the token. */
1331 if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->macro_pool))
1333 _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_token),
1334 (unsigned char **) ¯o->expansion);
1335 token = ¯o->expansion[macro->count];
1339 _cpp_lex_token (pfile, token);
1341 /* Is this an argument? */
1342 if (token->type == CPP_NAME && token->val.node->arg_index)
1344 token->type = CPP_MACRO_ARG;
1345 token->val.arg_no = token->val.node->arg_index;
1347 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1348 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1349 check_trad_stringification (pfile, macro, &token->val.str);
1354 /* Parse a macro and save its expansion. Returns non-zero on success. */
1356 _cpp_create_definition (pfile, node)
1362 unsigned int i, ok = 1;
1364 macro = (cpp_macro *) _cpp_pool_alloc (&pfile->macro_pool,
1365 sizeof (cpp_macro));
1366 macro->file = pfile->buffer->nominal_fname;
1367 macro->line = pfile->directive_pos.line;
1370 macro->fun_like = 0;
1371 macro->variadic = 0;
1373 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1375 /* Get the first token of the expansion (or the '(' of a
1376 function-like macro). */
1377 token = lex_expansion_token (pfile, macro);
1378 if (token->type == CPP_OPEN_PAREN && !(token->flags & PREV_WHITE))
1380 if (!(ok = parse_params (pfile, macro)))
1383 macro->fun_like = 1;
1384 /* Some of the pool may have been used for the parameter store. */
1385 macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1386 token = lex_expansion_token (pfile, macro);
1388 else if (token->type != CPP_EOF && !(token->flags & PREV_WHITE))
1389 cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
1391 /* Setting it here means we don't catch leading comments. */
1392 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
1396 /* Check the stringifying # constraint 6.10.3.2.1 of
1397 function-like macros when lexing the subsequent token. */
1398 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1400 if (token->type == CPP_MACRO_ARG)
1402 token->flags &= ~PREV_WHITE;
1403 token->flags |= STRINGIFY_ARG;
1404 token->flags |= token[-1].flags & PREV_WHITE;
1405 token[-1] = token[0];
1408 /* Let assembler get away with murder. */
1409 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1412 cpp_error (pfile, "'#' is not followed by a macro parameter");
1417 if (token->type == CPP_EOF)
1420 /* Paste operator constraint 6.10.3.3.1. */
1421 if (token->type == CPP_PASTE)
1423 /* Token-paste ##, can appear in both object-like and
1424 function-like macros, but not at the ends. */
1425 if (--macro->count > 0)
1426 token = lex_expansion_token (pfile, macro);
1428 if (macro->count == 0 || token->type == CPP_EOF)
1432 "'##' cannot appear at either end of a macro expansion");
1436 token[-1].flags |= PASTE_LEFT;
1437 /* Give it a PREV_WHITE for -dM etc. */
1438 token->flags |= PREV_WHITE;
1441 token = lex_expansion_token (pfile, macro);
1444 /* Don't count the CPP_EOF. */
1447 /* Clear the whitespace flag from the leading token. */
1448 macro->expansion[0].flags &= ~PREV_WHITE;
1450 /* Implement the macro-defined-to-itself optimisation. */
1451 macro->disabled = (macro->count == 1 && !macro->fun_like
1452 && macro->expansion[0].type == CPP_NAME
1453 && macro->expansion[0].val.node == node);
1455 /* Commit the memory. */
1456 POOL_COMMIT (&pfile->macro_pool, macro->count * sizeof (cpp_token));
1458 /* Redefinition of a macro is allowed if and only if the old and new
1459 definitions are the same. (6.10.3 paragraph 2). */
1460 if (node->type != NT_VOID)
1462 if (CPP_PEDANTIC (pfile)
1463 && !check_macro_redefinition (pfile, node, macro))
1465 cpp_pedwarn_with_line (pfile, pfile->directive_pos.line,
1466 pfile->directive_pos.col,
1467 "\"%s\" redefined", node->name);
1469 if (pfile->done_initializing && node->type == NT_MACRO
1470 && !(node->flags & NODE_BUILTIN))
1471 cpp_pedwarn_with_file_and_line (pfile,
1472 node->value.macro->file,
1473 node->value.macro->line, 1,
1474 "this is the location of the previous definition");
1476 _cpp_free_definition (node);
1479 /* Enter definition in hash table. */
1480 node->type = NT_MACRO;
1481 node->value.macro = macro;
1485 /* Stop the lexer accepting __VA_ARGS__. */
1486 pfile->state.va_args_ok = 0;
1488 /* Clear the fast argument lookup indices. */
1489 for (i = macro->paramc; i-- > 0; )
1490 macro->params[i]->arg_index = 0;
1495 /* Warn if a token in `string' matches one of the function macro
1496 arguments in `info'. This function assumes that the macro is a
1497 function macro and not an object macro. */
1499 check_trad_stringification (pfile, macro, string)
1501 const cpp_macro *macro;
1502 const cpp_string *string;
1504 unsigned int i, len;
1505 const U_CHAR *p, *q, *limit = string->text + string->len;
1507 /* Loop over the string. */
1508 for (p = string->text; p < limit; p = q)
1510 /* Find the start of an identifier. */
1511 while (p < limit && !is_idstart (*p))
1514 /* Find the end of the identifier. */
1516 while (q < limit && is_idchar (*q))
1521 /* Loop over the function macro arguments to see if the
1522 identifier inside the string matches one of them. */
1523 for (i = 0; i < macro->paramc; i++)
1525 const cpp_hashnode *node = macro->params[i];
1527 if (node->length == len && !memcmp (p, node->name, len))
1530 "macro argument \"%s\" would be stringified with -traditional.",
1538 /* Returns the expansion of a macro, in a format suitable to be read
1539 back in again, and therefore also for DWARF 2 debugging info.
1540 Caller is expected to generate the "#define NAME" bit. The
1541 returned text is temporary, and automatically freed later. */
1543 const unsigned char *
1544 cpp_macro_definition (pfile, node)
1546 const cpp_hashnode *node;
1548 unsigned int i, len;
1549 const cpp_macro *macro = node->value.macro;
1550 unsigned char *buffer;
1552 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1554 cpp_ice (pfile, "invalid hash type %d in dump_definition", node->type);
1558 /* Calculate length. */
1560 if (macro->fun_like)
1562 len += 3; /* "()" plus possible final "." of ellipsis. */
1563 for (i = 0; i < macro->paramc; i++)
1564 len += macro->params[i]->length + 2; /* ", " */
1567 for (i = 0; i < macro->count; i++)
1569 cpp_token *token = ¯o->expansion[i];
1571 if (token->type == CPP_MACRO_ARG)
1572 len += macro->params[token->val.arg_no - 1]->length;
1574 len += cpp_token_len (token); /* Includes room for ' '. */
1575 if (token->flags & STRINGIFY_ARG)
1577 if (token->flags & PASTE_LEFT)
1578 len += 3; /* " ##" */
1581 if (len > pfile->macro_buffer_len)
1583 pfile->macro_buffer = (U_CHAR *) xrealloc (pfile->macro_buffer, len);
1584 pfile->macro_buffer_len = len;
1586 buffer = pfile->macro_buffer;
1588 /* Parameter names. */
1589 if (macro->fun_like)
1592 for (i = 0; i < macro->paramc; i++)
1594 cpp_hashnode *param = macro->params[i];
1596 if (param != pfile->spec_nodes.n__VA_ARGS__)
1598 memcpy (buffer, param->name, param->length);
1599 buffer += param->length;
1602 if (i + 1 < macro->paramc)
1603 *buffer++ = ',', *buffer++ = ' ';
1604 else if (macro->variadic)
1605 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1610 /* Expansion tokens. */
1614 for (i = 0; i < macro->count; i++)
1616 cpp_token *token = ¯o->expansion[i];
1618 if (token->flags & PREV_WHITE)
1620 if (token->flags & STRINGIFY_ARG)
1623 if (token->type == CPP_MACRO_ARG)
1625 len = macro->params[token->val.arg_no - 1]->length;
1626 memcpy (buffer, macro->params[token->val.arg_no - 1]->name, len);
1630 buffer = cpp_spell_token (pfile, token, buffer);
1632 if (token->flags & PASTE_LEFT)
1637 /* Next has PREV_WHITE; see _cpp_create_definition. */
1643 return pfile->macro_buffer;