gfortran.h (gfc_expr): Remove from_H, add "representation" struct.
[official-gcc.git] / libcpp / macro.c
blobc8d099ed210f6eadc630bc671de7867540d1df33
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, 2003, 2004, 2005,
4 2006 Free Software Foundation, Inc.
5 Written by Per Bothner, 1994.
6 Based on CCCP program by Paul Rubin, June 1986
7 Adapted to ANSI C, Richard Stallman, Jan 1987
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 In other words, you are welcome to use, share and improve this program.
24 You are forbidden to forbid anyone else to use, share and improve
25 what you give them. Help stamp out software-hoarding! */
27 #include "config.h"
28 #include "system.h"
29 #include "cpplib.h"
30 #include "internal.h"
32 typedef struct macro_arg macro_arg;
33 struct macro_arg
35 const cpp_token **first; /* First token in unexpanded argument. */
36 const cpp_token **expanded; /* Macro-expanded argument. */
37 const cpp_token *stringified; /* Stringified argument. */
38 unsigned int count; /* # of tokens in argument. */
39 unsigned int expanded_count; /* # of tokens in expanded argument. */
42 /* Macro expansion. */
44 static int enter_macro_context (cpp_reader *, cpp_hashnode *);
45 static int builtin_macro (cpp_reader *, cpp_hashnode *);
46 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
47 const cpp_token **, unsigned int);
48 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *);
49 static cpp_context *next_context (cpp_reader *);
50 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
51 static void expand_arg (cpp_reader *, macro_arg *);
52 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
53 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
54 static void paste_all_tokens (cpp_reader *, const cpp_token *);
55 static bool paste_tokens (cpp_reader *, const cpp_token **, const cpp_token *);
56 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
57 macro_arg *);
58 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *);
59 static bool create_iso_definition (cpp_reader *, cpp_macro *);
61 /* #define directive parsing and handling. */
63 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
64 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
65 static bool warn_of_redefinition (cpp_reader *, const cpp_hashnode *,
66 const cpp_macro *);
67 static bool parse_params (cpp_reader *, cpp_macro *);
68 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
69 const cpp_string *);
71 /* Emits a warning if NODE is a macro defined in the main file that
72 has not been used. */
73 int
74 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
75 void *v ATTRIBUTE_UNUSED)
77 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
79 cpp_macro *macro = node->value.macro;
81 if (!macro->used
82 && MAIN_FILE_P (linemap_lookup (pfile->line_table, macro->line)))
83 cpp_error_with_line (pfile, CPP_DL_WARNING, macro->line, 0,
84 "macro \"%s\" is not used", NODE_NAME (node));
87 return 1;
90 /* Allocates and returns a CPP_STRING token, containing TEXT of length
91 LEN, after null-terminating it. TEXT must be in permanent storage. */
92 static const cpp_token *
93 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
95 cpp_token *token = _cpp_temp_token (pfile);
97 text[len] = '\0';
98 token->type = CPP_STRING;
99 token->val.str.len = len;
100 token->val.str.text = text;
101 token->flags = 0;
102 return token;
105 static const char * const monthnames[] =
107 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
108 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
111 /* Helper function for builtin_macro. Returns the text generated by
112 a builtin macro. */
113 const uchar *
114 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
116 const struct line_map *map;
117 const uchar *result = NULL;
118 unsigned int number = 1;
120 switch (node->value.builtin)
122 default:
123 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
124 NODE_NAME (node));
125 break;
127 case BT_TIMESTAMP:
129 cpp_buffer *pbuffer = cpp_get_buffer (pfile);
130 if (pbuffer->timestamp == NULL)
132 /* Initialize timestamp value of the assotiated file. */
133 struct _cpp_file *file = cpp_get_file (pbuffer);
134 if (file)
136 /* Generate __TIMESTAMP__ string, that represents
137 the date and time of the last modification
138 of the current source file. The string constant
139 looks like "Sun Sep 16 01:03:52 1973". */
140 struct tm *tb = NULL;
141 struct stat *st = _cpp_get_file_stat (file);
142 if (st)
143 tb = localtime (&st->st_mtime);
144 if (tb)
146 char *str = asctime (tb);
147 size_t len = strlen (str);
148 unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
149 buf[0] = '"';
150 strcpy ((char *) buf + 1, str);
151 buf[len] = '"';
152 pbuffer->timestamp = buf;
154 else
156 cpp_errno (pfile, CPP_DL_WARNING,
157 "could not determine file timestamp");
158 pbuffer->timestamp = U"\"??? ??? ?? ??:??:?? ????\"";
162 result = pbuffer->timestamp;
164 break;
165 case BT_FILE:
166 case BT_BASE_FILE:
168 unsigned int len;
169 const char *name;
170 uchar *buf;
171 map = linemap_lookup (pfile->line_table, pfile->line_table->highest_line);
173 if (node->value.builtin == BT_BASE_FILE)
174 while (! MAIN_FILE_P (map))
175 map = INCLUDED_FROM (pfile->line_table, map);
177 name = map->to_file;
178 len = strlen (name);
179 buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
180 result = buf;
181 *buf = '"';
182 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
183 *buf++ = '"';
184 *buf = '\0';
186 break;
188 case BT_INCLUDE_LEVEL:
189 /* The line map depth counts the primary source as level 1, but
190 historically __INCLUDE_DEPTH__ has called the primary source
191 level 0. */
192 number = pfile->line_table->depth - 1;
193 break;
195 case BT_SPECLINE:
196 map = &pfile->line_table->maps[pfile->line_table->used-1];
197 /* If __LINE__ is embedded in a macro, it must expand to the
198 line of the macro's invocation, not its definition.
199 Otherwise things like assert() will not work properly. */
200 if (CPP_OPTION (pfile, traditional))
201 number = pfile->line_table->highest_line;
202 else
203 number = pfile->cur_token[-1].src_loc;
204 number = SOURCE_LINE (map, number);
205 break;
207 /* __STDC__ has the value 1 under normal circumstances.
208 However, if (a) we are in a system header, (b) the option
209 stdc_0_in_system_headers is true (set by target config), and
210 (c) we are not in strictly conforming mode, then it has the
211 value 0. (b) and (c) are already checked in cpp_init_builtins. */
212 case BT_STDC:
213 if (cpp_in_system_header (pfile))
214 number = 0;
215 else
216 number = 1;
217 break;
219 case BT_DATE:
220 case BT_TIME:
221 if (pfile->date == NULL)
223 /* Allocate __DATE__ and __TIME__ strings from permanent
224 storage. We only do this once, and don't generate them
225 at init time, because time() and localtime() are very
226 slow on some systems. */
227 time_t tt;
228 struct tm *tb = NULL;
230 /* (time_t) -1 is a legitimate value for "number of seconds
231 since the Epoch", so we have to do a little dance to
232 distinguish that from a genuine error. */
233 errno = 0;
234 tt = time(NULL);
235 if (tt != (time_t)-1 || errno == 0)
236 tb = localtime (&tt);
238 if (tb)
240 pfile->date = _cpp_unaligned_alloc (pfile,
241 sizeof ("\"Oct 11 1347\""));
242 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
243 monthnames[tb->tm_mon], tb->tm_mday,
244 tb->tm_year + 1900);
246 pfile->time = _cpp_unaligned_alloc (pfile,
247 sizeof ("\"12:34:56\""));
248 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
249 tb->tm_hour, tb->tm_min, tb->tm_sec);
251 else
253 cpp_errno (pfile, CPP_DL_WARNING,
254 "could not determine date and time");
256 pfile->date = U"\"??? ?? ????\"";
257 pfile->time = U"\"??:??:??\"";
261 if (node->value.builtin == BT_DATE)
262 result = pfile->date;
263 else
264 result = pfile->time;
265 break;
267 case BT_COUNTER:
268 number = pfile->counter++;
269 break;
272 if (result == NULL)
274 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
275 result = _cpp_unaligned_alloc (pfile, 21);
276 sprintf ((char *) result, "%u", number);
279 return result;
282 /* Convert builtin macros like __FILE__ to a token and push it on the
283 context stack. Also handles _Pragma, for which a new token may not
284 be created. Returns 1 if it generates a new token context, 0 to
285 return the token to the caller. */
286 static int
287 builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
289 const uchar *buf;
290 size_t len;
291 char *nbuf;
293 if (node->value.builtin == BT_PRAGMA)
295 /* Don't interpret _Pragma within directives. The standard is
296 not clear on this, but to me this makes most sense. */
297 if (pfile->state.in_directive)
298 return 0;
300 _cpp_do__Pragma (pfile);
301 return 1;
304 buf = _cpp_builtin_macro_text (pfile, node);
305 len = ustrlen (buf);
306 nbuf = (char *) alloca (len + 1);
307 memcpy (nbuf, buf, len);
308 nbuf[len]='\n';
310 cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
311 _cpp_clean_line (pfile);
313 /* Set pfile->cur_token as required by _cpp_lex_direct. */
314 pfile->cur_token = _cpp_temp_token (pfile);
315 _cpp_push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
316 if (pfile->buffer->cur != pfile->buffer->rlimit)
317 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
318 NODE_NAME (node));
319 _cpp_pop_buffer (pfile);
321 return 1;
324 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
325 backslashes and double quotes. DEST must be of sufficient size.
326 Returns a pointer to the end of the string. */
327 uchar *
328 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
330 while (len--)
332 uchar c = *src++;
334 if (c == '\\' || c == '"')
336 *dest++ = '\\';
337 *dest++ = c;
339 else
340 *dest++ = c;
343 return dest;
346 /* Convert a token sequence ARG to a single string token according to
347 the rules of the ISO C #-operator. */
348 static const cpp_token *
349 stringify_arg (cpp_reader *pfile, macro_arg *arg)
351 unsigned char *dest;
352 unsigned int i, escape_it, backslash_count = 0;
353 const cpp_token *source = NULL;
354 size_t len;
356 if (BUFF_ROOM (pfile->u_buff) < 3)
357 _cpp_extend_buff (pfile, &pfile->u_buff, 3);
358 dest = BUFF_FRONT (pfile->u_buff);
359 *dest++ = '"';
361 /* Loop, reading in the argument's tokens. */
362 for (i = 0; i < arg->count; i++)
364 const cpp_token *token = arg->first[i];
366 if (token->type == CPP_PADDING)
368 if (source == NULL)
369 source = token->val.source;
370 continue;
373 escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
374 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
376 /* Room for each char being written in octal, initial space and
377 final quote and NUL. */
378 len = cpp_token_len (token);
379 if (escape_it)
380 len *= 4;
381 len += 3;
383 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
385 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
386 _cpp_extend_buff (pfile, &pfile->u_buff, len);
387 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
390 /* Leading white space? */
391 if (dest - 1 != BUFF_FRONT (pfile->u_buff))
393 if (source == NULL)
394 source = token;
395 if (source->flags & PREV_WHITE)
396 *dest++ = ' ';
398 source = NULL;
400 if (escape_it)
402 _cpp_buff *buff = _cpp_get_buff (pfile, len);
403 unsigned char *buf = BUFF_FRONT (buff);
404 len = cpp_spell_token (pfile, token, buf, true) - buf;
405 dest = cpp_quote_string (dest, buf, len);
406 _cpp_release_buff (pfile, buff);
408 else
409 dest = cpp_spell_token (pfile, token, dest, true);
411 if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
412 backslash_count++;
413 else
414 backslash_count = 0;
417 /* Ignore the final \ of invalid string literals. */
418 if (backslash_count & 1)
420 cpp_error (pfile, CPP_DL_WARNING,
421 "invalid string literal, ignoring final '\\'");
422 dest--;
425 /* Commit the memory, including NUL, and return the token. */
426 *dest++ = '"';
427 len = dest - BUFF_FRONT (pfile->u_buff);
428 BUFF_FRONT (pfile->u_buff) = dest + 1;
429 return new_string_token (pfile, dest - len, len);
432 /* Try to paste two tokens. On success, return nonzero. In any
433 case, PLHS is updated to point to the pasted token, which is
434 guaranteed to not have the PASTE_LEFT flag set. */
435 static bool
436 paste_tokens (cpp_reader *pfile, const cpp_token **plhs, const cpp_token *rhs)
438 unsigned char *buf, *end, *lhsend;
439 cpp_token *lhs;
440 unsigned int len;
442 len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
443 buf = (unsigned char *) alloca (len);
444 end = lhsend = cpp_spell_token (pfile, *plhs, buf, false);
446 /* Avoid comment headers, since they are still processed in stage 3.
447 It is simpler to insert a space here, rather than modifying the
448 lexer to ignore comments in some circumstances. Simply returning
449 false doesn't work, since we want to clear the PASTE_LEFT flag. */
450 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
451 *end++ = ' ';
452 end = cpp_spell_token (pfile, rhs, end, false);
453 *end = '\n';
455 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
456 _cpp_clean_line (pfile);
458 /* Set pfile->cur_token as required by _cpp_lex_direct. */
459 pfile->cur_token = _cpp_temp_token (pfile);
460 lhs = _cpp_lex_direct (pfile);
461 if (pfile->buffer->cur != pfile->buffer->rlimit)
463 source_location saved_loc = lhs->src_loc;
465 _cpp_pop_buffer (pfile);
466 _cpp_backup_tokens (pfile, 1);
467 *lhsend = '\0';
469 /* We have to remove the PASTE_LEFT flag from the old lhs, but
470 we want to keep the new location. */
471 *lhs = **plhs;
472 *plhs = lhs;
473 lhs->src_loc = saved_loc;
474 lhs->flags &= ~PASTE_LEFT;
476 /* Mandatory error for all apart from assembler. */
477 if (CPP_OPTION (pfile, lang) != CLK_ASM)
478 cpp_error (pfile, CPP_DL_ERROR,
479 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
480 buf, cpp_token_as_text (pfile, rhs));
481 return false;
484 *plhs = lhs;
485 _cpp_pop_buffer (pfile);
486 return true;
489 /* Handles an arbitrarily long sequence of ## operators, with initial
490 operand LHS. This implementation is left-associative,
491 non-recursive, and finishes a paste before handling succeeding
492 ones. If a paste fails, we back up to the RHS of the failing ##
493 operator before pushing the context containing the result of prior
494 successful pastes, with the effect that the RHS appears in the
495 output stream after the pasted LHS normally. */
496 static void
497 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
499 const cpp_token *rhs;
500 cpp_context *context = pfile->context;
504 /* Take the token directly from the current context. We can do
505 this, because we are in the replacement list of either an
506 object-like macro, or a function-like macro with arguments
507 inserted. In either case, the constraints to #define
508 guarantee we have at least one more token. */
509 if (context->direct_p)
510 rhs = FIRST (context).token++;
511 else
512 rhs = *FIRST (context).ptoken++;
514 if (rhs->type == CPP_PADDING)
515 abort ();
517 if (!paste_tokens (pfile, &lhs, rhs))
518 break;
520 while (rhs->flags & PASTE_LEFT);
522 /* Put the resulting token in its own context. */
523 _cpp_push_token_context (pfile, NULL, lhs, 1);
526 /* Returns TRUE if the number of arguments ARGC supplied in an
527 invocation of the MACRO referenced by NODE is valid. An empty
528 invocation to a macro with no parameters should pass ARGC as zero.
530 Note that MACRO cannot necessarily be deduced from NODE, in case
531 NODE was redefined whilst collecting arguments. */
532 bool
533 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
535 if (argc == macro->paramc)
536 return true;
538 if (argc < macro->paramc)
540 /* As an extension, a rest argument is allowed to not appear in
541 the invocation at all.
542 e.g. #define debug(format, args...) something
543 debug("string");
545 This is exactly the same as if there had been an empty rest
546 argument - debug("string", ). */
548 if (argc + 1 == macro->paramc && macro->variadic)
550 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
551 cpp_error (pfile, CPP_DL_PEDWARN,
552 "ISO C99 requires rest arguments to be used");
553 return true;
556 cpp_error (pfile, CPP_DL_ERROR,
557 "macro \"%s\" requires %u arguments, but only %u given",
558 NODE_NAME (node), macro->paramc, argc);
560 else
561 cpp_error (pfile, CPP_DL_ERROR,
562 "macro \"%s\" passed %u arguments, but takes just %u",
563 NODE_NAME (node), argc, macro->paramc);
565 return false;
568 /* Reads and returns the arguments to a function-like macro
569 invocation. Assumes the opening parenthesis has been processed.
570 If there is an error, emits an appropriate diagnostic and returns
571 NULL. Each argument is terminated by a CPP_EOF token, for the
572 future benefit of expand_arg(). */
573 static _cpp_buff *
574 collect_args (cpp_reader *pfile, const cpp_hashnode *node)
576 _cpp_buff *buff, *base_buff;
577 cpp_macro *macro;
578 macro_arg *args, *arg;
579 const cpp_token *token;
580 unsigned int argc;
582 macro = node->value.macro;
583 if (macro->paramc)
584 argc = macro->paramc;
585 else
586 argc = 1;
587 buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
588 + sizeof (macro_arg)));
589 base_buff = buff;
590 args = (macro_arg *) buff->base;
591 memset (args, 0, argc * sizeof (macro_arg));
592 buff->cur = (unsigned char *) &args[argc];
593 arg = args, argc = 0;
595 /* Collect the tokens making up each argument. We don't yet know
596 how many arguments have been supplied, whether too many or too
597 few. Hence the slightly bizarre usage of "argc" and "arg". */
600 unsigned int paren_depth = 0;
601 unsigned int ntokens = 0;
603 argc++;
604 arg->first = (const cpp_token **) buff->cur;
606 for (;;)
608 /* Require space for 2 new tokens (including a CPP_EOF). */
609 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
611 buff = _cpp_append_extend_buff (pfile, buff,
612 1000 * sizeof (cpp_token *));
613 arg->first = (const cpp_token **) buff->cur;
616 token = cpp_get_token (pfile);
618 if (token->type == CPP_PADDING)
620 /* Drop leading padding. */
621 if (ntokens == 0)
622 continue;
624 else if (token->type == CPP_OPEN_PAREN)
625 paren_depth++;
626 else if (token->type == CPP_CLOSE_PAREN)
628 if (paren_depth-- == 0)
629 break;
631 else if (token->type == CPP_COMMA)
633 /* A comma does not terminate an argument within
634 parentheses or as part of a variable argument. */
635 if (paren_depth == 0
636 && ! (macro->variadic && argc == macro->paramc))
637 break;
639 else if (token->type == CPP_EOF
640 || (token->type == CPP_HASH && token->flags & BOL))
641 break;
643 arg->first[ntokens++] = token;
646 /* Drop trailing padding. */
647 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
648 ntokens--;
650 arg->count = ntokens;
651 arg->first[ntokens] = &pfile->eof;
653 /* Terminate the argument. Excess arguments loop back and
654 overwrite the final legitimate argument, before failing. */
655 if (argc <= macro->paramc)
657 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
658 if (argc != macro->paramc)
659 arg++;
662 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
664 if (token->type == CPP_EOF)
666 /* We still need the CPP_EOF to end directives, and to end
667 pre-expansion of a macro argument. Step back is not
668 unconditional, since we don't want to return a CPP_EOF to our
669 callers at the end of an -include-d file. */
670 if (pfile->context->prev || pfile->state.in_directive)
671 _cpp_backup_tokens (pfile, 1);
672 cpp_error (pfile, CPP_DL_ERROR,
673 "unterminated argument list invoking macro \"%s\"",
674 NODE_NAME (node));
676 else
678 /* A single empty argument is counted as no argument. */
679 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
680 argc = 0;
681 if (_cpp_arguments_ok (pfile, macro, node, argc))
683 /* GCC has special semantics for , ## b where b is a varargs
684 parameter: we remove the comma if b was omitted entirely.
685 If b was merely an empty argument, the comma is retained.
686 If the macro takes just one (varargs) parameter, then we
687 retain the comma only if we are standards conforming.
689 If FIRST is NULL replace_args () swallows the comma. */
690 if (macro->variadic && (argc < macro->paramc
691 || (argc == 1 && args[0].count == 0
692 && !CPP_OPTION (pfile, std))))
693 args[macro->paramc - 1].first = NULL;
694 return base_buff;
698 /* An error occurred. */
699 _cpp_release_buff (pfile, base_buff);
700 return NULL;
703 /* Search for an opening parenthesis to the macro of NODE, in such a
704 way that, if none is found, we don't lose the information in any
705 intervening padding tokens. If we find the parenthesis, collect
706 the arguments and return the buffer containing them. */
707 static _cpp_buff *
708 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node)
710 const cpp_token *token, *padding = NULL;
712 for (;;)
714 token = cpp_get_token (pfile);
715 if (token->type != CPP_PADDING)
716 break;
717 if (padding == NULL
718 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
719 padding = token;
722 if (token->type == CPP_OPEN_PAREN)
724 pfile->state.parsing_args = 2;
725 return collect_args (pfile, node);
728 /* CPP_EOF can be the end of macro arguments, or the end of the
729 file. We mustn't back up over the latter. Ugh. */
730 if (token->type != CPP_EOF || token == &pfile->eof)
732 /* Back up. We may have skipped padding, in which case backing
733 up more than one token when expanding macros is in general
734 too difficult. We re-insert it in its own context. */
735 _cpp_backup_tokens (pfile, 1);
736 if (padding)
737 _cpp_push_token_context (pfile, NULL, padding, 1);
740 return NULL;
743 /* Push the context of a macro with hash entry NODE onto the context
744 stack. If we can successfully expand the macro, we push a context
745 containing its yet-to-be-rescanned replacement list and return one.
746 Otherwise, we don't push a context and return zero. */
747 static int
748 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node)
750 /* The presence of a macro invalidates a file's controlling macro. */
751 pfile->mi_valid = false;
753 pfile->state.angled_headers = false;
755 /* Handle standard macros. */
756 if (! (node->flags & NODE_BUILTIN))
758 cpp_macro *macro = node->value.macro;
760 if (macro->fun_like)
762 _cpp_buff *buff;
764 pfile->state.prevent_expansion++;
765 pfile->keep_tokens++;
766 pfile->state.parsing_args = 1;
767 buff = funlike_invocation_p (pfile, node);
768 pfile->state.parsing_args = 0;
769 pfile->keep_tokens--;
770 pfile->state.prevent_expansion--;
772 if (buff == NULL)
774 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
775 cpp_error (pfile, CPP_DL_WARNING,
776 "function-like macro \"%s\" must be used with arguments in traditional C",
777 NODE_NAME (node));
779 return 0;
782 if (macro->paramc > 0)
783 replace_args (pfile, node, macro, (macro_arg *) buff->base);
784 _cpp_release_buff (pfile, buff);
787 /* Disable the macro within its expansion. */
788 node->flags |= NODE_DISABLED;
790 macro->used = 1;
792 if (macro->paramc == 0)
793 _cpp_push_token_context (pfile, node, macro->exp.tokens, macro->count);
795 return 1;
798 /* Handle built-in macros and the _Pragma operator. */
799 return builtin_macro (pfile, node);
802 /* Replace the parameters in a function-like macro of NODE with the
803 actual ARGS, and place the result in a newly pushed token context.
804 Expand each argument before replacing, unless it is operated upon
805 by the # or ## operators. */
806 static void
807 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro, macro_arg *args)
809 unsigned int i, total;
810 const cpp_token *src, *limit;
811 const cpp_token **dest, **first;
812 macro_arg *arg;
813 _cpp_buff *buff;
815 /* First, fully macro-expand arguments, calculating the number of
816 tokens in the final expansion as we go. The ordering of the if
817 statements below is subtle; we must handle stringification before
818 pasting. */
819 total = macro->count;
820 limit = macro->exp.tokens + macro->count;
822 for (src = macro->exp.tokens; src < limit; src++)
823 if (src->type == CPP_MACRO_ARG)
825 /* Leading and trailing padding tokens. */
826 total += 2;
828 /* We have an argument. If it is not being stringified or
829 pasted it is macro-replaced before insertion. */
830 arg = &args[src->val.arg_no - 1];
832 if (src->flags & STRINGIFY_ARG)
834 if (!arg->stringified)
835 arg->stringified = stringify_arg (pfile, arg);
837 else if ((src->flags & PASTE_LEFT)
838 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
839 total += arg->count - 1;
840 else
842 if (!arg->expanded)
843 expand_arg (pfile, arg);
844 total += arg->expanded_count - 1;
848 /* Now allocate space for the expansion, copy the tokens and replace
849 the arguments. */
850 buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
851 first = (const cpp_token **) buff->base;
852 dest = first;
854 for (src = macro->exp.tokens; src < limit; src++)
856 unsigned int count;
857 const cpp_token **from, **paste_flag;
859 if (src->type != CPP_MACRO_ARG)
861 *dest++ = src;
862 continue;
865 paste_flag = 0;
866 arg = &args[src->val.arg_no - 1];
867 if (src->flags & STRINGIFY_ARG)
868 count = 1, from = &arg->stringified;
869 else if (src->flags & PASTE_LEFT)
870 count = arg->count, from = arg->first;
871 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
873 count = arg->count, from = arg->first;
874 if (dest != first)
876 if (dest[-1]->type == CPP_COMMA
877 && macro->variadic
878 && src->val.arg_no == macro->paramc)
880 /* Swallow a pasted comma if from == NULL, otherwise
881 drop the paste flag. */
882 if (from == NULL)
883 dest--;
884 else
885 paste_flag = dest - 1;
887 /* Remove the paste flag if the RHS is a placemarker. */
888 else if (count == 0)
889 paste_flag = dest - 1;
892 else
893 count = arg->expanded_count, from = arg->expanded;
895 /* Padding on the left of an argument (unless RHS of ##). */
896 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
897 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
898 *dest++ = padding_token (pfile, src);
900 if (count)
902 memcpy (dest, from, count * sizeof (cpp_token *));
903 dest += count;
905 /* With a non-empty argument on the LHS of ##, the last
906 token should be flagged PASTE_LEFT. */
907 if (src->flags & PASTE_LEFT)
908 paste_flag = dest - 1;
911 /* Avoid paste on RHS (even case count == 0). */
912 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
913 *dest++ = &pfile->avoid_paste;
915 /* Add a new paste flag, or remove an unwanted one. */
916 if (paste_flag)
918 cpp_token *token = _cpp_temp_token (pfile);
919 token->type = (*paste_flag)->type;
920 token->val = (*paste_flag)->val;
921 if (src->flags & PASTE_LEFT)
922 token->flags = (*paste_flag)->flags | PASTE_LEFT;
923 else
924 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
925 *paste_flag = token;
929 /* Free the expanded arguments. */
930 for (i = 0; i < macro->paramc; i++)
931 if (args[i].expanded)
932 free (args[i].expanded);
934 push_ptoken_context (pfile, node, buff, first, dest - first);
937 /* Return a special padding token, with padding inherited from SOURCE. */
938 static const cpp_token *
939 padding_token (cpp_reader *pfile, const cpp_token *source)
941 cpp_token *result = _cpp_temp_token (pfile);
943 result->type = CPP_PADDING;
945 /* Data in GCed data structures cannot be made const so far, so we
946 need a cast here. */
947 result->val.source = (cpp_token *) source;
948 result->flags = 0;
949 return result;
952 /* Get a new uninitialized context. Create a new one if we cannot
953 re-use an old one. */
954 static cpp_context *
955 next_context (cpp_reader *pfile)
957 cpp_context *result = pfile->context->next;
959 if (result == 0)
961 result = XNEW (cpp_context);
962 result->prev = pfile->context;
963 result->next = 0;
964 pfile->context->next = result;
967 pfile->context = result;
968 return result;
971 /* Push a list of pointers to tokens. */
972 static void
973 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
974 const cpp_token **first, unsigned int count)
976 cpp_context *context = next_context (pfile);
978 context->direct_p = false;
979 context->macro = macro;
980 context->buff = buff;
981 FIRST (context).ptoken = first;
982 LAST (context).ptoken = first + count;
985 /* Push a list of tokens. */
986 void
987 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
988 const cpp_token *first, unsigned int count)
990 cpp_context *context = next_context (pfile);
992 context->direct_p = true;
993 context->macro = macro;
994 context->buff = NULL;
995 FIRST (context).token = first;
996 LAST (context).token = first + count;
999 /* Push a traditional macro's replacement text. */
1000 void
1001 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
1002 const uchar *start, size_t len)
1004 cpp_context *context = next_context (pfile);
1006 context->direct_p = true;
1007 context->macro = macro;
1008 context->buff = NULL;
1009 CUR (context) = start;
1010 RLIMIT (context) = start + len;
1011 macro->flags |= NODE_DISABLED;
1014 /* Expand an argument ARG before replacing parameters in a
1015 function-like macro. This works by pushing a context with the
1016 argument's tokens, and then expanding that into a temporary buffer
1017 as if it were a normal part of the token stream. collect_args()
1018 has terminated the argument's tokens with a CPP_EOF so that we know
1019 when we have fully expanded the argument. */
1020 static void
1021 expand_arg (cpp_reader *pfile, macro_arg *arg)
1023 unsigned int capacity;
1024 bool saved_warn_trad;
1026 if (arg->count == 0)
1027 return;
1029 /* Don't warn about funlike macros when pre-expanding. */
1030 saved_warn_trad = CPP_WTRADITIONAL (pfile);
1031 CPP_WTRADITIONAL (pfile) = 0;
1033 /* Loop, reading in the arguments. */
1034 capacity = 256;
1035 arg->expanded = XNEWVEC (const cpp_token *, capacity);
1037 push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
1038 for (;;)
1040 const cpp_token *token;
1042 if (arg->expanded_count + 1 >= capacity)
1044 capacity *= 2;
1045 arg->expanded = XRESIZEVEC (const cpp_token *, arg->expanded,
1046 capacity);
1049 token = cpp_get_token (pfile);
1051 if (token->type == CPP_EOF)
1052 break;
1054 arg->expanded[arg->expanded_count++] = token;
1057 _cpp_pop_context (pfile);
1059 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
1062 /* Pop the current context off the stack, re-enabling the macro if the
1063 context represented a macro's replacement list. The context
1064 structure is not freed so that we can re-use it later. */
1065 void
1066 _cpp_pop_context (cpp_reader *pfile)
1068 cpp_context *context = pfile->context;
1070 if (context->macro)
1071 context->macro->flags &= ~NODE_DISABLED;
1073 if (context->buff)
1074 _cpp_release_buff (pfile, context->buff);
1076 pfile->context = context->prev;
1079 /* External routine to get a token. Also used nearly everywhere
1080 internally, except for places where we know we can safely call
1081 _cpp_lex_token directly, such as lexing a directive name.
1083 Macro expansions and directives are transparently handled,
1084 including entering included files. Thus tokens are post-macro
1085 expansion, and after any intervening directives. External callers
1086 see CPP_EOF only at EOF. Internal callers also see it when meeting
1087 a directive inside a macro call, when at the end of a directive and
1088 state.in_directive is still 1, and at the end of argument
1089 pre-expansion. */
1090 const cpp_token *
1091 cpp_get_token (cpp_reader *pfile)
1093 const cpp_token *result;
1095 for (;;)
1097 cpp_hashnode *node;
1098 cpp_context *context = pfile->context;
1100 /* Context->prev == 0 <=> base context. */
1101 if (!context->prev)
1102 result = _cpp_lex_token (pfile);
1103 else if (FIRST (context).token != LAST (context).token)
1105 if (context->direct_p)
1106 result = FIRST (context).token++;
1107 else
1108 result = *FIRST (context).ptoken++;
1110 if (result->flags & PASTE_LEFT)
1112 paste_all_tokens (pfile, result);
1113 if (pfile->state.in_directive)
1114 continue;
1115 return padding_token (pfile, result);
1118 else
1120 _cpp_pop_context (pfile);
1121 if (pfile->state.in_directive)
1122 continue;
1123 return &pfile->avoid_paste;
1126 if (pfile->state.in_directive && result->type == CPP_COMMENT)
1127 continue;
1129 if (result->type != CPP_NAME)
1130 break;
1132 node = result->val.node;
1134 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1135 break;
1137 if (!(node->flags & NODE_DISABLED))
1139 if (!pfile->state.prevent_expansion
1140 && enter_macro_context (pfile, node))
1142 if (pfile->state.in_directive)
1143 continue;
1144 return padding_token (pfile, result);
1147 else
1149 /* Flag this token as always unexpandable. FIXME: move this
1150 to collect_args()?. */
1151 cpp_token *t = _cpp_temp_token (pfile);
1152 t->type = result->type;
1153 t->flags = result->flags | NO_EXPAND;
1154 t->val = result->val;
1155 result = t;
1158 break;
1161 return result;
1164 /* Returns true if we're expanding an object-like macro that was
1165 defined in a system header. Just checks the macro at the top of
1166 the stack. Used for diagnostic suppression. */
1168 cpp_sys_macro_p (cpp_reader *pfile)
1170 cpp_hashnode *node = pfile->context->macro;
1172 return node && node->value.macro && node->value.macro->syshdr;
1175 /* Read each token in, until end of the current file. Directives are
1176 transparently processed. */
1177 void
1178 cpp_scan_nooutput (cpp_reader *pfile)
1180 /* Request a CPP_EOF token at the end of this file, rather than
1181 transparently continuing with the including file. */
1182 pfile->buffer->return_at_eof = true;
1184 pfile->state.discarding_output++;
1185 pfile->state.prevent_expansion++;
1187 if (CPP_OPTION (pfile, traditional))
1188 while (_cpp_read_logical_line_trad (pfile))
1190 else
1191 while (cpp_get_token (pfile)->type != CPP_EOF)
1194 pfile->state.discarding_output--;
1195 pfile->state.prevent_expansion--;
1198 /* Step back one (or more) tokens. Can only step back more than 1 if
1199 they are from the lexer, and not from macro expansion. */
1200 void
1201 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
1203 if (pfile->context->prev == NULL)
1205 pfile->lookaheads += count;
1206 while (count--)
1208 pfile->cur_token--;
1209 if (pfile->cur_token == pfile->cur_run->base
1210 /* Possible with -fpreprocessed and no leading #line. */
1211 && pfile->cur_run->prev != NULL)
1213 pfile->cur_run = pfile->cur_run->prev;
1214 pfile->cur_token = pfile->cur_run->limit;
1218 else
1220 if (count != 1)
1221 abort ();
1222 if (pfile->context->direct_p)
1223 FIRST (pfile->context).token--;
1224 else
1225 FIRST (pfile->context).ptoken--;
1229 /* #define directive parsing and handling. */
1231 /* Returns nonzero if a macro redefinition warning is required. */
1232 static bool
1233 warn_of_redefinition (cpp_reader *pfile, const cpp_hashnode *node,
1234 const cpp_macro *macro2)
1236 const cpp_macro *macro1;
1237 unsigned int i;
1239 /* Some redefinitions need to be warned about regardless. */
1240 if (node->flags & NODE_WARN)
1241 return true;
1243 /* Redefinition of a macro is allowed if and only if the old and new
1244 definitions are the same. (6.10.3 paragraph 2). */
1245 macro1 = node->value.macro;
1247 /* Don't check count here as it can be different in valid
1248 traditional redefinitions with just whitespace differences. */
1249 if (macro1->paramc != macro2->paramc
1250 || macro1->fun_like != macro2->fun_like
1251 || macro1->variadic != macro2->variadic)
1252 return true;
1254 /* Check parameter spellings. */
1255 for (i = 0; i < macro1->paramc; i++)
1256 if (macro1->params[i] != macro2->params[i])
1257 return true;
1259 /* Check the replacement text or tokens. */
1260 if (CPP_OPTION (pfile, traditional))
1261 return _cpp_expansions_different_trad (macro1, macro2);
1263 if (macro1->count != macro2->count)
1264 return true;
1266 for (i = 0; i < macro1->count; i++)
1267 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
1268 return true;
1270 return false;
1273 /* Free the definition of hashnode H. */
1274 void
1275 _cpp_free_definition (cpp_hashnode *h)
1277 /* Macros and assertions no longer have anything to free. */
1278 h->type = NT_VOID;
1279 /* Clear builtin flag in case of redefinition. */
1280 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1283 /* Save parameter NODE to the parameter list of macro MACRO. Returns
1284 zero on success, nonzero if the parameter is a duplicate. */
1285 bool
1286 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
1288 unsigned int len;
1289 /* Constraint 6.10.3.6 - duplicate parameter names. */
1290 if (node->flags & NODE_MACRO_ARG)
1292 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
1293 NODE_NAME (node));
1294 return true;
1297 if (BUFF_ROOM (pfile->a_buff)
1298 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1299 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1301 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1302 node->flags |= NODE_MACRO_ARG;
1303 len = macro->paramc * sizeof (union _cpp_hashnode_value);
1304 if (len > pfile->macro_buffer_len)
1306 pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
1307 len);
1308 pfile->macro_buffer_len = len;
1310 ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
1311 = node->value;
1313 node->value.arg_index = macro->paramc;
1314 return false;
1317 /* Check the syntax of the parameters in a MACRO definition. Returns
1318 false if an error occurs. */
1319 static bool
1320 parse_params (cpp_reader *pfile, cpp_macro *macro)
1322 unsigned int prev_ident = 0;
1324 for (;;)
1326 const cpp_token *token = _cpp_lex_token (pfile);
1328 switch (token->type)
1330 default:
1331 /* Allow/ignore comments in parameter lists if we are
1332 preserving comments in macro expansions. */
1333 if (token->type == CPP_COMMENT
1334 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
1335 continue;
1337 cpp_error (pfile, CPP_DL_ERROR,
1338 "\"%s\" may not appear in macro parameter list",
1339 cpp_token_as_text (pfile, token));
1340 return false;
1342 case CPP_NAME:
1343 if (prev_ident)
1345 cpp_error (pfile, CPP_DL_ERROR,
1346 "macro parameters must be comma-separated");
1347 return false;
1349 prev_ident = 1;
1351 if (_cpp_save_parameter (pfile, macro, token->val.node))
1352 return false;
1353 continue;
1355 case CPP_CLOSE_PAREN:
1356 if (prev_ident || macro->paramc == 0)
1357 return true;
1359 /* Fall through to pick up the error. */
1360 case CPP_COMMA:
1361 if (!prev_ident)
1363 cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
1364 return false;
1366 prev_ident = 0;
1367 continue;
1369 case CPP_ELLIPSIS:
1370 macro->variadic = 1;
1371 if (!prev_ident)
1373 _cpp_save_parameter (pfile, macro,
1374 pfile->spec_nodes.n__VA_ARGS__);
1375 pfile->state.va_args_ok = 1;
1376 if (! CPP_OPTION (pfile, c99)
1377 && CPP_OPTION (pfile, pedantic)
1378 && CPP_OPTION (pfile, warn_variadic_macros))
1379 cpp_error (pfile, CPP_DL_PEDWARN,
1380 "anonymous variadic macros were introduced in C99");
1382 else if (CPP_OPTION (pfile, pedantic)
1383 && CPP_OPTION (pfile, warn_variadic_macros))
1384 cpp_error (pfile, CPP_DL_PEDWARN,
1385 "ISO C does not permit named variadic macros");
1387 /* We're at the end, and just expect a closing parenthesis. */
1388 token = _cpp_lex_token (pfile);
1389 if (token->type == CPP_CLOSE_PAREN)
1390 return true;
1391 /* Fall through. */
1393 case CPP_EOF:
1394 cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
1395 return false;
1400 /* Allocate room for a token from a macro's replacement list. */
1401 static cpp_token *
1402 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
1404 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1405 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1407 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1410 /* Lex a token from the expansion of MACRO, but mark parameters as we
1411 find them and warn of traditional stringification. */
1412 static cpp_token *
1413 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
1415 cpp_token *token, *saved_cur_token;
1417 saved_cur_token = pfile->cur_token;
1418 pfile->cur_token = alloc_expansion_token (pfile, macro);
1419 token = _cpp_lex_direct (pfile);
1420 pfile->cur_token = saved_cur_token;
1422 /* Is this a parameter? */
1423 if (token->type == CPP_NAME
1424 && (token->val.node->flags & NODE_MACRO_ARG) != 0)
1426 token->type = CPP_MACRO_ARG;
1427 token->val.arg_no = token->val.node->value.arg_index;
1429 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1430 && (token->type == CPP_STRING || token->type == CPP_CHAR))
1431 check_trad_stringification (pfile, macro, &token->val.str);
1433 return token;
1436 static bool
1437 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
1439 cpp_token *token;
1440 const cpp_token *ctoken;
1441 bool following_paste_op = false;
1442 const char *paste_op_error_msg =
1443 N_("'##' cannot appear at either end of a macro expansion");
1445 /* Get the first token of the expansion (or the '(' of a
1446 function-like macro). */
1447 ctoken = _cpp_lex_token (pfile);
1449 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1451 bool ok = parse_params (pfile, macro);
1452 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1453 if (!ok)
1454 return false;
1456 /* Success. Commit or allocate the parameter array. */
1457 if (pfile->hash_table->alloc_subobject)
1459 cpp_hashnode **params =
1460 (cpp_hashnode **) pfile->hash_table->alloc_subobject
1461 (sizeof (cpp_hashnode *) * macro->paramc);
1462 memcpy (params, macro->params,
1463 sizeof (cpp_hashnode *) * macro->paramc);
1464 macro->params = params;
1466 else
1467 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1468 macro->fun_like = 1;
1470 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1472 /* While ISO C99 requires whitespace before replacement text
1473 in a macro definition, ISO C90 with TC1 allows there characters
1474 from the basic source character set. */
1475 if (CPP_OPTION (pfile, c99))
1476 cpp_error (pfile, CPP_DL_PEDWARN,
1477 "ISO C99 requires whitespace after the macro name");
1478 else
1480 int warntype = CPP_DL_WARNING;
1481 switch (ctoken->type)
1483 case CPP_ATSIGN:
1484 case CPP_AT_NAME:
1485 case CPP_OBJC_STRING:
1486 /* '@' is not in basic character set. */
1487 warntype = CPP_DL_PEDWARN;
1488 break;
1489 case CPP_OTHER:
1490 /* Basic character set sans letters, digits and _. */
1491 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
1492 ctoken->val.str.text[0]) == NULL)
1493 warntype = CPP_DL_PEDWARN;
1494 break;
1495 default:
1496 /* All other tokens start with a character from basic
1497 character set. */
1498 break;
1500 cpp_error (pfile, warntype,
1501 "missing whitespace after the macro name");
1505 if (macro->fun_like)
1506 token = lex_expansion_token (pfile, macro);
1507 else
1509 token = alloc_expansion_token (pfile, macro);
1510 *token = *ctoken;
1513 for (;;)
1515 /* Check the stringifying # constraint 6.10.3.2.1 of
1516 function-like macros when lexing the subsequent token. */
1517 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1519 if (token->type == CPP_MACRO_ARG)
1521 token->flags &= ~PREV_WHITE;
1522 token->flags |= STRINGIFY_ARG;
1523 token->flags |= token[-1].flags & PREV_WHITE;
1524 token[-1] = token[0];
1525 macro->count--;
1527 /* Let assembler get away with murder. */
1528 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1530 cpp_error (pfile, CPP_DL_ERROR,
1531 "'#' is not followed by a macro parameter");
1532 return false;
1536 if (token->type == CPP_EOF)
1538 /* Paste operator constraint 6.10.3.3.1:
1539 Token-paste ##, can appear in both object-like and
1540 function-like macros, but not at the end. */
1541 if (following_paste_op)
1543 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
1544 return false;
1546 break;
1549 /* Paste operator constraint 6.10.3.3.1. */
1550 if (token->type == CPP_PASTE)
1552 /* Token-paste ##, can appear in both object-like and
1553 function-like macros, but not at the beginning. */
1554 if (macro->count == 1)
1556 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
1557 return false;
1560 --macro->count;
1561 token[-1].flags |= PASTE_LEFT;
1564 following_paste_op = (token->type == CPP_PASTE);
1565 token = lex_expansion_token (pfile, macro);
1568 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1569 macro->traditional = 0;
1571 /* Don't count the CPP_EOF. */
1572 macro->count--;
1574 /* Clear whitespace on first token for warn_of_redefinition(). */
1575 if (macro->count)
1576 macro->exp.tokens[0].flags &= ~PREV_WHITE;
1578 /* Commit or allocate the memory. */
1579 if (pfile->hash_table->alloc_subobject)
1581 cpp_token *tokns =
1582 (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
1583 * macro->count);
1584 memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
1585 macro->exp.tokens = tokns;
1587 else
1588 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
1590 return true;
1593 /* Parse a macro and save its expansion. Returns nonzero on success. */
1594 bool
1595 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
1597 cpp_macro *macro;
1598 unsigned int i;
1599 bool ok;
1601 if (pfile->hash_table->alloc_subobject)
1602 macro = (cpp_macro *) pfile->hash_table->alloc_subobject
1603 (sizeof (cpp_macro));
1604 else
1605 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1606 macro->line = pfile->directive_line;
1607 macro->params = 0;
1608 macro->paramc = 0;
1609 macro->variadic = 0;
1610 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
1611 macro->count = 0;
1612 macro->fun_like = 0;
1613 /* To suppress some diagnostics. */
1614 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
1616 if (CPP_OPTION (pfile, traditional))
1617 ok = _cpp_create_trad_definition (pfile, macro);
1618 else
1620 ok = create_iso_definition (pfile, macro);
1622 /* We set the type for SEEN_EOL() in directives.c.
1624 Longer term we should lex the whole line before coming here,
1625 and just copy the expansion. */
1627 /* Stop the lexer accepting __VA_ARGS__. */
1628 pfile->state.va_args_ok = 0;
1631 /* Clear the fast argument lookup indices. */
1632 for (i = macro->paramc; i-- > 0; )
1634 struct cpp_hashnode *node = macro->params[i];
1635 node->flags &= ~ NODE_MACRO_ARG;
1636 node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
1639 if (!ok)
1640 return ok;
1642 if (node->type == NT_MACRO)
1644 if (CPP_OPTION (pfile, warn_unused_macros))
1645 _cpp_warn_if_unused_macro (pfile, node, NULL);
1647 if (warn_of_redefinition (pfile, node, macro))
1649 cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->directive_line, 0,
1650 "\"%s\" redefined", NODE_NAME (node));
1652 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1653 cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1654 node->value.macro->line, 0,
1655 "this is the location of the previous definition");
1659 if (node->type != NT_VOID)
1660 _cpp_free_definition (node);
1662 /* Enter definition in hash table. */
1663 node->type = NT_MACRO;
1664 node->value.macro = macro;
1665 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1666 node->flags |= NODE_WARN;
1668 return ok;
1671 /* Warn if a token in STRING matches one of a function-like MACRO's
1672 parameters. */
1673 static void
1674 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
1675 const cpp_string *string)
1677 unsigned int i, len;
1678 const uchar *p, *q, *limit;
1680 /* Loop over the string. */
1681 limit = string->text + string->len - 1;
1682 for (p = string->text + 1; p < limit; p = q)
1684 /* Find the start of an identifier. */
1685 while (p < limit && !is_idstart (*p))
1686 p++;
1688 /* Find the end of the identifier. */
1689 q = p;
1690 while (q < limit && is_idchar (*q))
1691 q++;
1693 len = q - p;
1695 /* Loop over the function macro arguments to see if the
1696 identifier inside the string matches one of them. */
1697 for (i = 0; i < macro->paramc; i++)
1699 const cpp_hashnode *node = macro->params[i];
1701 if (NODE_LEN (node) == len
1702 && !memcmp (p, NODE_NAME (node), len))
1704 cpp_error (pfile, CPP_DL_WARNING,
1705 "macro argument \"%s\" would be stringified in traditional C",
1706 NODE_NAME (node));
1707 break;
1713 /* Returns the name, arguments and expansion of a macro, in a format
1714 suitable to be read back in again, and therefore also for DWARF 2
1715 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1716 Caller is expected to generate the "#define" bit if needed. The
1717 returned text is temporary, and automatically freed later. */
1718 const unsigned char *
1719 cpp_macro_definition (cpp_reader *pfile, const cpp_hashnode *node)
1721 unsigned int i, len;
1722 const cpp_macro *macro = node->value.macro;
1723 unsigned char *buffer;
1725 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1727 cpp_error (pfile, CPP_DL_ICE,
1728 "invalid hash type %d in cpp_macro_definition", node->type);
1729 return 0;
1732 /* Calculate length. */
1733 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
1734 if (macro->fun_like)
1736 len += 4; /* "()" plus possible final ".." of named
1737 varargs (we have + 1 below). */
1738 for (i = 0; i < macro->paramc; i++)
1739 len += NODE_LEN (macro->params[i]) + 1; /* "," */
1742 /* This should match below where we fill in the buffer. */
1743 if (CPP_OPTION (pfile, traditional))
1744 len += _cpp_replacement_text_len (macro);
1745 else
1747 for (i = 0; i < macro->count; i++)
1749 cpp_token *token = &macro->exp.tokens[i];
1751 if (token->type == CPP_MACRO_ARG)
1752 len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1753 else
1754 len += cpp_token_len (token);
1756 if (token->flags & STRINGIFY_ARG)
1757 len++; /* "#" */
1758 if (token->flags & PASTE_LEFT)
1759 len += 3; /* " ##" */
1760 if (token->flags & PREV_WHITE)
1761 len++; /* " " */
1765 if (len > pfile->macro_buffer_len)
1767 pfile->macro_buffer = XRESIZEVEC (unsigned char,
1768 pfile->macro_buffer, len);
1769 pfile->macro_buffer_len = len;
1772 /* Fill in the buffer. Start with the macro name. */
1773 buffer = pfile->macro_buffer;
1774 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1775 buffer += NODE_LEN (node);
1777 /* Parameter names. */
1778 if (macro->fun_like)
1780 *buffer++ = '(';
1781 for (i = 0; i < macro->paramc; i++)
1783 cpp_hashnode *param = macro->params[i];
1785 if (param != pfile->spec_nodes.n__VA_ARGS__)
1787 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1788 buffer += NODE_LEN (param);
1791 if (i + 1 < macro->paramc)
1792 /* Don't emit a space after the comma here; we're trying
1793 to emit a Dwarf-friendly definition, and the Dwarf spec
1794 forbids spaces in the argument list. */
1795 *buffer++ = ',';
1796 else if (macro->variadic)
1797 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1799 *buffer++ = ')';
1802 /* The Dwarf spec requires a space after the macro name, even if the
1803 definition is the empty string. */
1804 *buffer++ = ' ';
1806 if (CPP_OPTION (pfile, traditional))
1807 buffer = _cpp_copy_replacement_text (macro, buffer);
1808 else if (macro->count)
1809 /* Expansion tokens. */
1811 for (i = 0; i < macro->count; i++)
1813 cpp_token *token = &macro->exp.tokens[i];
1815 if (token->flags & PREV_WHITE)
1816 *buffer++ = ' ';
1817 if (token->flags & STRINGIFY_ARG)
1818 *buffer++ = '#';
1820 if (token->type == CPP_MACRO_ARG)
1822 memcpy (buffer,
1823 NODE_NAME (macro->params[token->val.arg_no - 1]),
1824 NODE_LEN (macro->params[token->val.arg_no - 1]));
1825 buffer += NODE_LEN (macro->params[token->val.arg_no - 1]);
1827 else
1828 buffer = cpp_spell_token (pfile, token, buffer, false);
1830 if (token->flags & PASTE_LEFT)
1832 *buffer++ = ' ';
1833 *buffer++ = '#';
1834 *buffer++ = '#';
1835 /* Next has PREV_WHITE; see _cpp_create_definition. */
1840 *buffer = '\0';
1841 return pfile->macro_buffer;