* ChangeLog: Follow spelling conventions.
[official-gcc.git] / gcc / cppmacro.c
blobb8fb792de885aed425d90d987b3a426f7202def9
1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4 Written by Per Bothner, 1994.
5 Based on CCCP program by Paul Rubin, June 1986
6 Adapted to ANSI C, Richard Stallman, Jan 1987
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
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! */
26 #include "config.h"
27 #include "system.h"
28 #include "cpplib.h"
29 #include "cpphash.h"
31 typedef struct macro_arg macro_arg;
32 struct macro_arg
34 const cpp_token **first; /* First token in unexpanded argument. */
35 const cpp_token **expanded; /* Macro-expanded argument. */
36 const cpp_token *stringified; /* Stringified argument. */
37 unsigned int count; /* # of tokens in argument. */
38 unsigned int expanded_count; /* # of tokens in expanded argument. */
41 /* Macro expansion. */
43 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
44 static int builtin_macro PARAMS ((cpp_reader *, cpp_hashnode *));
45 static void push_token_context
46 PARAMS ((cpp_reader *, cpp_hashnode *, const cpp_token *, unsigned int));
47 static void push_ptoken_context
48 PARAMS ((cpp_reader *, cpp_hashnode *, _cpp_buff *,
49 const cpp_token **, unsigned int));
50 static _cpp_buff *collect_args PARAMS ((cpp_reader *, const cpp_hashnode *));
51 static cpp_context *next_context PARAMS ((cpp_reader *));
52 static const cpp_token *padding_token
53 PARAMS ((cpp_reader *, const cpp_token *));
54 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
55 static const cpp_token *new_string_token PARAMS ((cpp_reader *, uchar *,
56 unsigned int));
57 static const cpp_token *stringify_arg PARAMS ((cpp_reader *, macro_arg *));
58 static void paste_all_tokens PARAMS ((cpp_reader *, const cpp_token *));
59 static bool paste_tokens PARAMS ((cpp_reader *, const cpp_token **,
60 const cpp_token *));
61 static void replace_args PARAMS ((cpp_reader *, cpp_hashnode *, cpp_macro *,
62 macro_arg *));
63 static _cpp_buff *funlike_invocation_p PARAMS ((cpp_reader *, cpp_hashnode *));
64 static bool create_iso_definition PARAMS ((cpp_reader *, cpp_macro *));
66 /* #define directive parsing and handling. */
68 static cpp_token *alloc_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
69 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
70 static bool warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
71 const cpp_macro *));
72 static bool parse_params PARAMS ((cpp_reader *, cpp_macro *));
73 static void check_trad_stringification PARAMS ((cpp_reader *,
74 const cpp_macro *,
75 const cpp_string *));
77 /* Emits a warning if NODE is a macro defined in the main file that
78 has not been used. */
79 int
80 _cpp_warn_if_unused_macro (pfile, node, v)
81 cpp_reader *pfile;
82 cpp_hashnode *node;
83 void *v ATTRIBUTE_UNUSED;
85 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
87 cpp_macro *macro = node->value.macro;
89 if (!macro->used
90 /* Skip front-end built-ins and command line macros. */
91 && macro->line >= pfile->first_unused_line
92 && MAIN_FILE_P (lookup_line (&pfile->line_maps, macro->line)))
93 cpp_error_with_line (pfile, DL_WARNING, macro->line, 0,
94 "macro \"%s\" is not used", NODE_NAME (node));
97 return 1;
100 /* Allocates and returns a CPP_STRING token, containing TEXT of length
101 LEN, after null-terminating it. TEXT must be in permanent storage. */
102 static const cpp_token *
103 new_string_token (pfile, text, len)
104 cpp_reader *pfile;
105 unsigned char *text;
106 unsigned int len;
108 cpp_token *token = _cpp_temp_token (pfile);
110 text[len] = '\0';
111 token->type = CPP_STRING;
112 token->val.str.len = len;
113 token->val.str.text = text;
114 token->flags = 0;
115 return token;
118 static const char * const monthnames[] =
120 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
121 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
124 /* Handle builtin macros like __FILE__, and push the resulting token
125 on the context stack. Also handles _Pragma, for which no new token
126 is created. Returns 1 if it generates a new token context, 0 to
127 return the token to the caller. */
128 const uchar *
129 _cpp_builtin_macro_text (pfile, node)
130 cpp_reader *pfile;
131 cpp_hashnode *node;
133 const uchar *result = NULL;
134 unsigned int number = 1;
136 switch (node->value.builtin)
138 default:
139 cpp_error (pfile, DL_ICE, "invalid built-in macro \"%s\"",
140 NODE_NAME (node));
141 break;
143 case BT_FILE:
144 case BT_BASE_FILE:
146 unsigned int len;
147 const char *name;
148 uchar *buf;
149 const struct line_map *map = pfile->map;
151 if (node->value.builtin == BT_BASE_FILE)
152 while (! MAIN_FILE_P (map))
153 map = INCLUDED_FROM (&pfile->line_maps, map);
155 name = map->to_file;
156 len = strlen (name);
157 buf = _cpp_unaligned_alloc (pfile, len * 4 + 3);
158 result = buf;
159 *buf = '"';
160 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
161 *buf++ = '"';
162 *buf = '\0';
164 break;
166 case BT_INCLUDE_LEVEL:
167 /* The line map depth counts the primary source as level 1, but
168 historically __INCLUDE_DEPTH__ has called the primary source
169 level 0. */
170 number = pfile->line_maps.depth - 1;
171 break;
173 case BT_SPECLINE:
174 /* If __LINE__ is embedded in a macro, it must expand to the
175 line of the macro's invocation, not its definition.
176 Otherwise things like assert() will not work properly. */
177 if (CPP_OPTION (pfile, traditional))
178 number = pfile->line;
179 else
180 number = pfile->cur_token[-1].line;
181 number = SOURCE_LINE (pfile->map, number);
182 break;
184 /* __STDC__ has the value 1 under normal circumstances.
185 However, if (a) we are in a system header, (b) the option
186 stdc_0_in_system_headers is true (set by target config), and
187 (c) we are not in strictly conforming mode, then it has the
188 value 0. */
189 case BT_STDC:
191 if (CPP_IN_SYSTEM_HEADER (pfile)
192 && CPP_OPTION (pfile, stdc_0_in_system_headers)
193 && !CPP_OPTION (pfile,std))
194 number = 0;
195 else
196 number = 1;
198 break;
200 case BT_DATE:
201 case BT_TIME:
202 if (pfile->date == NULL)
204 /* Allocate __DATE__ and __TIME__ strings from permanent
205 storage. We only do this once, and don't generate them
206 at init time, because time() and localtime() are very
207 slow on some systems. */
208 time_t tt;
209 struct tm *tb = NULL;
211 /* (time_t) -1 is a legitimate value for "number of seconds
212 since the Epoch", so we have to do a little dance to
213 distinguish that from a genuine error. */
214 errno = 0;
215 tt = time(NULL);
216 if (tt != (time_t)-1 || errno == 0)
217 tb = localtime (&tt);
219 if (tb)
221 pfile->date = _cpp_unaligned_alloc (pfile,
222 sizeof ("\"Oct 11 1347\""));
223 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
224 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
226 pfile->time = _cpp_unaligned_alloc (pfile,
227 sizeof ("\"12:34:56\""));
228 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
229 tb->tm_hour, tb->tm_min, tb->tm_sec);
231 else
233 cpp_errno (pfile, DL_WARNING,
234 "could not determine date and time");
236 pfile->date = U"\"??? ?? ????\"";
237 pfile->time = U"\"??:??:??\"";
241 if (node->value.builtin == BT_DATE)
242 result = pfile->date;
243 else
244 result = pfile->time;
245 break;
248 if (result == NULL)
250 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
251 result = _cpp_unaligned_alloc (pfile, 21);
252 sprintf ((char *) result, "%u", number);
255 return result;
258 /* Convert builtin macros like __FILE__ to a token and push it on the
259 context stack. Also handles _Pragma, for which no new token is
260 created. Returns 1 if it generates a new token context, 0 to
261 return the token to the caller. */
262 static int
263 builtin_macro (pfile, node)
264 cpp_reader *pfile;
265 cpp_hashnode *node;
267 const uchar *buf;
269 if (node->value.builtin == BT_PRAGMA)
271 /* Don't interpret _Pragma within directives. The standard is
272 not clear on this, but to me this makes most sense. */
273 if (pfile->state.in_directive)
274 return 0;
276 _cpp_do__Pragma (pfile);
277 return 1;
280 buf = _cpp_builtin_macro_text (pfile, node);
282 cpp_push_buffer (pfile, buf, ustrlen (buf), /* from_stage3 */ true, 1);
284 /* Tweak the column number the lexer will report. */
285 pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
287 /* We don't want a leading # to be interpreted as a directive. */
288 pfile->buffer->saved_flags = 0;
290 /* Set pfile->cur_token as required by _cpp_lex_direct. */
291 pfile->cur_token = _cpp_temp_token (pfile);
292 push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
293 if (pfile->buffer->cur != pfile->buffer->rlimit)
294 cpp_error (pfile, DL_ICE, "invalid built-in macro \"%s\"",
295 NODE_NAME (node));
296 _cpp_pop_buffer (pfile);
298 return 1;
301 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
302 backslashes and double quotes. Non-printable characters are
303 converted to octal. DEST must be of sufficient size. Returns
304 a pointer to the end of the string. */
305 uchar *
306 cpp_quote_string (dest, src, len)
307 uchar *dest;
308 const uchar *src;
309 unsigned int len;
311 while (len--)
313 uchar c = *src++;
315 if (c == '\\' || c == '"')
317 *dest++ = '\\';
318 *dest++ = c;
320 else
322 if (ISPRINT (c))
323 *dest++ = c;
324 else
326 sprintf ((char *) dest, "\\%03o", c);
327 dest += 4;
332 return dest;
335 /* Convert a token sequence ARG to a single string token according to
336 the rules of the ISO C #-operator. */
337 static const cpp_token *
338 stringify_arg (pfile, arg)
339 cpp_reader *pfile;
340 macro_arg *arg;
342 unsigned char *dest = BUFF_FRONT (pfile->u_buff);
343 unsigned int i, escape_it, backslash_count = 0;
344 const cpp_token *source = NULL;
345 size_t len;
347 /* Loop, reading in the argument's tokens. */
348 for (i = 0; i < arg->count; i++)
350 const cpp_token *token = arg->first[i];
352 if (token->type == CPP_PADDING)
354 if (source == NULL)
355 source = token->val.source;
356 continue;
359 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
360 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
362 /* Room for each char being written in octal, initial space and
363 final NUL. */
364 len = cpp_token_len (token);
365 if (escape_it)
366 len *= 4;
367 len += 2;
369 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
371 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
372 _cpp_extend_buff (pfile, &pfile->u_buff, len);
373 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
376 /* Leading white space? */
377 if (dest != BUFF_FRONT (pfile->u_buff))
379 if (source == NULL)
380 source = token;
381 if (source->flags & PREV_WHITE)
382 *dest++ = ' ';
384 source = NULL;
386 if (escape_it)
388 _cpp_buff *buff = _cpp_get_buff (pfile, len);
389 unsigned char *buf = BUFF_FRONT (buff);
390 len = cpp_spell_token (pfile, token, buf) - buf;
391 dest = cpp_quote_string (dest, buf, len);
392 _cpp_release_buff (pfile, buff);
394 else
395 dest = cpp_spell_token (pfile, token, dest);
397 if (token->type == CPP_OTHER && token->val.c == '\\')
398 backslash_count++;
399 else
400 backslash_count = 0;
403 /* Ignore the final \ of invalid string literals. */
404 if (backslash_count & 1)
406 cpp_error (pfile, DL_WARNING,
407 "invalid string literal, ignoring final '\\'");
408 dest--;
411 /* Commit the memory, including NUL, and return the token. */
412 len = dest - BUFF_FRONT (pfile->u_buff);
413 BUFF_FRONT (pfile->u_buff) = dest + 1;
414 return new_string_token (pfile, dest - len, len);
417 /* Try to paste two tokens. On success, return nonzero. In any
418 case, PLHS is updated to point to the pasted token, which is
419 guaranteed to not have the PASTE_LEFT flag set. */
420 static bool
421 paste_tokens (pfile, plhs, rhs)
422 cpp_reader *pfile;
423 const cpp_token **plhs, *rhs;
425 unsigned char *buf, *end;
426 const cpp_token *lhs;
427 unsigned int len;
428 bool valid;
430 lhs = *plhs;
431 len = cpp_token_len (lhs) + cpp_token_len (rhs) + 1;
432 buf = (unsigned char *) alloca (len);
433 end = cpp_spell_token (pfile, lhs, buf);
435 /* Avoid comment headers, since they are still processed in stage 3.
436 It is simpler to insert a space here, rather than modifying the
437 lexer to ignore comments in some circumstances. Simply returning
438 false doesn't work, since we want to clear the PASTE_LEFT flag. */
439 if (lhs->type == CPP_DIV
440 && (rhs->type == CPP_MULT || rhs->type == CPP_DIV))
441 *end++ = ' ';
442 end = cpp_spell_token (pfile, rhs, end);
443 *end = '\0';
445 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true, 1);
447 /* Tweak the column number the lexer will report. */
448 pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
450 /* We don't want a leading # to be interpreted as a directive. */
451 pfile->buffer->saved_flags = 0;
453 /* Set pfile->cur_token as required by _cpp_lex_direct. */
454 pfile->cur_token = _cpp_temp_token (pfile);
455 *plhs = _cpp_lex_direct (pfile);
456 valid = pfile->buffer->cur == pfile->buffer->rlimit;
457 _cpp_pop_buffer (pfile);
459 return valid;
462 /* Handles an arbitrarily long sequence of ## operators, with initial
463 operand LHS. This implementation is left-associative,
464 non-recursive, and finishes a paste before handling succeeding
465 ones. If a paste fails, we back up to the RHS of the failing ##
466 operator before pushing the context containing the result of prior
467 successful pastes, with the effect that the RHS appears in the
468 output stream after the pasted LHS normally. */
469 static void
470 paste_all_tokens (pfile, lhs)
471 cpp_reader *pfile;
472 const cpp_token *lhs;
474 const cpp_token *rhs;
475 cpp_context *context = pfile->context;
479 /* Take the token directly from the current context. We can do
480 this, because we are in the replacement list of either an
481 object-like macro, or a function-like macro with arguments
482 inserted. In either case, the constraints to #define
483 guarantee we have at least one more token. */
484 if (context->direct_p)
485 rhs = FIRST (context).token++;
486 else
487 rhs = *FIRST (context).ptoken++;
489 if (rhs->type == CPP_PADDING)
490 abort ();
492 if (!paste_tokens (pfile, &lhs, rhs))
494 _cpp_backup_tokens (pfile, 1);
496 /* Mandatory error for all apart from assembler. */
497 if (CPP_OPTION (pfile, lang) != CLK_ASM)
498 cpp_error (pfile, DL_ERROR,
499 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
500 cpp_token_as_text (pfile, lhs),
501 cpp_token_as_text (pfile, rhs));
502 break;
505 while (rhs->flags & PASTE_LEFT);
507 /* Put the resulting token in its own context. */
508 push_token_context (pfile, NULL, lhs, 1);
511 /* Returns TRUE if the number of arguments ARGC supplied in an
512 invocation of the MACRO referenced by NODE is valid. An empty
513 invocation to a macro with no parameters should pass ARGC as zero.
515 Note that MACRO cannot necessarily be deduced from NODE, in case
516 NODE was redefined whilst collecting arguments. */
517 bool
518 _cpp_arguments_ok (pfile, macro, node, argc)
519 cpp_reader *pfile;
520 cpp_macro *macro;
521 const cpp_hashnode *node;
522 unsigned int argc;
524 if (argc == macro->paramc)
525 return true;
527 if (argc < macro->paramc)
529 /* As an extension, a rest argument is allowed to not appear in
530 the invocation at all.
531 e.g. #define debug(format, args...) something
532 debug("string");
534 This is exactly the same as if there had been an empty rest
535 argument - debug("string", ). */
537 if (argc + 1 == macro->paramc && macro->variadic)
539 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
540 cpp_error (pfile, DL_PEDWARN,
541 "ISO C99 requires rest arguments to be used");
542 return true;
545 cpp_error (pfile, DL_ERROR,
546 "macro \"%s\" requires %u arguments, but only %u given",
547 NODE_NAME (node), macro->paramc, argc);
549 else
550 cpp_error (pfile, DL_ERROR,
551 "macro \"%s\" passed %u arguments, but takes just %u",
552 NODE_NAME (node), argc, macro->paramc);
554 return false;
557 /* Reads and returns the arguments to a function-like macro
558 invocation. Assumes the opening parenthesis has been processed.
559 If there is an error, emits an appropriate diagnostic and returns
560 NULL. Each argument is terminated by a CPP_EOF token, for the
561 future benefit of expand_arg(). */
562 static _cpp_buff *
563 collect_args (pfile, node)
564 cpp_reader *pfile;
565 const cpp_hashnode *node;
567 _cpp_buff *buff, *base_buff;
568 cpp_macro *macro;
569 macro_arg *args, *arg;
570 const cpp_token *token;
571 unsigned int argc;
573 macro = node->value.macro;
574 if (macro->paramc)
575 argc = macro->paramc;
576 else
577 argc = 1;
578 buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
579 + sizeof (macro_arg)));
580 base_buff = buff;
581 args = (macro_arg *) buff->base;
582 memset (args, 0, argc * sizeof (macro_arg));
583 buff->cur = (unsigned char *) &args[argc];
584 arg = args, argc = 0;
586 /* Collect the tokens making up each argument. We don't yet know
587 how many arguments have been supplied, whether too many or too
588 few. Hence the slightly bizarre usage of "argc" and "arg". */
591 unsigned int paren_depth = 0;
592 unsigned int ntokens = 0;
594 argc++;
595 arg->first = (const cpp_token **) buff->cur;
597 for (;;)
599 /* Require space for 2 new tokens (including a CPP_EOF). */
600 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
602 buff = _cpp_append_extend_buff (pfile, buff,
603 1000 * sizeof (cpp_token *));
604 arg->first = (const cpp_token **) buff->cur;
607 token = cpp_get_token (pfile);
609 if (token->type == CPP_PADDING)
611 /* Drop leading padding. */
612 if (ntokens == 0)
613 continue;
615 else if (token->type == CPP_OPEN_PAREN)
616 paren_depth++;
617 else if (token->type == CPP_CLOSE_PAREN)
619 if (paren_depth-- == 0)
620 break;
622 else if (token->type == CPP_COMMA)
624 /* A comma does not terminate an argument within
625 parentheses or as part of a variable argument. */
626 if (paren_depth == 0
627 && ! (macro->variadic && argc == macro->paramc))
628 break;
630 else if (token->type == CPP_EOF
631 || (token->type == CPP_HASH && token->flags & BOL))
632 break;
634 arg->first[ntokens++] = token;
637 /* Drop trailing padding. */
638 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
639 ntokens--;
641 arg->count = ntokens;
642 arg->first[ntokens] = &pfile->eof;
644 /* Terminate the argument. Excess arguments loop back and
645 overwrite the final legitimate argument, before failing. */
646 if (argc <= macro->paramc)
648 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
649 if (argc != macro->paramc)
650 arg++;
653 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
655 if (token->type == CPP_EOF)
657 /* We still need the CPP_EOF to end directives, and to end
658 pre-expansion of a macro argument. Step back is not
659 unconditional, since we don't want to return a CPP_EOF to our
660 callers at the end of an -include-d file. */
661 if (pfile->context->prev || pfile->state.in_directive)
662 _cpp_backup_tokens (pfile, 1);
663 cpp_error (pfile, DL_ERROR,
664 "unterminated argument list invoking macro \"%s\"",
665 NODE_NAME (node));
667 else
669 /* A single empty argument is counted as no argument. */
670 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
671 argc = 0;
672 if (_cpp_arguments_ok (pfile, macro, node, argc))
674 /* GCC has special semantics for , ## b where b is a varargs
675 parameter: we remove the comma if b was omitted entirely.
676 If b was merely an empty argument, the comma is retained.
677 If the macro takes just one (varargs) parameter, then we
678 retain the comma only if we are standards conforming.
680 If FIRST is NULL replace_args () swallows the comma. */
681 if (macro->variadic && (argc < macro->paramc
682 || (argc == 1 && args[0].count == 0
683 && !CPP_OPTION (pfile, std))))
684 args[macro->paramc - 1].first = NULL;
685 return base_buff;
689 /* An error occurred. */
690 _cpp_release_buff (pfile, base_buff);
691 return NULL;
694 /* Search for an opening parenthesis to the macro of NODE, in such a
695 way that, if none is found, we don't lose the information in any
696 intervening padding tokens. If we find the parenthesis, collect
697 the arguments and return the buffer containing them. */
698 static _cpp_buff *
699 funlike_invocation_p (pfile, node)
700 cpp_reader *pfile;
701 cpp_hashnode *node;
703 const cpp_token *token, *padding = NULL;
705 for (;;)
707 token = cpp_get_token (pfile);
708 if (token->type != CPP_PADDING)
709 break;
710 if (padding == NULL
711 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
712 padding = token;
715 if (token->type == CPP_OPEN_PAREN)
717 pfile->state.parsing_args = 2;
718 return collect_args (pfile, node);
721 /* CPP_EOF can be the end of macro arguments, or the end of the
722 file. We mustn't back up over the latter. Ugh. */
723 if (token->type != CPP_EOF || token == &pfile->eof)
725 /* Back up. We may have skipped padding, in which case backing
726 up more than one token when expanding macros is in general
727 too difficult. We re-insert it in its own context. */
728 _cpp_backup_tokens (pfile, 1);
729 if (padding)
730 push_token_context (pfile, NULL, padding, 1);
733 return NULL;
736 /* Push the context of a macro with hash entry NODE onto the context
737 stack. If we can successfully expand the macro, we push a context
738 containing its yet-to-be-rescanned replacement list and return one.
739 Otherwise, we don't push a context and return zero. */
740 static int
741 enter_macro_context (pfile, node)
742 cpp_reader *pfile;
743 cpp_hashnode *node;
745 /* The presence of a macro invalidates a file's controlling macro. */
746 pfile->mi_valid = false;
748 pfile->state.angled_headers = false;
750 /* Handle standard macros. */
751 if (! (node->flags & NODE_BUILTIN))
753 cpp_macro *macro = node->value.macro;
755 if (macro->fun_like)
757 _cpp_buff *buff;
759 pfile->state.prevent_expansion++;
760 pfile->keep_tokens++;
761 pfile->state.parsing_args = 1;
762 buff = funlike_invocation_p (pfile, node);
763 pfile->state.parsing_args = 0;
764 pfile->keep_tokens--;
765 pfile->state.prevent_expansion--;
767 if (buff == NULL)
769 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
770 cpp_error (pfile, DL_WARNING,
771 "function-like macro \"%s\" must be used with arguments in traditional C",
772 NODE_NAME (node));
774 return 0;
777 if (macro->paramc > 0)
778 replace_args (pfile, node, macro, (macro_arg *) buff->base);
779 _cpp_release_buff (pfile, buff);
782 /* Disable the macro within its expansion. */
783 node->flags |= NODE_DISABLED;
785 macro->used = 1;
787 if (macro->paramc == 0)
788 push_token_context (pfile, node, macro->exp.tokens, macro->count);
790 return 1;
793 /* Handle built-in macros and the _Pragma operator. */
794 return builtin_macro (pfile, node);
797 /* Replace the parameters in a function-like macro of NODE with the
798 actual ARGS, and place the result in a newly pushed token context.
799 Expand each argument before replacing, unless it is operated upon
800 by the # or ## operators. */
801 static void
802 replace_args (pfile, node, macro, args)
803 cpp_reader *pfile;
804 cpp_hashnode *node;
805 cpp_macro *macro;
806 macro_arg *args;
808 unsigned int i, total;
809 const cpp_token *src, *limit;
810 const cpp_token **dest, **first;
811 macro_arg *arg;
812 _cpp_buff *buff;
814 /* First, fully macro-expand arguments, calculating the number of
815 tokens in the final expansion as we go. The ordering of the if
816 statements below is subtle; we must handle stringification before
817 pasting. */
818 total = macro->count;
819 limit = macro->exp.tokens + macro->count;
821 for (src = macro->exp.tokens; src < limit; src++)
822 if (src->type == CPP_MACRO_ARG)
824 /* Leading and trailing padding tokens. */
825 total += 2;
827 /* We have an argument. If it is not being stringified or
828 pasted it is macro-replaced before insertion. */
829 arg = &args[src->val.arg_no - 1];
831 if (src->flags & STRINGIFY_ARG)
833 if (!arg->stringified)
834 arg->stringified = stringify_arg (pfile, arg);
836 else if ((src->flags & PASTE_LEFT)
837 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
838 total += arg->count - 1;
839 else
841 if (!arg->expanded)
842 expand_arg (pfile, arg);
843 total += arg->expanded_count - 1;
847 /* Now allocate space for the expansion, copy the tokens and replace
848 the arguments. */
849 buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
850 first = (const cpp_token **) buff->base;
851 dest = first;
853 for (src = macro->exp.tokens; src < limit; src++)
855 unsigned int count;
856 const cpp_token **from, **paste_flag;
858 if (src->type != CPP_MACRO_ARG)
860 *dest++ = src;
861 continue;
864 paste_flag = 0;
865 arg = &args[src->val.arg_no - 1];
866 if (src->flags & STRINGIFY_ARG)
867 count = 1, from = &arg->stringified;
868 else if (src->flags & PASTE_LEFT)
869 count = arg->count, from = arg->first;
870 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
872 count = arg->count, from = arg->first;
873 if (dest != first)
875 if (dest[-1]->type == CPP_COMMA
876 && macro->variadic
877 && src->val.arg_no == macro->paramc)
879 /* Swallow a pasted comma if from == NULL, otherwise
880 drop the paste flag. */
881 if (from == NULL)
882 dest--;
883 else
884 paste_flag = dest - 1;
886 /* Remove the paste flag if the RHS is a placemarker. */
887 else if (count == 0)
888 paste_flag = dest - 1;
891 else
892 count = arg->expanded_count, from = arg->expanded;
894 /* Padding on the left of an argument (unless RHS of ##). */
895 if (!pfile->state.in_directive
896 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
897 *dest++ = padding_token (pfile, src);
899 if (count)
901 memcpy (dest, from, count * sizeof (cpp_token *));
902 dest += count;
904 /* With a non-empty argument on the LHS of ##, the last
905 token should be flagged PASTE_LEFT. */
906 if (src->flags & PASTE_LEFT)
907 paste_flag = dest - 1;
910 /* Avoid paste on RHS (even case count == 0). */
911 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
912 *dest++ = &pfile->avoid_paste;
914 /* Add a new paste flag, or remove an unwanted one. */
915 if (paste_flag)
917 cpp_token *token = _cpp_temp_token (pfile);
918 token->type = (*paste_flag)->type;
919 token->val.str = (*paste_flag)->val.str;
920 if (src->flags & PASTE_LEFT)
921 token->flags = (*paste_flag)->flags | PASTE_LEFT;
922 else
923 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
924 *paste_flag = token;
928 /* Free the expanded arguments. */
929 for (i = 0; i < macro->paramc; i++)
930 if (args[i].expanded)
931 free (args[i].expanded);
933 push_ptoken_context (pfile, node, buff, first, dest - first);
936 /* Return a special padding token, with padding inherited from SOURCE. */
937 static const cpp_token *
938 padding_token (pfile, source)
939 cpp_reader *pfile;
940 const cpp_token *source;
942 cpp_token *result = _cpp_temp_token (pfile);
944 result->type = CPP_PADDING;
945 result->val.source = source;
946 result->flags = 0;
947 return result;
950 /* Get a new uninitialized context. Create a new one if we cannot
951 re-use an old one. */
952 static cpp_context *
953 next_context (pfile)
954 cpp_reader *pfile;
956 cpp_context *result = pfile->context->next;
958 if (result == 0)
960 result = xnew (cpp_context);
961 result->prev = pfile->context;
962 result->next = 0;
963 pfile->context->next = result;
966 pfile->context = result;
967 return result;
970 /* Push a list of pointers to tokens. */
971 static void
972 push_ptoken_context (pfile, macro, buff, first, count)
973 cpp_reader *pfile;
974 cpp_hashnode *macro;
975 _cpp_buff *buff;
976 const cpp_token **first;
977 unsigned int count;
979 cpp_context *context = next_context (pfile);
981 context->direct_p = false;
982 context->macro = macro;
983 context->buff = buff;
984 FIRST (context).ptoken = first;
985 LAST (context).ptoken = first + count;
988 /* Push a list of tokens. */
989 static void
990 push_token_context (pfile, macro, first, count)
991 cpp_reader *pfile;
992 cpp_hashnode *macro;
993 const cpp_token *first;
994 unsigned int count;
996 cpp_context *context = next_context (pfile);
998 context->direct_p = true;
999 context->macro = macro;
1000 context->buff = NULL;
1001 FIRST (context).token = first;
1002 LAST (context).token = first + count;
1005 /* Push a traditional macro's replacement text. */
1006 void
1007 _cpp_push_text_context (pfile, macro, start, len)
1008 cpp_reader *pfile;
1009 cpp_hashnode *macro;
1010 const uchar *start;
1011 size_t len;
1013 cpp_context *context = next_context (pfile);
1015 context->direct_p = true;
1016 context->macro = macro;
1017 context->buff = NULL;
1018 CUR (context) = start;
1019 RLIMIT (context) = start + len;
1020 macro->flags |= NODE_DISABLED;
1023 /* Expand an argument ARG before replacing parameters in a
1024 function-like macro. This works by pushing a context with the
1025 argument's tokens, and then expanding that into a temporary buffer
1026 as if it were a normal part of the token stream. collect_args()
1027 has terminated the argument's tokens with a CPP_EOF so that we know
1028 when we have fully expanded the argument. */
1029 static void
1030 expand_arg (pfile, arg)
1031 cpp_reader *pfile;
1032 macro_arg *arg;
1034 unsigned int capacity;
1035 bool saved_warn_trad;
1037 if (arg->count == 0)
1038 return;
1040 /* Don't warn about funlike macros when pre-expanding. */
1041 saved_warn_trad = CPP_WTRADITIONAL (pfile);
1042 CPP_WTRADITIONAL (pfile) = 0;
1044 /* Loop, reading in the arguments. */
1045 capacity = 256;
1046 arg->expanded = (const cpp_token **)
1047 xmalloc (capacity * sizeof (cpp_token *));
1049 push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
1050 for (;;)
1052 const cpp_token *token;
1054 if (arg->expanded_count + 1 >= capacity)
1056 capacity *= 2;
1057 arg->expanded = (const cpp_token **)
1058 xrealloc (arg->expanded, capacity * sizeof (cpp_token *));
1061 token = cpp_get_token (pfile);
1063 if (token->type == CPP_EOF)
1064 break;
1066 arg->expanded[arg->expanded_count++] = token;
1069 _cpp_pop_context (pfile);
1071 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
1074 /* Pop the current context off the stack, re-enabling the macro if the
1075 context represented a macro's replacement list. The context
1076 structure is not freed so that we can re-use it later. */
1077 void
1078 _cpp_pop_context (pfile)
1079 cpp_reader *pfile;
1081 cpp_context *context = pfile->context;
1083 if (context->macro)
1084 context->macro->flags &= ~NODE_DISABLED;
1086 if (context->buff)
1087 _cpp_release_buff (pfile, context->buff);
1089 pfile->context = context->prev;
1092 /* Eternal routine to get a token. Also used nearly everywhere
1093 internally, except for places where we know we can safely call
1094 the lexer directly, such as lexing a directive name.
1096 Macro expansions and directives are transparently handled,
1097 including entering included files. Thus tokens are post-macro
1098 expansion, and after any intervening directives. External callers
1099 see CPP_EOF only at EOF. Internal callers also see it when meeting
1100 a directive inside a macro call, when at the end of a directive and
1101 state.in_directive is still 1, and at the end of argument
1102 pre-expansion. */
1103 const cpp_token *
1104 cpp_get_token (pfile)
1105 cpp_reader *pfile;
1107 const cpp_token *result;
1109 for (;;)
1111 cpp_hashnode *node;
1112 cpp_context *context = pfile->context;
1114 /* Context->prev == 0 <=> base context. */
1115 if (!context->prev)
1116 result = _cpp_lex_token (pfile);
1117 else if (FIRST (context).token != LAST (context).token)
1119 if (context->direct_p)
1120 result = FIRST (context).token++;
1121 else
1122 result = *FIRST (context).ptoken++;
1124 if (result->flags & PASTE_LEFT)
1126 paste_all_tokens (pfile, result);
1127 if (pfile->state.in_directive)
1128 continue;
1129 return padding_token (pfile, result);
1132 else
1134 _cpp_pop_context (pfile);
1135 if (pfile->state.in_directive)
1136 continue;
1137 return &pfile->avoid_paste;
1140 if (pfile->state.in_directive && result->type == CPP_COMMENT)
1141 continue;
1143 if (result->type != CPP_NAME)
1144 break;
1146 node = result->val.node;
1148 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1149 break;
1151 if (!(node->flags & NODE_DISABLED))
1153 if (!pfile->state.prevent_expansion
1154 && enter_macro_context (pfile, node))
1156 if (pfile->state.in_directive)
1157 continue;
1158 return padding_token (pfile, result);
1161 else
1163 /* Flag this token as always unexpandable. FIXME: move this
1164 to collect_args()?. */
1165 cpp_token *t = _cpp_temp_token (pfile);
1166 t->type = result->type;
1167 t->flags = result->flags | NO_EXPAND;
1168 t->val.str = result->val.str;
1169 result = t;
1172 break;
1175 return result;
1178 /* Returns true if we're expanding an object-like macro that was
1179 defined in a system header. Just checks the macro at the top of
1180 the stack. Used for diagnostic suppression. */
1182 cpp_sys_macro_p (pfile)
1183 cpp_reader *pfile;
1185 cpp_hashnode *node = pfile->context->macro;
1187 return node && node->value.macro && node->value.macro->syshdr;
1190 /* Read each token in, until end of the current file. Directives are
1191 transparently processed. */
1192 void
1193 cpp_scan_nooutput (pfile)
1194 cpp_reader *pfile;
1196 /* Request a CPP_EOF token at the end of this file, rather than
1197 transparently continuing with the including file. */
1198 pfile->buffer->return_at_eof = true;
1200 if (CPP_OPTION (pfile, traditional))
1201 while (_cpp_read_logical_line_trad (pfile))
1203 else
1204 while (cpp_get_token (pfile)->type != CPP_EOF)
1208 /* Step back one (or more) tokens. Can only step mack more than 1 if
1209 they are from the lexer, and not from macro expansion. */
1210 void
1211 _cpp_backup_tokens (pfile, count)
1212 cpp_reader *pfile;
1213 unsigned int count;
1215 if (pfile->context->prev == NULL)
1217 pfile->lookaheads += count;
1218 while (count--)
1220 pfile->cur_token--;
1221 if (pfile->cur_token == pfile->cur_run->base
1222 /* Possible with -fpreprocessed and no leading #line. */
1223 && pfile->cur_run->prev != NULL)
1225 pfile->cur_run = pfile->cur_run->prev;
1226 pfile->cur_token = pfile->cur_run->limit;
1230 else
1232 if (count != 1)
1233 abort ();
1234 if (pfile->context->direct_p)
1235 FIRST (pfile->context).token--;
1236 else
1237 FIRST (pfile->context).ptoken--;
1241 /* #define directive parsing and handling. */
1243 /* Returns nonzero if a macro redefinition warning is required. */
1244 static bool
1245 warn_of_redefinition (pfile, node, macro2)
1246 cpp_reader *pfile;
1247 const cpp_hashnode *node;
1248 const cpp_macro *macro2;
1250 const cpp_macro *macro1;
1251 unsigned int i;
1253 /* Some redefinitions need to be warned about regardless. */
1254 if (node->flags & NODE_WARN)
1255 return true;
1257 /* Redefinition of a macro is allowed if and only if the old and new
1258 definitions are the same. (6.10.3 paragraph 2). */
1259 macro1 = node->value.macro;
1261 /* Don't check count here as it can be different in valid
1262 traditional redefinitions with just whitespace differences. */
1263 if (macro1->paramc != macro2->paramc
1264 || macro1->fun_like != macro2->fun_like
1265 || macro1->variadic != macro2->variadic)
1266 return true;
1268 /* Check parameter spellings. */
1269 for (i = 0; i < macro1->paramc; i++)
1270 if (macro1->params[i] != macro2->params[i])
1271 return true;
1273 /* Check the replacement text or tokens. */
1274 if (CPP_OPTION (pfile, traditional))
1275 return _cpp_expansions_different_trad (macro1, macro2);
1277 if (macro1->count == macro2->count)
1278 for (i = 0; i < macro1->count; i++)
1279 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
1280 return true;
1282 return false;
1285 /* Free the definition of hashnode H. */
1286 void
1287 _cpp_free_definition (h)
1288 cpp_hashnode *h;
1290 /* Macros and assertions no longer have anything to free. */
1291 h->type = NT_VOID;
1292 /* Clear builtin flag in case of redefinition. */
1293 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1296 /* Save parameter NODE to the parameter list of macro MACRO. Returns
1297 zero on success, nonzero if the parameter is a duplicate. */
1298 bool
1299 _cpp_save_parameter (pfile, macro, node)
1300 cpp_reader *pfile;
1301 cpp_macro *macro;
1302 cpp_hashnode *node;
1304 /* Constraint 6.10.3.6 - duplicate parameter names. */
1305 if (node->arg_index)
1307 cpp_error (pfile, DL_ERROR, "duplicate macro parameter \"%s\"",
1308 NODE_NAME (node));
1309 return true;
1312 if (BUFF_ROOM (pfile->a_buff)
1313 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1314 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1316 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1317 node->arg_index = macro->paramc;
1318 return false;
1321 /* Check the syntax of the parameters in a MACRO definition. Returns
1322 false if an error occurs. */
1323 static bool
1324 parse_params (pfile, macro)
1325 cpp_reader *pfile;
1326 cpp_macro *macro;
1328 unsigned int prev_ident = 0;
1330 for (;;)
1332 const cpp_token *token = _cpp_lex_token (pfile);
1334 switch (token->type)
1336 default:
1337 /* Allow/ignore comments in parameter lists if we are
1338 preserving comments in macro expansions. */
1339 if (token->type == CPP_COMMENT
1340 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
1341 continue;
1343 cpp_error (pfile, DL_ERROR,
1344 "\"%s\" may not appear in macro parameter list",
1345 cpp_token_as_text (pfile, token));
1346 return false;
1348 case CPP_NAME:
1349 if (prev_ident)
1351 cpp_error (pfile, DL_ERROR,
1352 "macro parameters must be comma-separated");
1353 return false;
1355 prev_ident = 1;
1357 if (_cpp_save_parameter (pfile, macro, token->val.node))
1358 return false;
1359 continue;
1361 case CPP_CLOSE_PAREN:
1362 if (prev_ident || macro->paramc == 0)
1363 return true;
1365 /* Fall through to pick up the error. */
1366 case CPP_COMMA:
1367 if (!prev_ident)
1369 cpp_error (pfile, DL_ERROR, "parameter name missing");
1370 return false;
1372 prev_ident = 0;
1373 continue;
1375 case CPP_ELLIPSIS:
1376 macro->variadic = 1;
1377 if (!prev_ident)
1379 _cpp_save_parameter (pfile, macro,
1380 pfile->spec_nodes.n__VA_ARGS__);
1381 pfile->state.va_args_ok = 1;
1382 if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1383 cpp_error (pfile, DL_PEDWARN,
1384 "anonymous variadic macros were introduced in C99");
1386 else if (CPP_OPTION (pfile, pedantic))
1387 cpp_error (pfile, DL_PEDWARN,
1388 "ISO C does not permit named variadic macros");
1390 /* We're at the end, and just expect a closing parenthesis. */
1391 token = _cpp_lex_token (pfile);
1392 if (token->type == CPP_CLOSE_PAREN)
1393 return true;
1394 /* Fall through. */
1396 case CPP_EOF:
1397 cpp_error (pfile, DL_ERROR, "missing ')' in macro parameter list");
1398 return false;
1403 /* Allocate room for a token from a macro's replacement list. */
1404 static cpp_token *
1405 alloc_expansion_token (pfile, macro)
1406 cpp_reader *pfile;
1407 cpp_macro *macro;
1409 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1410 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1412 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1415 /* Lex a token from the expansion of MACRO, but mark parameters as we
1416 find them and warn of traditional stringification. */
1417 static cpp_token *
1418 lex_expansion_token (pfile, macro)
1419 cpp_reader *pfile;
1420 cpp_macro *macro;
1422 cpp_token *token;
1424 pfile->cur_token = alloc_expansion_token (pfile, macro);
1425 token = _cpp_lex_direct (pfile);
1427 /* Is this a parameter? */
1428 if (token->type == CPP_NAME && token->val.node->arg_index)
1430 token->type = CPP_MACRO_ARG;
1431 token->val.arg_no = token->val.node->arg_index;
1433 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1434 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1435 check_trad_stringification (pfile, macro, &token->val.str);
1437 return token;
1440 static bool
1441 create_iso_definition (pfile, macro)
1442 cpp_reader *pfile;
1443 cpp_macro *macro;
1445 cpp_token *token;
1446 const cpp_token *ctoken;
1448 /* Get the first token of the expansion (or the '(' of a
1449 function-like macro). */
1450 ctoken = _cpp_lex_token (pfile);
1452 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1454 bool ok = parse_params (pfile, macro);
1455 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1456 if (!ok)
1457 return false;
1459 /* Success. Commit the parameter array. */
1460 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1461 macro->fun_like = 1;
1463 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1464 cpp_error (pfile, DL_PEDWARN,
1465 "ISO C requires whitespace after the macro name");
1467 if (macro->fun_like)
1468 token = lex_expansion_token (pfile, macro);
1469 else
1471 token = alloc_expansion_token (pfile, macro);
1472 *token = *ctoken;
1475 for (;;)
1477 /* Check the stringifying # constraint 6.10.3.2.1 of
1478 function-like macros when lexing the subsequent token. */
1479 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1481 if (token->type == CPP_MACRO_ARG)
1483 token->flags &= ~PREV_WHITE;
1484 token->flags |= STRINGIFY_ARG;
1485 token->flags |= token[-1].flags & PREV_WHITE;
1486 token[-1] = token[0];
1487 macro->count--;
1489 /* Let assembler get away with murder. */
1490 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1492 cpp_error (pfile, DL_ERROR,
1493 "'#' is not followed by a macro parameter");
1494 return false;
1498 if (token->type == CPP_EOF)
1499 break;
1501 /* Paste operator constraint 6.10.3.3.1. */
1502 if (token->type == CPP_PASTE)
1504 /* Token-paste ##, can appear in both object-like and
1505 function-like macros, but not at the ends. */
1506 if (--macro->count > 0)
1507 token = lex_expansion_token (pfile, macro);
1509 if (macro->count == 0 || token->type == CPP_EOF)
1511 cpp_error (pfile, DL_ERROR,
1512 "'##' cannot appear at either end of a macro expansion");
1513 return false;
1516 token[-1].flags |= PASTE_LEFT;
1519 token = lex_expansion_token (pfile, macro);
1522 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1524 /* Don't count the CPP_EOF. */
1525 macro->count--;
1527 /* Clear whitespace on first token for warn_of_redefinition(). */
1528 if (macro->count)
1529 macro->exp.tokens[0].flags &= ~PREV_WHITE;
1531 /* Commit the memory. */
1532 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
1534 return true;
1537 /* Parse a macro and save its expansion. Returns nonzero on success. */
1538 bool
1539 _cpp_create_definition (pfile, node)
1540 cpp_reader *pfile;
1541 cpp_hashnode *node;
1543 cpp_macro *macro;
1544 unsigned int i;
1545 bool ok;
1547 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1548 macro->line = pfile->directive_line;
1549 macro->params = 0;
1550 macro->paramc = 0;
1551 macro->variadic = 0;
1552 macro->used = 0;
1553 macro->count = 0;
1554 macro->fun_like = 0;
1555 /* To suppress some diagnostics. */
1556 macro->syshdr = pfile->map->sysp != 0;
1558 if (CPP_OPTION (pfile, traditional))
1559 ok = _cpp_create_trad_definition (pfile, macro);
1560 else
1562 cpp_token *saved_cur_token = pfile->cur_token;
1564 ok = create_iso_definition (pfile, macro);
1566 /* Restore lexer position because of games lex_expansion_token()
1567 plays lexing the macro. We set the type for SEEN_EOL() in
1568 cpplib.c.
1570 Longer term we should lex the whole line before coming here,
1571 and just copy the expansion. */
1572 saved_cur_token[-1].type = pfile->cur_token[-1].type;
1573 pfile->cur_token = saved_cur_token;
1575 /* Stop the lexer accepting __VA_ARGS__. */
1576 pfile->state.va_args_ok = 0;
1579 /* Clear the fast argument lookup indices. */
1580 for (i = macro->paramc; i-- > 0; )
1581 macro->params[i]->arg_index = 0;
1583 if (!ok)
1584 return ok;
1586 if (node->type == NT_MACRO)
1588 if (CPP_OPTION (pfile, warn_unused_macros))
1589 _cpp_warn_if_unused_macro (pfile, node, NULL);
1591 if (warn_of_redefinition (pfile, node, macro))
1593 cpp_error_with_line (pfile, DL_PEDWARN, pfile->directive_line, 0,
1594 "\"%s\" redefined", NODE_NAME (node));
1596 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1597 cpp_error_with_line (pfile, DL_PEDWARN,
1598 node->value.macro->line, 0,
1599 "this is the location of the previous definition");
1603 if (node->type != NT_VOID)
1604 _cpp_free_definition (node);
1606 /* Enter definition in hash table. */
1607 node->type = NT_MACRO;
1608 node->value.macro = macro;
1609 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1610 node->flags |= NODE_WARN;
1612 return ok;
1615 /* Warn if a token in STRING matches one of a function-like MACRO's
1616 parameters. */
1617 static void
1618 check_trad_stringification (pfile, macro, string)
1619 cpp_reader *pfile;
1620 const cpp_macro *macro;
1621 const cpp_string *string;
1623 unsigned int i, len;
1624 const uchar *p, *q, *limit = string->text + string->len;
1626 /* Loop over the string. */
1627 for (p = string->text; p < limit; p = q)
1629 /* Find the start of an identifier. */
1630 while (p < limit && !is_idstart (*p))
1631 p++;
1633 /* Find the end of the identifier. */
1634 q = p;
1635 while (q < limit && is_idchar (*q))
1636 q++;
1638 len = q - p;
1640 /* Loop over the function macro arguments to see if the
1641 identifier inside the string matches one of them. */
1642 for (i = 0; i < macro->paramc; i++)
1644 const cpp_hashnode *node = macro->params[i];
1646 if (NODE_LEN (node) == len
1647 && !memcmp (p, NODE_NAME (node), len))
1649 cpp_error (pfile, DL_WARNING,
1650 "macro argument \"%s\" would be stringified in traditional C",
1651 NODE_NAME (node));
1652 break;
1658 /* Returns the name, arguments and expansion of a macro, in a format
1659 suitable to be read back in again, and therefore also for DWARF 2
1660 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1661 Caller is expected to generate the "#define" bit if needed. The
1662 returned text is temporary, and automatically freed later. */
1663 const unsigned char *
1664 cpp_macro_definition (pfile, node)
1665 cpp_reader *pfile;
1666 const cpp_hashnode *node;
1668 unsigned int i, len;
1669 const cpp_macro *macro = node->value.macro;
1670 unsigned char *buffer;
1672 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1674 cpp_error (pfile, DL_ICE,
1675 "invalid hash type %d in cpp_macro_definition", node->type);
1676 return 0;
1679 /* Calculate length. */
1680 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
1681 if (macro->fun_like)
1683 len += 4; /* "()" plus possible final ".." of named
1684 varargs (we have + 1 below). */
1685 for (i = 0; i < macro->paramc; i++)
1686 len += NODE_LEN (macro->params[i]) + 1; /* "," */
1689 if (CPP_OPTION (pfile, traditional))
1690 len += _cpp_replacement_text_len (macro);
1691 else
1693 for (i = 0; i < macro->count; i++)
1695 cpp_token *token = &macro->exp.tokens[i];
1697 if (token->type == CPP_MACRO_ARG)
1698 len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1699 else
1700 len += cpp_token_len (token); /* Includes room for ' '. */
1701 if (token->flags & STRINGIFY_ARG)
1702 len++; /* "#" */
1703 if (token->flags & PASTE_LEFT)
1704 len += 3; /* " ##" */
1708 if (len > pfile->macro_buffer_len)
1710 pfile->macro_buffer = (uchar *) xrealloc (pfile->macro_buffer, len);
1711 pfile->macro_buffer_len = len;
1714 /* Fill in the buffer. Start with the macro name. */
1715 buffer = pfile->macro_buffer;
1716 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1717 buffer += NODE_LEN (node);
1719 /* Parameter names. */
1720 if (macro->fun_like)
1722 *buffer++ = '(';
1723 for (i = 0; i < macro->paramc; i++)
1725 cpp_hashnode *param = macro->params[i];
1727 if (param != pfile->spec_nodes.n__VA_ARGS__)
1729 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1730 buffer += NODE_LEN (param);
1733 if (i + 1 < macro->paramc)
1734 /* Don't emit a space after the comma here; we're trying
1735 to emit a Dwarf-friendly definition, and the Dwarf spec
1736 forbids spaces in the argument list. */
1737 *buffer++ = ',';
1738 else if (macro->variadic)
1739 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1741 *buffer++ = ')';
1744 /* The Dwarf spec requires a space after the macro name, even if the
1745 definition is the empty string. */
1746 *buffer++ = ' ';
1748 if (CPP_OPTION (pfile, traditional))
1749 buffer = _cpp_copy_replacement_text (macro, buffer);
1750 else if (macro->count)
1751 /* Expansion tokens. */
1753 for (i = 0; i < macro->count; i++)
1755 cpp_token *token = &macro->exp.tokens[i];
1757 if (token->flags & PREV_WHITE)
1758 *buffer++ = ' ';
1759 if (token->flags & STRINGIFY_ARG)
1760 *buffer++ = '#';
1762 if (token->type == CPP_MACRO_ARG)
1764 len = NODE_LEN (macro->params[token->val.arg_no - 1]);
1765 memcpy (buffer,
1766 NODE_NAME (macro->params[token->val.arg_no - 1]), len);
1767 buffer += len;
1769 else
1770 buffer = cpp_spell_token (pfile, token, buffer);
1772 if (token->flags & PASTE_LEFT)
1774 *buffer++ = ' ';
1775 *buffer++ = '#';
1776 *buffer++ = '#';
1777 /* Next has PREV_WHITE; see _cpp_create_definition. */
1782 *buffer = '\0';
1783 return pfile->macro_buffer;