1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3 1999, 2000, 2001 Free Software Foundation, Inc.
4 Written by Per Bothner, 1994.
5 Based on CCCP program by Paul Rubin, June 1986
6 Adapted to ANSI C, Richard Stallman, Jan 1987
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 In other words, you are welcome to use, share and improve this program.
23 You are forbidden to forbid anyone else to use, share and improve
24 what you give them. Help stamp out software-hoarding! */
28 #include "intl.h" /* for _("<command line>") below. */
34 cpp_hashnode **params; /* Parameters, if any. */
35 cpp_token *expansion; /* First token of replacement list. */
36 unsigned int line; /* Starting line number. */
37 unsigned int count; /* Number of tokens in expansion. */
38 unsigned short paramc; /* Number of parameters. */
39 unsigned int fun_like : 1; /* If a function-like macro. */
40 unsigned int variadic : 1; /* If a variadic macro. */
41 unsigned int syshdr : 1; /* If macro defined in system header. */
44 typedef struct macro_arg macro_arg;
47 const cpp_token **first; /* First token in unexpanded argument. */
48 const cpp_token **expanded; /* Macro-expanded argument. */
49 const cpp_token *stringified; /* Stringified argument. */
50 unsigned int count; /* # of tokens in argument. */
51 unsigned int expanded_count; /* # of tokens in expanded argument. */
54 /* Macro expansion. */
56 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
57 static int builtin_macro PARAMS ((cpp_reader *, cpp_hashnode *));
58 static void push_token_context
59 PARAMS ((cpp_reader *, cpp_hashnode *, const cpp_token *, unsigned int));
60 static void push_ptoken_context
61 PARAMS ((cpp_reader *, cpp_hashnode *, _cpp_buff *,
62 const cpp_token **, unsigned int));
63 static _cpp_buff *collect_args PARAMS ((cpp_reader *, const cpp_hashnode *));
64 static cpp_context *next_context PARAMS ((cpp_reader *));
65 static const cpp_token *padding_token
66 PARAMS ((cpp_reader *, const cpp_token *));
67 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
68 static unsigned char *quote_string PARAMS ((unsigned char *,
69 const unsigned char *,
71 static const cpp_token *new_string_token PARAMS ((cpp_reader *, U_CHAR *,
73 static const cpp_token *new_number_token PARAMS ((cpp_reader *, int));
74 static const cpp_token *stringify_arg PARAMS ((cpp_reader *, macro_arg *));
75 static void paste_all_tokens PARAMS ((cpp_reader *, const cpp_token *));
76 static bool paste_tokens PARAMS ((cpp_reader *, const cpp_token **,
78 static int funlike_invocation_p PARAMS ((cpp_reader *, cpp_hashnode *));
79 static void replace_args PARAMS ((cpp_reader *, cpp_hashnode *, macro_arg *));
81 /* #define directive parsing and handling. */
83 static cpp_token *alloc_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
84 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
85 static int warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
87 static int save_parameter PARAMS ((cpp_reader *, cpp_macro *, cpp_hashnode *));
88 static int parse_params PARAMS ((cpp_reader *, cpp_macro *));
89 static void check_trad_stringification PARAMS ((cpp_reader *,
93 /* Allocates and returns a CPP_STRING token, containing TEXT of length
94 LEN, after null-terminating it. TEXT must be in permanent storage. */
95 static const cpp_token *
96 new_string_token (pfile, text, len)
101 cpp_token *token = _cpp_temp_token (pfile);
104 token->type = CPP_STRING;
105 token->val.str.len = len;
106 token->val.str.text = text;
111 /* Allocates and returns a CPP_NUMBER token evaluating to NUMBER. */
112 static const cpp_token *
113 new_number_token (pfile, number)
117 cpp_token *token = _cpp_temp_token (pfile);
118 unsigned char *buf = _cpp_unaligned_alloc (pfile, 20);
120 sprintf ((char *) buf, "%d", number);
121 token->type = CPP_NUMBER;
122 token->val.str.text = buf;
123 token->val.str.len = ustrlen (buf);
128 static const char * const monthnames[] =
130 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
131 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
134 /* Handle builtin macros like __FILE__, and push the resulting token
135 on the context stack. Also handles _Pragma, for which no new token
136 is created. Returns 1 on success, 0 to return the token to the
139 builtin_macro (pfile, node)
143 const cpp_token *result;
145 switch (node->value.builtin)
148 cpp_ice (pfile, "invalid builtin macro \"%s\"", NODE_NAME (node));
157 const struct line_map *map = pfile->map;
159 if (node->value.builtin == BT_BASE_FILE)
160 while (! MAIN_FILE_P (map))
161 map = INCLUDED_FROM (&pfile->line_maps, map);
165 buf = _cpp_unaligned_alloc (pfile, len * 4 + 1);
166 len = quote_string (buf, (const unsigned char *) name, len) - buf;
168 result = new_string_token (pfile, buf, len);
172 case BT_INCLUDE_LEVEL:
173 /* The line map depth counts the primary source as level 1, but
174 historically __INCLUDE_DEPTH__ has called the primary source
176 result = new_number_token (pfile, pfile->line_maps.depth - 1);
180 /* If __LINE__ is embedded in a macro, it must expand to the
181 line of the macro's invocation, not its definition.
182 Otherwise things like assert() will not work properly. */
183 result = new_number_token (pfile,
184 SOURCE_LINE (pfile->map,
185 pfile->cur_token[-1].line));
190 int stdc = (!CPP_IN_SYSTEM_HEADER (pfile)
191 || pfile->spec_nodes.n__STRICT_ANSI__->type != NT_VOID);
192 result = new_number_token (pfile, stdc);
198 if (pfile->date.type == CPP_EOF)
200 /* Allocate __DATE__ and __TIME__ strings from permanent
201 storage. We only do this once, and don't generate them
202 at init time, because time() and localtime() are very
203 slow on some systems. */
204 time_t tt = time (NULL);
205 struct tm *tb = localtime (&tt);
207 pfile->date.val.str.text =
208 _cpp_unaligned_alloc (pfile, sizeof ("Oct 11 1347"));
209 pfile->date.val.str.len = sizeof ("Oct 11 1347") - 1;
210 pfile->date.type = CPP_STRING;
211 pfile->date.flags = 0;
212 sprintf ((char *) pfile->date.val.str.text, "%s %2d %4d",
213 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
215 pfile->time.val.str.text =
216 _cpp_unaligned_alloc (pfile, sizeof ("12:34:56"));
217 pfile->time.val.str.len = sizeof ("12:34:56") - 1;
218 pfile->time.type = CPP_STRING;
219 pfile->time.flags = 0;
220 sprintf ((char *) pfile->time.val.str.text, "%02d:%02d:%02d",
221 tb->tm_hour, tb->tm_min, tb->tm_sec);
224 if (node->value.builtin == BT_DATE)
225 result = &pfile->date;
227 result = &pfile->time;
231 /* Don't interpret _Pragma within directives. The standard is
232 not clear on this, but to me this makes most sense. */
233 if (pfile->state.in_directive)
236 _cpp_do__Pragma (pfile);
240 push_token_context (pfile, NULL, result, 1);
244 /* Adds backslashes before all backslashes and double quotes appearing
245 in strings. Non-printable characters are converted to octal. */
247 quote_string (dest, src, len)
256 if (c == '\\' || c == '"')
267 sprintf ((char *) dest, "\\%03o", c);
276 /* Convert a token sequence to a single string token according to the
277 rules of the ISO C #-operator. */
278 static const cpp_token *
279 stringify_arg (pfile, arg)
283 unsigned char *dest = BUFF_FRONT (pfile->u_buff);
284 unsigned int i, escape_it, backslash_count = 0;
285 const cpp_token *source = NULL;
288 /* Loop, reading in the argument's tokens. */
289 for (i = 0; i < arg->count; i++)
291 const cpp_token *token = arg->first[i];
293 if (token->type == CPP_PADDING)
296 source = token->val.source;
300 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
301 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
303 /* Room for each char being written in octal, initial space and
305 len = cpp_token_len (token);
310 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
312 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
313 _cpp_extend_buff (pfile, &pfile->u_buff, len);
314 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
317 /* Leading white space? */
318 if (dest != BUFF_FRONT (pfile->u_buff))
322 if (source->flags & PREV_WHITE)
329 _cpp_buff *buff = _cpp_get_buff (pfile, len);
330 unsigned char *buf = BUFF_FRONT (buff);
331 len = cpp_spell_token (pfile, token, buf) - buf;
332 dest = quote_string (dest, buf, len);
333 _cpp_release_buff (pfile, buff);
336 dest = cpp_spell_token (pfile, token, dest);
338 if (token->type == CPP_OTHER && token->val.c == '\\')
344 /* Ignore the final \ of invalid string literals. */
345 if (backslash_count & 1)
347 cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
351 /* Commit the memory, including NUL, and return the token. */
352 len = dest - BUFF_FRONT (pfile->u_buff);
353 BUFF_FRONT (pfile->u_buff) = dest + 1;
354 return new_string_token (pfile, dest - len, len);
357 /* Try to paste two tokens. On success, return non-zero. In any
358 case, PLHS is updated to point to the pasted token, which is
359 guaranteed to not have the PASTE_LEFT flag set. */
361 paste_tokens (pfile, plhs, rhs)
363 const cpp_token **plhs, *rhs;
365 unsigned char *buf, *end;
366 const cpp_token *lhs;
371 len = cpp_token_len (lhs) + cpp_token_len (rhs) + 1;
372 buf = (unsigned char *) alloca (len);
373 end = cpp_spell_token (pfile, lhs, buf);
375 /* Avoid comment headers, since they are still processed in stage 3.
376 It is simpler to insert a space here, rather than modifying the
377 lexer to ignore comments in some circumstances. Simply returning
378 false doesn't work, since we want to clear the PASTE_LEFT flag. */
379 if (lhs->type == CPP_DIV
380 && (rhs->type == CPP_MULT || rhs->type == CPP_DIV))
382 end = cpp_spell_token (pfile, rhs, end);
384 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true, 1);
386 /* Tweak the column number the lexer will report. */
387 pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
389 /* We don't want a leading # to be interpreted as a directive. */
390 pfile->buffer->saved_flags = 0;
392 /* Set pfile->cur_token as required by _cpp_lex_direct. */
393 pfile->cur_token = _cpp_temp_token (pfile);
394 *plhs = _cpp_lex_direct (pfile);
395 valid = (pfile->buffer->cur == pfile->buffer->rlimit
396 && pfile->buffer->read_ahead == EOF);
397 _cpp_pop_buffer (pfile);
402 /* Handles an arbitrarily long sequence of ## operators. This
403 implementation is left-associative, non-recursive, and finishes a
404 paste before handling succeeding ones. If the paste fails, we back
405 up a token to just after the ## operator, with the effect that it
406 appears in the output stream normally. */
408 paste_all_tokens (pfile, lhs)
410 const cpp_token *lhs;
412 const cpp_token *rhs;
413 cpp_context *context = pfile->context;
417 /* Take the token directly from the current context. We can do
418 this, because we are in the replacement list of either an
419 object-like macro, or a function-like macro with arguments
420 inserted. In either case, the constraints to #define
421 guarantee we have at least one more token. */
422 if (context->direct_p)
423 rhs = context->first.token++;
425 rhs = *context->first.ptoken++;
427 if (rhs->type == CPP_PADDING)
430 if (!paste_tokens (pfile, &lhs, rhs))
432 _cpp_backup_tokens (pfile, 1);
434 /* Mandatory warning for all apart from assembler. */
435 if (CPP_OPTION (pfile, lang) != CLK_ASM)
437 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
438 cpp_token_as_text (pfile, lhs),
439 cpp_token_as_text (pfile, rhs));
443 while (rhs->flags & PASTE_LEFT);
445 /* Put the resulting token in its own context. */
446 push_token_context (pfile, NULL, lhs, 1);
449 /* Reads and returns the arguments to a function-like macro invocation.
450 Assumes the opening parenthesis has been processed. If there is an
451 error, emits an appropriate diagnostic and returns NULL. */
453 collect_args (pfile, node)
455 const cpp_hashnode *node;
457 _cpp_buff *buff, *base_buff;
459 macro_arg *args, *arg;
460 const cpp_token *token;
464 macro = node->value.macro;
466 argc = macro->paramc;
469 buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
470 + sizeof (macro_arg)));
472 args = (macro_arg *) buff->base;
473 memset (args, 0, argc * sizeof (macro_arg));
474 buff->cur = (unsigned char *) &args[argc];
475 arg = args, argc = 0;
477 /* Collect the tokens making up each argument. We don't yet know
478 how many arguments have been supplied, whether too many or too
479 few. Hence the slightly bizarre usage of "argc" and "arg". */
482 unsigned int paren_depth = 0;
483 unsigned int ntokens = 0;
486 arg->first = (const cpp_token **) buff->cur;
490 /* Require space for 2 new tokens (including a CPP_EOF). */
491 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
493 buff = _cpp_append_extend_buff (pfile, buff,
494 1000 * sizeof (cpp_token *));
495 arg->first = (const cpp_token **) buff->cur;
498 token = cpp_get_token (pfile);
500 if (token->type == CPP_PADDING)
502 /* Drop leading padding. */
506 else if (token->type == CPP_OPEN_PAREN)
508 else if (token->type == CPP_CLOSE_PAREN)
510 if (paren_depth-- == 0)
513 else if (token->type == CPP_COMMA)
515 /* A comma does not terminate an argument within
516 parentheses or as part of a variable argument. */
518 && ! (macro->variadic && argc == macro->paramc))
521 else if (token->type == CPP_EOF
522 || (token->type == CPP_HASH && token->flags & BOL))
525 arg->first[ntokens++] = token;
528 /* Drop trailing padding. */
529 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
532 arg->count = ntokens;
533 arg->first[ntokens] = &pfile->eof;
535 /* Terminate the argument. Excess arguments loop back and
536 overwrite the final legitimate argument, before failing. */
537 if (argc <= macro->paramc)
539 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
540 if (argc != macro->paramc)
544 while (token->type != CPP_CLOSE_PAREN
545 && token->type != CPP_EOF
546 && token->type != CPP_HASH);
548 if (token->type == CPP_EOF || token->type == CPP_HASH)
550 bool step_back = false;
552 /* 6.10.3 paragraph 11: If there are sequences of preprocessing
553 tokens within the list of arguments that would otherwise act
554 as preprocessing directives, the behavior is undefined.
556 This implementation will report a hard error, terminate the
557 macro invocation, and proceed to process the directive. */
558 if (token->type == CPP_HASH)
561 "directives may not be used inside a macro argument");
565 step_back = (pfile->context->prev || pfile->state.in_directive);
567 /* We still need the CPP_EOF to end directives, and to end
568 pre-expansion of a macro argument. Step back is not
569 unconditional, since we don't want to return a CPP_EOF to our
570 callers at the end of an -include-d file. */
572 _cpp_backup_tokens (pfile, 1);
573 cpp_error (pfile, "unterminated argument list invoking macro \"%s\"",
577 else if (argc < macro->paramc)
579 /* As an extension, a rest argument is allowed to not appear in
580 the invocation at all.
581 e.g. #define debug(format, args...) something
584 This is exactly the same as if there had been an empty rest
585 argument - debug("string", ). */
587 if (argc + 1 == macro->paramc && macro->variadic)
589 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
590 cpp_pedwarn (pfile, "ISO C99 requires rest arguments to be used");
595 "macro \"%s\" requires %u arguments, but only %u given",
596 NODE_NAME (node), macro->paramc, argc);
600 else if (argc > macro->paramc)
602 /* Empty argument to a macro taking no arguments is OK. */
603 if (argc != 1 || arg->count)
606 "macro \"%s\" passed %u arguments, but takes just %u",
607 NODE_NAME (node), argc, macro->paramc);
615 _cpp_release_buff (pfile, base_buff);
620 funlike_invocation_p (pfile, node)
624 const cpp_token *maybe_paren;
625 _cpp_buff *buff = NULL;
627 pfile->state.prevent_expansion++;
628 pfile->keep_tokens++;
630 pfile->state.parsing_args = 1;
632 maybe_paren = cpp_get_token (pfile);
633 while (maybe_paren->type == CPP_PADDING);
634 pfile->state.parsing_args = 2;
636 if (maybe_paren->type == CPP_OPEN_PAREN)
637 buff = collect_args (pfile, node);
640 _cpp_backup_tokens (pfile, 1);
641 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
643 "function-like macro \"%s\" must be used with arguments in traditional C",
647 pfile->state.parsing_args = 0;
648 pfile->keep_tokens--;
649 pfile->state.prevent_expansion--;
653 if (node->value.macro->paramc > 0)
654 replace_args (pfile, node, (macro_arg *) buff->base);
655 _cpp_release_buff (pfile, buff);
661 /* Push the context of a macro onto the context stack. TOKEN is the
662 macro name. If we can successfully start expanding the macro,
663 TOKEN is replaced with the first token of the expansion, and we
666 enter_macro_context (pfile, node)
670 /* Macros invalidate controlling macros. */
671 pfile->mi_valid = false;
673 /* Handle macros and the _Pragma operator. */
674 if (! (node->flags & NODE_BUILTIN))
676 cpp_macro *macro = node->value.macro;
678 if (macro->fun_like && !funlike_invocation_p (pfile, node))
681 /* Disable the macro within its expansion. */
682 node->flags |= NODE_DISABLED;
684 if (macro->paramc == 0)
685 push_token_context (pfile, node, macro->expansion, macro->count);
690 return builtin_macro (pfile, node);
693 /* Take the expansion of a function-like MACRO, replacing parameters
694 with the actual arguments. Each argument is macro-expanded before
695 replacement, unless operated upon by the # or ## operators. */
697 replace_args (pfile, node, args)
702 unsigned int i, total;
703 const cpp_token *src, *limit;
704 const cpp_token **dest, **first;
709 /* First, fully macro-expand arguments, calculating the number of
710 tokens in the final expansion as we go. The ordering of the if
711 statements below is subtle; we must handle stringification before
713 macro = node->value.macro;
714 total = macro->count;
715 limit = macro->expansion + macro->count;
717 for (src = macro->expansion; src < limit; src++)
718 if (src->type == CPP_MACRO_ARG)
720 /* Leading and trailing padding tokens. */
723 /* We have an argument. If it is not being stringified or
724 pasted it is macro-replaced before insertion. */
725 arg = &args[src->val.arg_no - 1];
727 if (src->flags & STRINGIFY_ARG)
729 if (!arg->stringified)
730 arg->stringified = stringify_arg (pfile, arg);
732 else if ((src->flags & PASTE_LEFT)
733 || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
734 total += arg->count - 1;
738 expand_arg (pfile, arg);
739 total += arg->expanded_count - 1;
743 /* Now allocate space for the expansion, copy the tokens and replace
745 buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
746 first = (const cpp_token **) buff->base;
749 for (src = macro->expansion; src < limit; src++)
752 const cpp_token **from, **paste_flag;
754 if (src->type != CPP_MACRO_ARG)
761 arg = &args[src->val.arg_no - 1];
762 if (src->flags & STRINGIFY_ARG)
763 count = 1, from = &arg->stringified;
764 else if (src->flags & PASTE_LEFT)
765 count = arg->count, from = arg->first;
766 else if (src != macro->expansion && (src[-1].flags & PASTE_LEFT))
768 count = arg->count, from = arg->first;
771 /* GCC has special semantics for , ## b where b is a
772 varargs parameter: the comma disappears if b was
773 given no actual arguments (not merely if b is an
774 empty argument); otherwise the paste flag is removed. */
775 if (dest[-1]->type == CPP_COMMA
777 && src->val.arg_no == macro->paramc)
782 paste_flag = dest - 1;
784 /* Remove the paste flag if the RHS is a placemarker. */
786 paste_flag = dest - 1;
790 count = arg->expanded_count, from = arg->expanded;
792 /* Padding on the left of an argument (unless RHS of ##). */
793 if (!pfile->state.in_directive
794 && src != macro->expansion && !(src[-1].flags & PASTE_LEFT))
795 *dest++ = padding_token (pfile, src);
799 memcpy (dest, from, count * sizeof (cpp_token *));
802 /* With a non-empty argument on the LHS of ##, the last
803 token should be flagged PASTE_LEFT. */
804 if (src->flags & PASTE_LEFT)
805 paste_flag = dest - 1;
808 /* Avoid paste on RHS (even case count == 0). */
809 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
810 *dest++ = &pfile->avoid_paste;
812 /* Add a new paste flag, or remove an unwanted one. */
815 cpp_token *token = _cpp_temp_token (pfile);
816 token->type = (*paste_flag)->type;
817 token->val.str = (*paste_flag)->val.str;
818 if (src->flags & PASTE_LEFT)
819 token->flags = (*paste_flag)->flags | PASTE_LEFT;
821 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
826 /* Free the expanded arguments. */
827 for (i = 0; i < macro->paramc; i++)
828 if (args[i].expanded)
829 free (args[i].expanded);
831 push_ptoken_context (pfile, node, buff, first, dest - first);
834 /* Return a special padding token, with padding inherited from SOURCE. */
835 static const cpp_token *
836 padding_token (pfile, source)
838 const cpp_token *source;
840 cpp_token *result = _cpp_temp_token (pfile);
842 result->type = CPP_PADDING;
843 result->val.source = source;
848 /* Move to the next context. Create one if there is none. */
853 cpp_context *result = pfile->context->next;
857 result = xnew (cpp_context);
858 result->prev = pfile->context;
860 pfile->context->next = result;
863 pfile->context = result;
867 /* Push a list of pointers to tokens. */
869 push_ptoken_context (pfile, macro, buff, first, count)
873 const cpp_token **first;
876 cpp_context *context = next_context (pfile);
878 context->direct_p = false;
879 context->macro = macro;
880 context->buff = buff;
881 context->first.ptoken = first;
882 context->last.ptoken = first + count;
885 /* Push a list of tokens. */
887 push_token_context (pfile, macro, first, count)
890 const cpp_token *first;
893 cpp_context *context = next_context (pfile);
895 context->direct_p = true;
896 context->macro = macro;
897 context->buff = NULL;
898 context->first.token = first;
899 context->last.token = first + count;
903 expand_arg (pfile, arg)
907 unsigned int capacity;
912 /* Loop, reading in the arguments. */
914 arg->expanded = (const cpp_token **)
915 xmalloc (capacity * sizeof (cpp_token *));
917 push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
920 const cpp_token *token;
922 if (arg->expanded_count + 1 >= capacity)
925 arg->expanded = (const cpp_token **)
926 xrealloc (arg->expanded, capacity * sizeof (cpp_token *));
929 token = cpp_get_token (pfile);
931 if (token->type == CPP_EOF)
934 arg->expanded[arg->expanded_count++] = token;
937 _cpp_pop_context (pfile);
941 _cpp_pop_context (pfile)
944 cpp_context *context = pfile->context;
946 /* Re-enable a macro when leaving its expansion. */
948 context->macro->flags &= ~NODE_DISABLED;
951 _cpp_release_buff (pfile, context->buff);
953 pfile->context = context->prev;
956 /* Eternal routine to get a token. Also used nearly everywhere
957 internally, except for places where we know we can safely call
958 the lexer directly, such as lexing a directive name.
960 Macro expansions and directives are transparently handled,
961 including entering included files. Thus tokens are post-macro
962 expansion, and after any intervening directives. External callers
963 see CPP_EOF only at EOF. Internal callers also see it when meeting
964 a directive inside a macro call, when at the end of a directive and
965 state.in_directive is still 1, and at the end of argument
968 cpp_get_token (pfile)
971 const cpp_token *result;
976 cpp_context *context = pfile->context;
978 /* Context->prev == 0 <=> base context. */
980 result = _cpp_lex_token (pfile);
981 else if (context->first.token != context->last.token)
983 if (context->direct_p)
984 result = context->first.token++;
986 result = *context->first.ptoken++;
988 if (result->flags & PASTE_LEFT)
990 paste_all_tokens (pfile, result);
991 if (pfile->state.in_directive)
993 return padding_token (pfile, result);
998 _cpp_pop_context (pfile);
999 if (pfile->state.in_directive)
1001 return &pfile->avoid_paste;
1004 if (result->type != CPP_NAME)
1007 node = result->val.node;
1009 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1012 if (!(node->flags & NODE_DISABLED))
1014 if (!pfile->state.prevent_expansion
1015 && enter_macro_context (pfile, node))
1017 if (pfile->state.in_directive)
1019 return padding_token (pfile, result);
1024 /* Flag this token as always unexpandable. */
1025 cpp_token *t = _cpp_temp_token (pfile);
1026 t->type = result->type;
1027 t->flags = result->flags | NO_EXPAND;
1028 t->val.str = result->val.str;
1038 /* Returns true if we're expanding an object-like macro that was
1039 defined in a system header. Just checks the macro at the top of
1040 the stack. Used for diagnostic suppression. */
1042 cpp_sys_macro_p (pfile)
1045 cpp_hashnode *node = pfile->context->macro;
1047 return node && node->value.macro && node->value.macro->syshdr;
1050 /* Read each token in, until EOF. Directives are transparently
1053 cpp_scan_nooutput (pfile)
1056 while (cpp_get_token (pfile)->type != CPP_EOF)
1060 /* Step back one (or more) tokens. Can only step mack more than 1 if
1061 they are from the lexer, and not from macro expansion. */
1063 _cpp_backup_tokens (pfile, count)
1067 if (pfile->context->prev == NULL)
1069 pfile->lookaheads += count;
1073 if (pfile->cur_token == pfile->cur_run->base)
1075 pfile->cur_run = pfile->cur_run->prev;
1076 pfile->cur_token = pfile->cur_run->limit;
1084 if (pfile->context->direct_p)
1085 pfile->context->first.token--;
1087 pfile->context->first.ptoken--;
1091 /* #define directive parsing and handling. */
1093 /* Returns non-zero if a macro redefinition warning is required. */
1095 warn_of_redefinition (pfile, node, macro2)
1097 const cpp_hashnode *node;
1098 const cpp_macro *macro2;
1100 const cpp_macro *macro1;
1103 /* Some redefinitions need to be warned about regardless. */
1104 if (node->flags & NODE_WARN)
1107 if (! CPP_PEDANTIC (pfile))
1110 /* Redefinition of a macro is allowed if and only if the old and new
1111 definitions are the same. (6.10.3 paragraph 2). */
1112 macro1 = node->value.macro;
1114 /* The quick failures. */
1115 if (macro1->count != macro2->count
1116 || macro1->paramc != macro2->paramc
1117 || macro1->fun_like != macro2->fun_like
1118 || macro1->variadic != macro2->variadic)
1121 /* Check each token. */
1122 for (i = 0; i < macro1->count; i++)
1123 if (! _cpp_equiv_tokens (¯o1->expansion[i], ¯o2->expansion[i]))
1126 /* Check parameter spellings. */
1127 for (i = 0; i < macro1->paramc; i++)
1128 if (macro1->params[i] != macro2->params[i])
1134 /* Free the definition of hashnode H. */
1137 _cpp_free_definition (h)
1140 /* Macros and assertions no longer have anything to free. */
1142 /* Clear builtin flag in case of redefinition. */
1143 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1146 /* Save parameter NODE to the parameter list of macro MACRO. Returns
1147 zero on success, non-zero if the paramter is a duplicate. */
1149 save_parameter (pfile, macro, node)
1154 /* Constraint 6.10.3.6 - duplicate parameter names. */
1155 if (node->arg_index)
1157 cpp_error (pfile, "duplicate macro parameter \"%s\"", NODE_NAME (node));
1161 if (BUFF_ROOM (pfile->a_buff)
1162 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1163 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1165 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1166 node->arg_index = macro->paramc;
1170 /* Check the syntax of the parameters in a MACRO definition. */
1172 parse_params (pfile, macro)
1176 unsigned int prev_ident = 0;
1180 const cpp_token *token = _cpp_lex_token (pfile);
1182 switch (token->type)
1185 cpp_error (pfile, "\"%s\" may not appear in macro parameter list",
1186 cpp_token_as_text (pfile, token));
1192 cpp_error (pfile, "macro parameters must be comma-separated");
1197 if (save_parameter (pfile, macro, token->val.node))
1201 case CPP_CLOSE_PAREN:
1202 if (prev_ident || macro->paramc == 0)
1205 /* Fall through to pick up the error. */
1209 cpp_error (pfile, "parameter name missing");
1216 macro->variadic = 1;
1219 save_parameter (pfile, macro, pfile->spec_nodes.n__VA_ARGS__);
1220 pfile->state.va_args_ok = 1;
1221 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1223 "anonymous variadic macros were introduced in C99");
1225 else if (CPP_OPTION (pfile, pedantic))
1226 cpp_pedwarn (pfile, "ISO C does not permit named variadic macros");
1228 /* We're at the end, and just expect a closing parenthesis. */
1229 token = _cpp_lex_token (pfile);
1230 if (token->type == CPP_CLOSE_PAREN)
1235 cpp_error (pfile, "missing ')' in macro parameter list");
1241 /* Allocate room for a token from a macro's replacement list. */
1243 alloc_expansion_token (pfile, macro)
1247 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1248 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1250 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1254 lex_expansion_token (pfile, macro)
1260 pfile->cur_token = alloc_expansion_token (pfile, macro);
1261 token = _cpp_lex_direct (pfile);
1263 /* Is this an argument? */
1264 if (token->type == CPP_NAME && token->val.node->arg_index)
1266 token->type = CPP_MACRO_ARG;
1267 token->val.arg_no = token->val.node->arg_index;
1269 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1270 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1271 check_trad_stringification (pfile, macro, &token->val.str);
1276 /* Parse a macro and save its expansion. Returns non-zero on success. */
1278 _cpp_create_definition (pfile, node)
1283 cpp_token *token, *saved_cur_token;
1284 const cpp_token *ctoken;
1285 unsigned int i, ok = 1;
1287 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1288 macro->line = pfile->directive_line;
1291 macro->variadic = 0;
1293 macro->fun_like = 0;
1295 /* Get the first token of the expansion (or the '(' of a
1296 function-like macro). */
1297 ctoken = _cpp_lex_token (pfile);
1299 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1301 ok = parse_params (pfile, macro);
1302 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1306 /* Success. Commit the parameter array. */
1307 BUFF_FRONT (pfile->a_buff) = (U_CHAR *) ¯o->params[macro->paramc];
1308 macro->fun_like = 1;
1310 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1311 cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
1313 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
1314 saved_cur_token = pfile->cur_token;
1316 if (macro->fun_like)
1317 token = lex_expansion_token (pfile, macro);
1320 token = alloc_expansion_token (pfile, macro);
1326 /* Check the stringifying # constraint 6.10.3.2.1 of
1327 function-like macros when lexing the subsequent token. */
1328 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1330 if (token->type == CPP_MACRO_ARG)
1332 token->flags &= ~PREV_WHITE;
1333 token->flags |= STRINGIFY_ARG;
1334 token->flags |= token[-1].flags & PREV_WHITE;
1335 token[-1] = token[0];
1338 /* Let assembler get away with murder. */
1339 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1342 cpp_error (pfile, "'#' is not followed by a macro parameter");
1347 if (token->type == CPP_EOF)
1350 /* Paste operator constraint 6.10.3.3.1. */
1351 if (token->type == CPP_PASTE)
1353 /* Token-paste ##, can appear in both object-like and
1354 function-like macros, but not at the ends. */
1355 if (--macro->count > 0)
1356 token = lex_expansion_token (pfile, macro);
1358 if (macro->count == 0 || token->type == CPP_EOF)
1362 "'##' cannot appear at either end of a macro expansion");
1366 token[-1].flags |= PASTE_LEFT;
1369 token = lex_expansion_token (pfile, macro);
1372 macro->expansion = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1374 /* Don't count the CPP_EOF. */
1377 /* Clear whitespace on first token for macro equivalence purposes. */
1379 macro->expansion[0].flags &= ~PREV_WHITE;
1381 /* Commit the memory. */
1382 BUFF_FRONT (pfile->a_buff) = (U_CHAR *) ¯o->expansion[macro->count];
1384 /* Implement the macro-defined-to-itself optimisation. */
1385 if (macro->count == 1 && !macro->fun_like
1386 && macro->expansion[0].type == CPP_NAME
1387 && macro->expansion[0].val.node == node)
1388 node->flags |= NODE_DISABLED;
1390 /* To suppress some diagnostics. */
1391 macro->syshdr = pfile->map->sysp != 0;
1393 if (node->type != NT_VOID)
1395 if (warn_of_redefinition (pfile, node, macro))
1397 cpp_pedwarn_with_line (pfile, pfile->directive_line, 0,
1398 "\"%s\" redefined", NODE_NAME (node));
1400 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1401 cpp_pedwarn_with_line (pfile, node->value.macro->line, 0,
1402 "this is the location of the previous definition");
1404 _cpp_free_definition (node);
1407 /* Enter definition in hash table. */
1408 node->type = NT_MACRO;
1409 node->value.macro = macro;
1410 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1411 node->flags |= NODE_WARN;
1415 /* Set type for SEEN_EOL() in cpplib.c, restore the lexer position. */
1416 saved_cur_token[-1].type = pfile->cur_token[-1].type;
1417 pfile->cur_token = saved_cur_token;
1421 /* Stop the lexer accepting __VA_ARGS__. */
1422 pfile->state.va_args_ok = 0;
1424 /* Clear the fast argument lookup indices. */
1425 for (i = macro->paramc; i-- > 0; )
1426 macro->params[i]->arg_index = 0;
1431 /* Warn if a token in `string' matches one of the function macro
1432 arguments in `info'. This function assumes that the macro is a
1433 function macro and not an object macro. */
1435 check_trad_stringification (pfile, macro, string)
1437 const cpp_macro *macro;
1438 const cpp_string *string;
1440 unsigned int i, len;
1441 const U_CHAR *p, *q, *limit = string->text + string->len;
1443 /* Loop over the string. */
1444 for (p = string->text; p < limit; p = q)
1446 /* Find the start of an identifier. */
1447 while (p < limit && !is_idstart (*p))
1450 /* Find the end of the identifier. */
1452 while (q < limit && is_idchar (*q))
1457 /* Loop over the function macro arguments to see if the
1458 identifier inside the string matches one of them. */
1459 for (i = 0; i < macro->paramc; i++)
1461 const cpp_hashnode *node = macro->params[i];
1463 if (NODE_LEN (node) == len
1464 && !memcmp (p, NODE_NAME (node), len))
1467 "macro argument \"%s\" would be stringified with -traditional.",
1475 /* Returns the name, arguments and expansion of a macro, in a format
1476 suitable to be read back in again, and therefore also for DWARF 2
1477 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1478 Caller is expected to generate the "#define" bit if needed. The
1479 returned text is temporary, and automatically freed later. */
1481 const unsigned char *
1482 cpp_macro_definition (pfile, node)
1484 const cpp_hashnode *node;
1486 unsigned int i, len;
1487 const cpp_macro *macro = node->value.macro;
1488 unsigned char *buffer;
1490 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1492 cpp_ice (pfile, "invalid hash type %d in cpp_macro_definition", node->type);
1496 /* Calculate length. */
1497 len = NODE_LEN (node) + 1; /* ' ' */
1498 if (macro->fun_like)
1500 len += 3; /* "()" plus possible final "." of named
1501 varargs (we have + 2 below). */
1502 for (i = 0; i < macro->paramc; i++)
1503 len += NODE_LEN (macro->params[i]) + 2; /* ", " */
1506 for (i = 0; i < macro->count; i++)
1508 cpp_token *token = ¯o->expansion[i];
1510 if (token->type == CPP_MACRO_ARG)
1511 len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1513 len += cpp_token_len (token); /* Includes room for ' '. */
1514 if (token->flags & STRINGIFY_ARG)
1516 if (token->flags & PASTE_LEFT)
1517 len += 3; /* " ##" */
1520 if (len > pfile->macro_buffer_len)
1522 pfile->macro_buffer = (U_CHAR *) xrealloc (pfile->macro_buffer, len);
1523 pfile->macro_buffer_len = len;
1526 /* Fill in the buffer. Start with the macro name. */
1527 buffer = pfile->macro_buffer;
1528 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1529 buffer += NODE_LEN (node);
1531 /* Parameter names. */
1532 if (macro->fun_like)
1535 for (i = 0; i < macro->paramc; i++)
1537 cpp_hashnode *param = macro->params[i];
1539 if (param != pfile->spec_nodes.n__VA_ARGS__)
1541 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1542 buffer += NODE_LEN (param);
1545 if (i + 1 < macro->paramc)
1546 *buffer++ = ',', *buffer++ = ' ';
1547 else if (macro->variadic)
1548 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1553 /* Expansion tokens. */
1557 for (i = 0; i < macro->count; i++)
1559 cpp_token *token = ¯o->expansion[i];
1561 if (token->flags & PREV_WHITE)
1563 if (token->flags & STRINGIFY_ARG)
1566 if (token->type == CPP_MACRO_ARG)
1568 len = NODE_LEN (macro->params[token->val.arg_no - 1]);
1570 NODE_NAME (macro->params[token->val.arg_no - 1]), len);
1574 buffer = cpp_spell_token (pfile, token, buffer);
1576 if (token->flags & PASTE_LEFT)
1581 /* Next has PREV_WHITE; see _cpp_create_definition. */
1587 return pfile->macro_buffer;