OSDN Git Service

* intrinsic.c (add_functions): Add function version of TTYNAM.
[pf3gnuchains/gcc-fork.git] / libcpp / macro.c
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 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
7
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.
12
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.
17
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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
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!  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "cpplib.h"
29 #include "internal.h"
30
31 typedef struct macro_arg macro_arg;
32 struct macro_arg
33 {
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.  */
39 };
40
41 /* Macro expansion.  */
42
43 static int enter_macro_context (cpp_reader *, cpp_hashnode *);
44 static int builtin_macro (cpp_reader *, cpp_hashnode *);
45 static void push_token_context (cpp_reader *, cpp_hashnode *,
46                                 const cpp_token *, unsigned int);
47 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
48                                  const cpp_token **, unsigned int);
49 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *);
50 static cpp_context *next_context (cpp_reader *);
51 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
52 static void expand_arg (cpp_reader *, macro_arg *);
53 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
54 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
55 static void paste_all_tokens (cpp_reader *, const cpp_token *);
56 static bool paste_tokens (cpp_reader *, const cpp_token **, const cpp_token *);
57 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
58                           macro_arg *);
59 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *);
60 static bool create_iso_definition (cpp_reader *, cpp_macro *);
61
62 /* #define directive parsing and handling.  */
63
64 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
65 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
66 static bool warn_of_redefinition (cpp_reader *, const cpp_hashnode *,
67                                   const cpp_macro *);
68 static bool parse_params (cpp_reader *, cpp_macro *);
69 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
70                                         const cpp_string *);
71
72 /* Emits a warning if NODE is a macro defined in the main file that
73    has not been used.  */
74 int
75 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
76                            void *v ATTRIBUTE_UNUSED)
77 {
78   if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
79     {
80       cpp_macro *macro = node->value.macro;
81
82       if (!macro->used
83           && MAIN_FILE_P (linemap_lookup (pfile->line_table, macro->line)))
84         cpp_error_with_line (pfile, CPP_DL_WARNING, macro->line, 0,
85                              "macro \"%s\" is not used", NODE_NAME (node));
86     }
87
88   return 1;
89 }
90
91 /* Allocates and returns a CPP_STRING token, containing TEXT of length
92    LEN, after null-terminating it.  TEXT must be in permanent storage.  */
93 static const cpp_token *
94 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
95 {
96   cpp_token *token = _cpp_temp_token (pfile);
97
98   text[len] = '\0';
99   token->type = CPP_STRING;
100   token->val.str.len = len;
101   token->val.str.text = text;
102   token->flags = 0;
103   return token;
104 }
105
106 static const char * const monthnames[] =
107 {
108   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
109   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
110 };
111
112 /* Helper function for builtin_macro.  Returns the text generated by
113    a builtin macro. */
114 const uchar *
115 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
116 {
117   const struct line_map *map;
118   const uchar *result = NULL;
119   unsigned int number = 1;
120
121   switch (node->value.builtin)
122     {
123     default:
124       cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
125                  NODE_NAME (node));
126       break;
127
128     case BT_FILE:
129     case BT_BASE_FILE:
130       {
131         unsigned int len;
132         const char *name;
133         uchar *buf;
134         map = linemap_lookup (pfile->line_table, pfile->line_table->highest_line);
135
136         if (node->value.builtin == BT_BASE_FILE)
137           while (! MAIN_FILE_P (map))
138             map = INCLUDED_FROM (pfile->line_table, map);
139
140         name = map->to_file;
141         len = strlen (name);
142         buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
143         result = buf;
144         *buf = '"';
145         buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
146         *buf++ = '"';
147         *buf = '\0';
148       }
149       break;
150
151     case BT_INCLUDE_LEVEL:
152       /* The line map depth counts the primary source as level 1, but
153          historically __INCLUDE_DEPTH__ has called the primary source
154          level 0.  */
155       number = pfile->line_table->depth - 1;
156       break;
157
158     case BT_SPECLINE:
159       map = &pfile->line_table->maps[pfile->line_table->used-1];
160       /* If __LINE__ is embedded in a macro, it must expand to the
161          line of the macro's invocation, not its definition.
162          Otherwise things like assert() will not work properly.  */
163       if (CPP_OPTION (pfile, traditional))
164         number = pfile->line_table->highest_line;
165       else
166         number = pfile->cur_token[-1].src_loc;
167       number = SOURCE_LINE (map, number);
168       break;
169
170       /* __STDC__ has the value 1 under normal circumstances.
171          However, if (a) we are in a system header, (b) the option
172          stdc_0_in_system_headers is true (set by target config), and
173          (c) we are not in strictly conforming mode, then it has the
174          value 0.  */
175     case BT_STDC:
176       {
177         if (cpp_in_system_header (pfile)
178             && CPP_OPTION (pfile, stdc_0_in_system_headers)
179             && !CPP_OPTION (pfile,std))
180           number = 0;
181         else
182           number = 1;
183       }
184       break;
185
186     case BT_DATE:
187     case BT_TIME:
188       if (pfile->date == NULL)
189         {
190           /* Allocate __DATE__ and __TIME__ strings from permanent
191              storage.  We only do this once, and don't generate them
192              at init time, because time() and localtime() are very
193              slow on some systems.  */
194           time_t tt;
195           struct tm *tb = NULL;
196
197           /* (time_t) -1 is a legitimate value for "number of seconds
198              since the Epoch", so we have to do a little dance to
199              distinguish that from a genuine error.  */
200           errno = 0;
201           tt = time(NULL);
202           if (tt != (time_t)-1 || errno == 0)
203             tb = localtime (&tt);
204
205           if (tb)
206             {
207               pfile->date = _cpp_unaligned_alloc (pfile,
208                                                   sizeof ("\"Oct 11 1347\""));
209               sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
210                        monthnames[tb->tm_mon], tb->tm_mday,
211                        tb->tm_year + 1900);
212
213               pfile->time = _cpp_unaligned_alloc (pfile,
214                                                   sizeof ("\"12:34:56\""));
215               sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
216                        tb->tm_hour, tb->tm_min, tb->tm_sec);
217             }
218           else
219             {
220               cpp_errno (pfile, CPP_DL_WARNING,
221                          "could not determine date and time");
222                 
223               pfile->date = U"\"??? ?? ????\"";
224               pfile->time = U"\"??:??:??\"";
225             }
226         }
227
228       if (node->value.builtin == BT_DATE)
229         result = pfile->date;
230       else
231         result = pfile->time;
232       break;
233     }
234
235   if (result == NULL)
236     {
237       /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers.  */
238       result = _cpp_unaligned_alloc (pfile, 21);
239       sprintf ((char *) result, "%u", number);
240     }
241
242   return result;      
243 }
244
245 /* Convert builtin macros like __FILE__ to a token and push it on the
246    context stack.  Also handles _Pragma, for which a new token may not
247    be created.  Returns 1 if it generates a new token context, 0 to
248    return the token to the caller.  */
249 static int
250 builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
251 {
252   const uchar *buf;
253   size_t len;
254   char *nbuf;
255
256   if (node->value.builtin == BT_PRAGMA)
257     {
258       /* Don't interpret _Pragma within directives.  The standard is
259          not clear on this, but to me this makes most sense.  */
260       if (pfile->state.in_directive)
261         return 0;
262
263       _cpp_do__Pragma (pfile);
264       if (pfile->directive_result.type == CPP_PRAGMA) 
265         {
266           cpp_token *tok = _cpp_temp_token (pfile);
267           *tok = pfile->directive_result;
268           push_token_context (pfile, NULL, tok, 1);
269         }
270
271       return 1;
272     }
273
274   buf = _cpp_builtin_macro_text (pfile, node);
275   len = ustrlen (buf);
276   nbuf = (char *) alloca (len + 1);
277   memcpy (nbuf, buf, len);
278   nbuf[len]='\n';
279
280   cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
281   _cpp_clean_line (pfile);
282
283   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
284   pfile->cur_token = _cpp_temp_token (pfile);
285   push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
286   if (pfile->buffer->cur != pfile->buffer->rlimit)
287     cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
288                NODE_NAME (node));
289   _cpp_pop_buffer (pfile);
290
291   return 1;
292 }
293
294 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
295    backslashes and double quotes. DEST must be of sufficient size.
296    Returns a pointer to the end of the string.  */
297 uchar *
298 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
299 {
300   while (len--)
301     {
302       uchar c = *src++;
303
304       if (c == '\\' || c == '"')
305         {
306           *dest++ = '\\';
307           *dest++ = c;
308         }
309       else
310           *dest++ = c;
311     }
312
313   return dest;
314 }
315
316 /* Convert a token sequence ARG to a single string token according to
317    the rules of the ISO C #-operator.  */
318 static const cpp_token *
319 stringify_arg (cpp_reader *pfile, macro_arg *arg)
320 {
321   unsigned char *dest;
322   unsigned int i, escape_it, backslash_count = 0;
323   const cpp_token *source = NULL;
324   size_t len;
325
326   if (BUFF_ROOM (pfile->u_buff) < 3)
327     _cpp_extend_buff (pfile, &pfile->u_buff, 3);
328   dest = BUFF_FRONT (pfile->u_buff);
329   *dest++ = '"';
330
331   /* Loop, reading in the argument's tokens.  */
332   for (i = 0; i < arg->count; i++)
333     {
334       const cpp_token *token = arg->first[i];
335
336       if (token->type == CPP_PADDING)
337         {
338           if (source == NULL)
339             source = token->val.source;
340           continue;
341         }
342
343       escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
344                    || token->type == CPP_CHAR || token->type == CPP_WCHAR);
345
346       /* Room for each char being written in octal, initial space and
347          final quote and NUL.  */
348       len = cpp_token_len (token);
349       if (escape_it)
350         len *= 4;
351       len += 3;
352
353       if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
354         {
355           size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
356           _cpp_extend_buff (pfile, &pfile->u_buff, len);
357           dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
358         }
359
360       /* Leading white space?  */
361       if (dest - 1 != BUFF_FRONT (pfile->u_buff))
362         {
363           if (source == NULL)
364             source = token;
365           if (source->flags & PREV_WHITE)
366             *dest++ = ' ';
367         }
368       source = NULL;
369
370       if (escape_it)
371         {
372           _cpp_buff *buff = _cpp_get_buff (pfile, len);
373           unsigned char *buf = BUFF_FRONT (buff);
374           len = cpp_spell_token (pfile, token, buf, true) - buf;
375           dest = cpp_quote_string (dest, buf, len);
376           _cpp_release_buff (pfile, buff);
377         }
378       else
379         dest = cpp_spell_token (pfile, token, dest, true);
380
381       if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
382         backslash_count++;
383       else
384         backslash_count = 0;
385     }
386
387   /* Ignore the final \ of invalid string literals.  */
388   if (backslash_count & 1)
389     {
390       cpp_error (pfile, CPP_DL_WARNING,
391                  "invalid string literal, ignoring final '\\'");
392       dest--;
393     }
394
395   /* Commit the memory, including NUL, and return the token.  */
396   *dest++ = '"';
397   len = dest - BUFF_FRONT (pfile->u_buff);
398   BUFF_FRONT (pfile->u_buff) = dest + 1;
399   return new_string_token (pfile, dest - len, len);
400 }
401
402 /* Try to paste two tokens.  On success, return nonzero.  In any
403    case, PLHS is updated to point to the pasted token, which is
404    guaranteed to not have the PASTE_LEFT flag set.  */
405 static bool
406 paste_tokens (cpp_reader *pfile, const cpp_token **plhs, const cpp_token *rhs)
407 {
408   unsigned char *buf, *end;
409   const cpp_token *lhs;
410   unsigned int len;
411   bool valid;
412
413   lhs = *plhs;
414   len = cpp_token_len (lhs) + cpp_token_len (rhs) + 1;
415   buf = (unsigned char *) alloca (len);
416   end = cpp_spell_token (pfile, lhs, buf, false);
417
418   /* Avoid comment headers, since they are still processed in stage 3.
419      It is simpler to insert a space here, rather than modifying the
420      lexer to ignore comments in some circumstances.  Simply returning
421      false doesn't work, since we want to clear the PASTE_LEFT flag.  */
422   if (lhs->type == CPP_DIV && rhs->type != CPP_EQ)
423     *end++ = ' ';
424   end = cpp_spell_token (pfile, rhs, end, false);
425   *end = '\n';
426
427   cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
428   _cpp_clean_line (pfile);
429
430   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
431   pfile->cur_token = _cpp_temp_token (pfile);
432   *plhs = _cpp_lex_direct (pfile);
433   valid = pfile->buffer->cur == pfile->buffer->rlimit;
434   _cpp_pop_buffer (pfile);
435
436   return valid;
437 }
438
439 /* Handles an arbitrarily long sequence of ## operators, with initial
440    operand LHS.  This implementation is left-associative,
441    non-recursive, and finishes a paste before handling succeeding
442    ones.  If a paste fails, we back up to the RHS of the failing ##
443    operator before pushing the context containing the result of prior
444    successful pastes, with the effect that the RHS appears in the
445    output stream after the pasted LHS normally.  */
446 static void
447 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
448 {
449   const cpp_token *rhs;
450   cpp_context *context = pfile->context;
451
452   do
453     {
454       /* Take the token directly from the current context.  We can do
455          this, because we are in the replacement list of either an
456          object-like macro, or a function-like macro with arguments
457          inserted.  In either case, the constraints to #define
458          guarantee we have at least one more token.  */
459       if (context->direct_p)
460         rhs = FIRST (context).token++;
461       else
462         rhs = *FIRST (context).ptoken++;
463
464       if (rhs->type == CPP_PADDING)
465         abort ();
466
467       if (!paste_tokens (pfile, &lhs, rhs))
468         {
469           _cpp_backup_tokens (pfile, 1);
470
471           /* Mandatory error for all apart from assembler.  */
472           if (CPP_OPTION (pfile, lang) != CLK_ASM)
473             cpp_error (pfile, CPP_DL_ERROR,
474          "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
475                        cpp_token_as_text (pfile, lhs),
476                        cpp_token_as_text (pfile, rhs));
477           break;
478         }
479     }
480   while (rhs->flags & PASTE_LEFT);
481
482   /* Put the resulting token in its own context.  */
483   push_token_context (pfile, NULL, lhs, 1);
484 }
485
486 /* Returns TRUE if the number of arguments ARGC supplied in an
487    invocation of the MACRO referenced by NODE is valid.  An empty
488    invocation to a macro with no parameters should pass ARGC as zero.
489
490    Note that MACRO cannot necessarily be deduced from NODE, in case
491    NODE was redefined whilst collecting arguments.  */
492 bool
493 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
494 {
495   if (argc == macro->paramc)
496     return true;
497
498   if (argc < macro->paramc)
499     {
500       /* As an extension, a rest argument is allowed to not appear in
501          the invocation at all.
502          e.g. #define debug(format, args...) something
503          debug("string");
504
505          This is exactly the same as if there had been an empty rest
506          argument - debug("string", ).  */
507
508       if (argc + 1 == macro->paramc && macro->variadic)
509         {
510           if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
511             cpp_error (pfile, CPP_DL_PEDWARN,
512                        "ISO C99 requires rest arguments to be used");
513           return true;
514         }
515
516       cpp_error (pfile, CPP_DL_ERROR,
517                  "macro \"%s\" requires %u arguments, but only %u given",
518                  NODE_NAME (node), macro->paramc, argc);
519     }
520   else
521     cpp_error (pfile, CPP_DL_ERROR,
522                "macro \"%s\" passed %u arguments, but takes just %u",
523                NODE_NAME (node), argc, macro->paramc);
524
525   return false;
526 }
527
528 /* Reads and returns the arguments to a function-like macro
529    invocation.  Assumes the opening parenthesis has been processed.
530    If there is an error, emits an appropriate diagnostic and returns
531    NULL.  Each argument is terminated by a CPP_EOF token, for the
532    future benefit of expand_arg().  */
533 static _cpp_buff *
534 collect_args (cpp_reader *pfile, const cpp_hashnode *node)
535 {
536   _cpp_buff *buff, *base_buff;
537   cpp_macro *macro;
538   macro_arg *args, *arg;
539   const cpp_token *token;
540   unsigned int argc;
541
542   macro = node->value.macro;
543   if (macro->paramc)
544     argc = macro->paramc;
545   else
546     argc = 1;
547   buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
548                                        + sizeof (macro_arg)));
549   base_buff = buff;
550   args = (macro_arg *) buff->base;
551   memset (args, 0, argc * sizeof (macro_arg));
552   buff->cur = (unsigned char *) &args[argc];
553   arg = args, argc = 0;
554
555   /* Collect the tokens making up each argument.  We don't yet know
556      how many arguments have been supplied, whether too many or too
557      few.  Hence the slightly bizarre usage of "argc" and "arg".  */
558   do
559     {
560       unsigned int paren_depth = 0;
561       unsigned int ntokens = 0;
562
563       argc++;
564       arg->first = (const cpp_token **) buff->cur;
565
566       for (;;)
567         {
568           /* Require space for 2 new tokens (including a CPP_EOF).  */
569           if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
570             {
571               buff = _cpp_append_extend_buff (pfile, buff,
572                                               1000 * sizeof (cpp_token *));
573               arg->first = (const cpp_token **) buff->cur;
574             }
575
576           token = cpp_get_token (pfile);
577
578           if (token->type == CPP_PADDING)
579             {
580               /* Drop leading padding.  */
581               if (ntokens == 0)
582                 continue;
583             }
584           else if (token->type == CPP_OPEN_PAREN)
585             paren_depth++;
586           else if (token->type == CPP_CLOSE_PAREN)
587             {
588               if (paren_depth-- == 0)
589                 break;
590             }
591           else if (token->type == CPP_COMMA)
592             {
593               /* A comma does not terminate an argument within
594                  parentheses or as part of a variable argument.  */
595               if (paren_depth == 0
596                   && ! (macro->variadic && argc == macro->paramc))
597                 break;
598             }
599           else if (token->type == CPP_EOF
600                    || (token->type == CPP_HASH && token->flags & BOL))
601             break;
602
603           arg->first[ntokens++] = token;
604         }
605
606       /* Drop trailing padding.  */
607       while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
608         ntokens--;
609
610       arg->count = ntokens;
611       arg->first[ntokens] = &pfile->eof;
612
613       /* Terminate the argument.  Excess arguments loop back and
614          overwrite the final legitimate argument, before failing.  */
615       if (argc <= macro->paramc)
616         {
617           buff->cur = (unsigned char *) &arg->first[ntokens + 1];
618           if (argc != macro->paramc)
619             arg++;
620         }
621     }
622   while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
623
624   if (token->type == CPP_EOF)
625     {
626       /* We still need the CPP_EOF to end directives, and to end
627          pre-expansion of a macro argument.  Step back is not
628          unconditional, since we don't want to return a CPP_EOF to our
629          callers at the end of an -include-d file.  */
630       if (pfile->context->prev || pfile->state.in_directive)
631         _cpp_backup_tokens (pfile, 1);
632       cpp_error (pfile, CPP_DL_ERROR,
633                  "unterminated argument list invoking macro \"%s\"",
634                  NODE_NAME (node));
635     }
636   else
637     {
638       /* A single empty argument is counted as no argument.  */
639       if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
640         argc = 0;
641       if (_cpp_arguments_ok (pfile, macro, node, argc))
642         {
643           /* GCC has special semantics for , ## b where b is a varargs
644              parameter: we remove the comma if b was omitted entirely.
645              If b was merely an empty argument, the comma is retained.
646              If the macro takes just one (varargs) parameter, then we
647              retain the comma only if we are standards conforming.
648
649              If FIRST is NULL replace_args () swallows the comma.  */
650           if (macro->variadic && (argc < macro->paramc
651                                   || (argc == 1 && args[0].count == 0
652                                       && !CPP_OPTION (pfile, std))))
653             args[macro->paramc - 1].first = NULL;
654           return base_buff;
655         }
656     }
657
658   /* An error occurred.  */
659   _cpp_release_buff (pfile, base_buff);
660   return NULL;
661 }
662
663 /* Search for an opening parenthesis to the macro of NODE, in such a
664    way that, if none is found, we don't lose the information in any
665    intervening padding tokens.  If we find the parenthesis, collect
666    the arguments and return the buffer containing them.  */
667 static _cpp_buff *
668 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node)
669 {
670   const cpp_token *token, *padding = NULL;
671
672   for (;;)
673     {
674       token = cpp_get_token (pfile);
675       if (token->type != CPP_PADDING)
676         break;
677       if (padding == NULL
678           || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
679         padding = token;
680     }
681
682   if (token->type == CPP_OPEN_PAREN)
683     {
684       pfile->state.parsing_args = 2;
685       return collect_args (pfile, node);
686     }
687
688   /* CPP_EOF can be the end of macro arguments, or the end of the
689      file.  We mustn't back up over the latter.  Ugh.  */
690   if (token->type != CPP_EOF || token == &pfile->eof)
691     {
692       /* Back up.  We may have skipped padding, in which case backing
693          up more than one token when expanding macros is in general
694          too difficult.  We re-insert it in its own context.  */
695       _cpp_backup_tokens (pfile, 1);
696       if (padding)
697         push_token_context (pfile, NULL, padding, 1);
698     }
699
700   return NULL;
701 }
702
703 /* Push the context of a macro with hash entry NODE onto the context
704    stack.  If we can successfully expand the macro, we push a context
705    containing its yet-to-be-rescanned replacement list and return one.
706    Otherwise, we don't push a context and return zero.  */
707 static int
708 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node)
709 {
710   /* The presence of a macro invalidates a file's controlling macro.  */
711   pfile->mi_valid = false;
712
713   pfile->state.angled_headers = false;
714
715   /* Handle standard macros.  */
716   if (! (node->flags & NODE_BUILTIN))
717     {
718       cpp_macro *macro = node->value.macro;
719
720       if (macro->fun_like)
721         {
722           _cpp_buff *buff;
723
724           pfile->state.prevent_expansion++;
725           pfile->keep_tokens++;
726           pfile->state.parsing_args = 1;
727           buff = funlike_invocation_p (pfile, node);
728           pfile->state.parsing_args = 0;
729           pfile->keep_tokens--;
730           pfile->state.prevent_expansion--;
731
732           if (buff == NULL)
733             {
734               if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
735                 cpp_error (pfile, CPP_DL_WARNING,
736  "function-like macro \"%s\" must be used with arguments in traditional C",
737                            NODE_NAME (node));
738
739               return 0;
740             }
741
742           if (macro->paramc > 0)
743             replace_args (pfile, node, macro, (macro_arg *) buff->base);
744           _cpp_release_buff (pfile, buff);
745         }
746
747       /* Disable the macro within its expansion.  */
748       node->flags |= NODE_DISABLED;
749
750       macro->used = 1;
751
752       if (macro->paramc == 0)
753         push_token_context (pfile, node, macro->exp.tokens, macro->count);
754
755       return 1;
756     }
757
758   /* Handle built-in macros and the _Pragma operator.  */
759   return builtin_macro (pfile, node);
760 }
761
762 /* Replace the parameters in a function-like macro of NODE with the
763    actual ARGS, and place the result in a newly pushed token context.
764    Expand each argument before replacing, unless it is operated upon
765    by the # or ## operators.  */
766 static void
767 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro, macro_arg *args)
768 {
769   unsigned int i, total;
770   const cpp_token *src, *limit;
771   const cpp_token **dest, **first;
772   macro_arg *arg;
773   _cpp_buff *buff;
774
775   /* First, fully macro-expand arguments, calculating the number of
776      tokens in the final expansion as we go.  The ordering of the if
777      statements below is subtle; we must handle stringification before
778      pasting.  */
779   total = macro->count;
780   limit = macro->exp.tokens + macro->count;
781
782   for (src = macro->exp.tokens; src < limit; src++)
783     if (src->type == CPP_MACRO_ARG)
784       {
785         /* Leading and trailing padding tokens.  */
786         total += 2;
787
788         /* We have an argument.  If it is not being stringified or
789            pasted it is macro-replaced before insertion.  */
790         arg = &args[src->val.arg_no - 1];
791
792         if (src->flags & STRINGIFY_ARG)
793           {
794             if (!arg->stringified)
795               arg->stringified = stringify_arg (pfile, arg);
796           }
797         else if ((src->flags & PASTE_LEFT)
798                  || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
799           total += arg->count - 1;
800         else
801           {
802             if (!arg->expanded)
803               expand_arg (pfile, arg);
804             total += arg->expanded_count - 1;
805           }
806       }
807
808   /* Now allocate space for the expansion, copy the tokens and replace
809      the arguments.  */
810   buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
811   first = (const cpp_token **) buff->base;
812   dest = first;
813
814   for (src = macro->exp.tokens; src < limit; src++)
815     {
816       unsigned int count;
817       const cpp_token **from, **paste_flag;
818
819       if (src->type != CPP_MACRO_ARG)
820         {
821           *dest++ = src;
822           continue;
823         }
824
825       paste_flag = 0;
826       arg = &args[src->val.arg_no - 1];
827       if (src->flags & STRINGIFY_ARG)
828         count = 1, from = &arg->stringified;
829       else if (src->flags & PASTE_LEFT)
830         count = arg->count, from = arg->first;
831       else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
832         {
833           count = arg->count, from = arg->first;
834           if (dest != first)
835             {
836               if (dest[-1]->type == CPP_COMMA
837                   && macro->variadic
838                   && src->val.arg_no == macro->paramc)
839                 {
840                   /* Swallow a pasted comma if from == NULL, otherwise
841                      drop the paste flag.  */
842                   if (from == NULL)
843                     dest--;
844                   else
845                     paste_flag = dest - 1;
846                 }
847               /* Remove the paste flag if the RHS is a placemarker.  */
848               else if (count == 0)
849                 paste_flag = dest - 1;
850             }
851         }
852       else
853         count = arg->expanded_count, from = arg->expanded;
854
855       /* Padding on the left of an argument (unless RHS of ##).  */
856       if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
857           && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
858         *dest++ = padding_token (pfile, src);
859
860       if (count)
861         {
862           memcpy (dest, from, count * sizeof (cpp_token *));
863           dest += count;
864
865           /* With a non-empty argument on the LHS of ##, the last
866              token should be flagged PASTE_LEFT.  */
867           if (src->flags & PASTE_LEFT)
868             paste_flag = dest - 1;
869         }
870
871       /* Avoid paste on RHS (even case count == 0).  */
872       if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
873         *dest++ = &pfile->avoid_paste;
874
875       /* Add a new paste flag, or remove an unwanted one.  */
876       if (paste_flag)
877         {
878           cpp_token *token = _cpp_temp_token (pfile);
879           token->type = (*paste_flag)->type;
880           token->val = (*paste_flag)->val;
881           if (src->flags & PASTE_LEFT)
882             token->flags = (*paste_flag)->flags | PASTE_LEFT;
883           else
884             token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
885           *paste_flag = token;
886         }
887     }
888
889   /* Free the expanded arguments.  */
890   for (i = 0; i < macro->paramc; i++)
891     if (args[i].expanded)
892       free (args[i].expanded);
893
894   push_ptoken_context (pfile, node, buff, first, dest - first);
895 }
896
897 /* Return a special padding token, with padding inherited from SOURCE.  */
898 static const cpp_token *
899 padding_token (cpp_reader *pfile, const cpp_token *source)
900 {
901   cpp_token *result = _cpp_temp_token (pfile);
902
903   result->type = CPP_PADDING;
904
905   /* Data in GCed data structures cannot be made const so far, so we
906      need a cast here.  */
907   result->val.source = (cpp_token *) source;
908   result->flags = 0;
909   return result;
910 }
911
912 /* Get a new uninitialized context.  Create a new one if we cannot
913    re-use an old one.  */
914 static cpp_context *
915 next_context (cpp_reader *pfile)
916 {
917   cpp_context *result = pfile->context->next;
918
919   if (result == 0)
920     {
921       result = XNEW (cpp_context);
922       result->prev = pfile->context;
923       result->next = 0;
924       pfile->context->next = result;
925     }
926
927   pfile->context = result;
928   return result;
929 }
930
931 /* Push a list of pointers to tokens.  */
932 static void
933 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
934                      const cpp_token **first, unsigned int count)
935 {
936   cpp_context *context = next_context (pfile);
937
938   context->direct_p = false;
939   context->macro = macro;
940   context->buff = buff;
941   FIRST (context).ptoken = first;
942   LAST (context).ptoken = first + count;
943 }
944
945 /* Push a list of tokens.  */
946 static void
947 push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
948                     const cpp_token *first, unsigned int count)
949 {
950   cpp_context *context = next_context (pfile);
951
952   context->direct_p = true;
953   context->macro = macro;
954   context->buff = NULL;
955   FIRST (context).token = first;
956   LAST (context).token = first + count;
957 }
958
959 /* Push a traditional macro's replacement text.  */
960 void
961 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
962                         const uchar *start, size_t len)
963 {
964   cpp_context *context = next_context (pfile);
965
966   context->direct_p = true;
967   context->macro = macro;
968   context->buff = NULL;
969   CUR (context) = start;
970   RLIMIT (context) = start + len;
971   macro->flags |= NODE_DISABLED;
972 }
973
974 /* Expand an argument ARG before replacing parameters in a
975    function-like macro.  This works by pushing a context with the
976    argument's tokens, and then expanding that into a temporary buffer
977    as if it were a normal part of the token stream.  collect_args()
978    has terminated the argument's tokens with a CPP_EOF so that we know
979    when we have fully expanded the argument.  */
980 static void
981 expand_arg (cpp_reader *pfile, macro_arg *arg)
982 {
983   unsigned int capacity;
984   bool saved_warn_trad;
985
986   if (arg->count == 0)
987     return;
988
989   /* Don't warn about funlike macros when pre-expanding.  */
990   saved_warn_trad = CPP_WTRADITIONAL (pfile);
991   CPP_WTRADITIONAL (pfile) = 0;
992
993   /* Loop, reading in the arguments.  */
994   capacity = 256;
995   arg->expanded = XNEWVEC (const cpp_token *, capacity);
996
997   push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
998   for (;;)
999     {
1000       const cpp_token *token;
1001
1002       if (arg->expanded_count + 1 >= capacity)
1003         {
1004           capacity *= 2;
1005           arg->expanded = XRESIZEVEC (const cpp_token *, arg->expanded,
1006                                       capacity);
1007         }
1008
1009       token = cpp_get_token (pfile);
1010
1011       if (token->type == CPP_EOF)
1012         break;
1013
1014       arg->expanded[arg->expanded_count++] = token;
1015     }
1016
1017   _cpp_pop_context (pfile);
1018
1019   CPP_WTRADITIONAL (pfile) = saved_warn_trad;
1020 }
1021
1022 /* Pop the current context off the stack, re-enabling the macro if the
1023    context represented a macro's replacement list.  The context
1024    structure is not freed so that we can re-use it later.  */
1025 void
1026 _cpp_pop_context (cpp_reader *pfile)
1027 {
1028   cpp_context *context = pfile->context;
1029
1030   if (context->macro)
1031     context->macro->flags &= ~NODE_DISABLED;
1032
1033   if (context->buff)
1034     _cpp_release_buff (pfile, context->buff);
1035
1036   pfile->context = context->prev;
1037 }
1038
1039 /* External routine to get a token.  Also used nearly everywhere
1040    internally, except for places where we know we can safely call
1041    _cpp_lex_token directly, such as lexing a directive name.
1042
1043    Macro expansions and directives are transparently handled,
1044    including entering included files.  Thus tokens are post-macro
1045    expansion, and after any intervening directives.  External callers
1046    see CPP_EOF only at EOF.  Internal callers also see it when meeting
1047    a directive inside a macro call, when at the end of a directive and
1048    state.in_directive is still 1, and at the end of argument
1049    pre-expansion.  */
1050 const cpp_token *
1051 cpp_get_token (cpp_reader *pfile)
1052 {
1053   const cpp_token *result;
1054
1055   for (;;)
1056     {
1057       cpp_hashnode *node;
1058       cpp_context *context = pfile->context;
1059
1060       /* Context->prev == 0 <=> base context.  */
1061       if (!context->prev)
1062         result = _cpp_lex_token (pfile);
1063       else if (FIRST (context).token != LAST (context).token)
1064         {
1065           if (context->direct_p)
1066             result = FIRST (context).token++;
1067           else
1068             result = *FIRST (context).ptoken++;
1069
1070           if (result->flags & PASTE_LEFT)
1071             {
1072               paste_all_tokens (pfile, result);
1073               if (pfile->state.in_directive)
1074                 continue;
1075               return padding_token (pfile, result);
1076             }
1077         }
1078       else
1079         {
1080           _cpp_pop_context (pfile);
1081           if (pfile->state.in_directive)
1082             continue;
1083           return &pfile->avoid_paste;
1084         }
1085
1086       if (pfile->state.in_directive && result->type == CPP_COMMENT)
1087         continue;
1088
1089       if (result->type != CPP_NAME)
1090         break;
1091
1092       node = result->val.node;
1093
1094       if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1095         break;
1096
1097       if (!(node->flags & NODE_DISABLED))
1098         {
1099           if (!pfile->state.prevent_expansion
1100               && enter_macro_context (pfile, node))
1101             {
1102               if (pfile->state.in_directive)
1103                 continue;
1104               return padding_token (pfile, result);
1105             }
1106         }
1107       else
1108         {
1109           /* Flag this token as always unexpandable.  FIXME: move this
1110              to collect_args()?.  */
1111           cpp_token *t = _cpp_temp_token (pfile);
1112           t->type = result->type;
1113           t->flags = result->flags | NO_EXPAND;
1114           t->val = result->val;
1115           result = t;
1116         }
1117
1118       break;
1119     }
1120
1121   return result;
1122 }
1123
1124 /* Returns true if we're expanding an object-like macro that was
1125    defined in a system header.  Just checks the macro at the top of
1126    the stack.  Used for diagnostic suppression.  */
1127 int
1128 cpp_sys_macro_p (cpp_reader *pfile)
1129 {
1130   cpp_hashnode *node = pfile->context->macro;
1131
1132   return node && node->value.macro && node->value.macro->syshdr;
1133 }
1134
1135 /* Read each token in, until end of the current file.  Directives are
1136    transparently processed.  */
1137 void
1138 cpp_scan_nooutput (cpp_reader *pfile)
1139 {
1140   /* Request a CPP_EOF token at the end of this file, rather than
1141      transparently continuing with the including file.  */
1142   pfile->buffer->return_at_eof = true;
1143
1144   pfile->state.discarding_output++;
1145   pfile->state.prevent_expansion++;
1146
1147   if (CPP_OPTION (pfile, traditional))
1148     while (_cpp_read_logical_line_trad (pfile))
1149       ;
1150   else
1151     while (cpp_get_token (pfile)->type != CPP_EOF)
1152       ;
1153
1154   pfile->state.discarding_output--;
1155   pfile->state.prevent_expansion--;
1156 }
1157
1158 /* Step back one (or more) tokens.  Can only step mack more than 1 if
1159    they are from the lexer, and not from macro expansion.  */
1160 void
1161 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
1162 {
1163   if (pfile->context->prev == NULL)
1164     {
1165       pfile->lookaheads += count;
1166       while (count--)
1167         {
1168           pfile->cur_token--;
1169           if (pfile->cur_token == pfile->cur_run->base
1170               /* Possible with -fpreprocessed and no leading #line.  */
1171               && pfile->cur_run->prev != NULL)
1172             {
1173               pfile->cur_run = pfile->cur_run->prev;
1174               pfile->cur_token = pfile->cur_run->limit;
1175             }
1176         }
1177     }
1178   else
1179     {
1180       if (count != 1)
1181         abort ();
1182       if (pfile->context->direct_p)
1183         FIRST (pfile->context).token--;
1184       else
1185         FIRST (pfile->context).ptoken--;
1186     }
1187 }
1188
1189 /* #define directive parsing and handling.  */
1190
1191 /* Returns nonzero if a macro redefinition warning is required.  */
1192 static bool
1193 warn_of_redefinition (cpp_reader *pfile, const cpp_hashnode *node,
1194                       const cpp_macro *macro2)
1195 {
1196   const cpp_macro *macro1;
1197   unsigned int i;
1198
1199   /* Some redefinitions need to be warned about regardless.  */
1200   if (node->flags & NODE_WARN)
1201     return true;
1202
1203   /* Redefinition of a macro is allowed if and only if the old and new
1204      definitions are the same.  (6.10.3 paragraph 2).  */
1205   macro1 = node->value.macro;
1206
1207   /* Don't check count here as it can be different in valid
1208      traditional redefinitions with just whitespace differences.  */
1209   if (macro1->paramc != macro2->paramc
1210       || macro1->fun_like != macro2->fun_like
1211       || macro1->variadic != macro2->variadic)
1212     return true;
1213
1214   /* Check parameter spellings.  */
1215   for (i = 0; i < macro1->paramc; i++)
1216     if (macro1->params[i] != macro2->params[i])
1217       return true;
1218
1219   /* Check the replacement text or tokens.  */
1220   if (CPP_OPTION (pfile, traditional))
1221     return _cpp_expansions_different_trad (macro1, macro2);
1222
1223   if (macro1->count != macro2->count)
1224     return true;
1225
1226   for (i = 0; i < macro1->count; i++)
1227     if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
1228       return true;
1229
1230   return false;
1231 }
1232
1233 /* Free the definition of hashnode H.  */
1234 void
1235 _cpp_free_definition (cpp_hashnode *h)
1236 {
1237   /* Macros and assertions no longer have anything to free.  */
1238   h->type = NT_VOID;
1239   /* Clear builtin flag in case of redefinition.  */
1240   h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1241 }
1242
1243 /* Save parameter NODE to the parameter list of macro MACRO.  Returns
1244    zero on success, nonzero if the parameter is a duplicate.  */
1245 bool
1246 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
1247 {
1248   unsigned int len;
1249   /* Constraint 6.10.3.6 - duplicate parameter names.  */
1250   if (node->flags & NODE_MACRO_ARG)
1251     {
1252       cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
1253                  NODE_NAME (node));
1254       return true;
1255     }
1256
1257   if (BUFF_ROOM (pfile->a_buff)
1258       < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1259     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1260
1261   ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1262   node->flags |= NODE_MACRO_ARG;
1263   len = macro->paramc * sizeof (union _cpp_hashnode_value);
1264   if (len > pfile->macro_buffer_len)
1265     {
1266       pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
1267                                         len);
1268       pfile->macro_buffer_len = len;
1269     }
1270   ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
1271     = node->value;
1272   
1273   node->value.arg_index  = macro->paramc;
1274   return false;
1275 }
1276
1277 /* Check the syntax of the parameters in a MACRO definition.  Returns
1278    false if an error occurs.  */
1279 static bool
1280 parse_params (cpp_reader *pfile, cpp_macro *macro)
1281 {
1282   unsigned int prev_ident = 0;
1283
1284   for (;;)
1285     {
1286       const cpp_token *token = _cpp_lex_token (pfile);
1287
1288       switch (token->type)
1289         {
1290         default:
1291           /* Allow/ignore comments in parameter lists if we are
1292              preserving comments in macro expansions.  */
1293           if (token->type == CPP_COMMENT
1294               && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
1295             continue;
1296
1297           cpp_error (pfile, CPP_DL_ERROR,
1298                      "\"%s\" may not appear in macro parameter list",
1299                      cpp_token_as_text (pfile, token));
1300           return false;
1301
1302         case CPP_NAME:
1303           if (prev_ident)
1304             {
1305               cpp_error (pfile, CPP_DL_ERROR,
1306                          "macro parameters must be comma-separated");
1307               return false;
1308             }
1309           prev_ident = 1;
1310
1311           if (_cpp_save_parameter (pfile, macro, token->val.node))
1312             return false;
1313           continue;
1314
1315         case CPP_CLOSE_PAREN:
1316           if (prev_ident || macro->paramc == 0)
1317             return true;
1318
1319           /* Fall through to pick up the error.  */
1320         case CPP_COMMA:
1321           if (!prev_ident)
1322             {
1323               cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
1324               return false;
1325             }
1326           prev_ident = 0;
1327           continue;
1328
1329         case CPP_ELLIPSIS:
1330           macro->variadic = 1;
1331           if (!prev_ident)
1332             {
1333               _cpp_save_parameter (pfile, macro,
1334                                    pfile->spec_nodes.n__VA_ARGS__);
1335               pfile->state.va_args_ok = 1;
1336               if (! CPP_OPTION (pfile, c99)
1337                   && CPP_OPTION (pfile, pedantic)
1338                   && CPP_OPTION (pfile, warn_variadic_macros))
1339                 cpp_error (pfile, CPP_DL_PEDWARN,
1340                            "anonymous variadic macros were introduced in C99");
1341             }
1342           else if (CPP_OPTION (pfile, pedantic)
1343                    && CPP_OPTION (pfile, warn_variadic_macros))
1344             cpp_error (pfile, CPP_DL_PEDWARN,
1345                        "ISO C does not permit named variadic macros");
1346
1347           /* We're at the end, and just expect a closing parenthesis.  */
1348           token = _cpp_lex_token (pfile);
1349           if (token->type == CPP_CLOSE_PAREN)
1350             return true;
1351           /* Fall through.  */
1352
1353         case CPP_EOF:
1354           cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
1355           return false;
1356         }
1357     }
1358 }
1359
1360 /* Allocate room for a token from a macro's replacement list.  */
1361 static cpp_token *
1362 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
1363 {
1364   if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1365     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1366
1367   return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1368 }
1369
1370 /* Lex a token from the expansion of MACRO, but mark parameters as we
1371    find them and warn of traditional stringification.  */
1372 static cpp_token *
1373 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
1374 {
1375   cpp_token *token;
1376
1377   pfile->cur_token = alloc_expansion_token (pfile, macro);
1378   token = _cpp_lex_direct (pfile);
1379
1380   /* Is this a parameter?  */
1381   if (token->type == CPP_NAME
1382       && (token->val.node->flags & NODE_MACRO_ARG) != 0)
1383     {
1384       token->type = CPP_MACRO_ARG;
1385       token->val.arg_no = token->val.node->value.arg_index;
1386     }
1387   else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1388            && (token->type == CPP_STRING || token->type == CPP_CHAR))
1389     check_trad_stringification (pfile, macro, &token->val.str);
1390
1391   return token;
1392 }
1393
1394 static bool
1395 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
1396 {
1397   cpp_token *token;
1398   const cpp_token *ctoken;
1399
1400   /* Get the first token of the expansion (or the '(' of a
1401      function-like macro).  */
1402   ctoken = _cpp_lex_token (pfile);
1403
1404   if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1405     {
1406       bool ok = parse_params (pfile, macro);
1407       macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1408       if (!ok)
1409         return false;
1410
1411       /* Success.  Commit or allocate the parameter array.  */
1412       if (pfile->hash_table->alloc_subobject)
1413         {
1414           cpp_hashnode **params =
1415             (cpp_hashnode **) pfile->hash_table->alloc_subobject
1416             (sizeof (cpp_hashnode *) * macro->paramc);
1417           memcpy (params, macro->params,
1418                   sizeof (cpp_hashnode *) * macro->paramc);
1419           macro->params = params;
1420         }
1421       else
1422         BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1423       macro->fun_like = 1;
1424     }
1425   else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1426     {
1427       /* While ISO C99 requires whitespace before replacement text
1428          in a macro definition, ISO C90 with TC1 allows there characters
1429          from the basic source character set.  */
1430       if (CPP_OPTION (pfile, c99))
1431         cpp_error (pfile, CPP_DL_PEDWARN,
1432                    "ISO C99 requires whitespace after the macro name");
1433       else
1434         {
1435           int warntype = CPP_DL_WARNING;
1436           switch (ctoken->type)
1437             {
1438             case CPP_ATSIGN:
1439             case CPP_AT_NAME:
1440             case CPP_OBJC_STRING:
1441               /* '@' is not in basic character set.  */
1442               warntype = CPP_DL_PEDWARN;
1443               break;
1444             case CPP_OTHER:
1445               /* Basic character set sans letters, digits and _.  */
1446               if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
1447                           ctoken->val.str.text[0]) == NULL)
1448                 warntype = CPP_DL_PEDWARN;
1449               break;
1450             default:
1451               /* All other tokens start with a character from basic
1452                  character set.  */
1453               break;
1454             }
1455           cpp_error (pfile, warntype,
1456                      "missing whitespace after the macro name");
1457         }
1458     }
1459
1460   if (macro->fun_like)
1461     token = lex_expansion_token (pfile, macro);
1462   else
1463     {
1464       token = alloc_expansion_token (pfile, macro);
1465       *token = *ctoken;
1466     }
1467
1468   for (;;)
1469     {
1470       /* Check the stringifying # constraint 6.10.3.2.1 of
1471          function-like macros when lexing the subsequent token.  */
1472       if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1473         {
1474           if (token->type == CPP_MACRO_ARG)
1475             {
1476               token->flags &= ~PREV_WHITE;
1477               token->flags |= STRINGIFY_ARG;
1478               token->flags |= token[-1].flags & PREV_WHITE;
1479               token[-1] = token[0];
1480               macro->count--;
1481             }
1482           /* Let assembler get away with murder.  */
1483           else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1484             {
1485               cpp_error (pfile, CPP_DL_ERROR,
1486                          "'#' is not followed by a macro parameter");
1487               return false;
1488             }
1489         }
1490
1491       if (token->type == CPP_EOF)
1492         break;
1493
1494       /* Paste operator constraint 6.10.3.3.1.  */
1495       if (token->type == CPP_PASTE)
1496         {
1497           /* Token-paste ##, can appear in both object-like and
1498              function-like macros, but not at the ends.  */
1499           if (--macro->count > 0)
1500             token = lex_expansion_token (pfile, macro);
1501
1502           if (macro->count == 0 || token->type == CPP_EOF)
1503             {
1504               cpp_error (pfile, CPP_DL_ERROR,
1505                  "'##' cannot appear at either end of a macro expansion");
1506               return false;
1507             }
1508
1509           token[-1].flags |= PASTE_LEFT;
1510         }
1511
1512       token = lex_expansion_token (pfile, macro);
1513     }
1514
1515   macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1516   macro->traditional = 0;
1517
1518   /* Don't count the CPP_EOF.  */
1519   macro->count--;
1520
1521   /* Clear whitespace on first token for warn_of_redefinition().  */
1522   if (macro->count)
1523     macro->exp.tokens[0].flags &= ~PREV_WHITE;
1524
1525   /* Commit or allocate the memory.  */
1526   if (pfile->hash_table->alloc_subobject)
1527     {
1528       cpp_token *tokns =
1529         (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
1530                                                           * macro->count);
1531       memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
1532       macro->exp.tokens = tokns;
1533     }
1534   else
1535     BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
1536
1537   return true;
1538 }
1539
1540 /* Parse a macro and save its expansion.  Returns nonzero on success.  */
1541 bool
1542 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
1543 {
1544   cpp_macro *macro;
1545   unsigned int i;
1546   bool ok;
1547
1548   if (pfile->hash_table->alloc_subobject)
1549     macro = (cpp_macro *) pfile->hash_table->alloc_subobject
1550       (sizeof (cpp_macro));
1551   else
1552     macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1553   macro->line = pfile->directive_line;
1554   macro->params = 0;
1555   macro->paramc = 0;
1556   macro->variadic = 0;
1557   macro->used = !CPP_OPTION (pfile, warn_unused_macros);
1558   macro->count = 0;
1559   macro->fun_like = 0;
1560   /* To suppress some diagnostics.  */
1561   macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
1562
1563   if (CPP_OPTION (pfile, traditional))
1564     ok = _cpp_create_trad_definition (pfile, macro);
1565   else
1566     {
1567       cpp_token *saved_cur_token = pfile->cur_token;
1568
1569       ok = create_iso_definition (pfile, macro);
1570
1571       /* Restore lexer position because of games lex_expansion_token()
1572          plays lexing the macro.  We set the type for SEEN_EOL() in
1573          directives.c.
1574
1575          Longer term we should lex the whole line before coming here,
1576          and just copy the expansion.  */
1577       saved_cur_token[-1].type = pfile->cur_token[-1].type;
1578       pfile->cur_token = saved_cur_token;
1579
1580       /* Stop the lexer accepting __VA_ARGS__.  */
1581       pfile->state.va_args_ok = 0;
1582     }
1583
1584   /* Clear the fast argument lookup indices.  */
1585   for (i = macro->paramc; i-- > 0; )
1586     {
1587       struct cpp_hashnode *node = macro->params[i];
1588       node->flags &= ~ NODE_MACRO_ARG;
1589       node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
1590     }
1591
1592   if (!ok)
1593     return ok;
1594
1595   if (node->type == NT_MACRO)
1596     {
1597       if (CPP_OPTION (pfile, warn_unused_macros))
1598         _cpp_warn_if_unused_macro (pfile, node, NULL);
1599
1600       if (warn_of_redefinition (pfile, node, macro))
1601         {
1602           cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->directive_line, 0,
1603                                "\"%s\" redefined", NODE_NAME (node));
1604
1605           if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1606             cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1607                                  node->value.macro->line, 0,
1608                          "this is the location of the previous definition");
1609         }
1610     }
1611
1612   if (node->type != NT_VOID)
1613     _cpp_free_definition (node);
1614
1615   /* Enter definition in hash table.  */
1616   node->type = NT_MACRO;
1617   node->value.macro = macro;
1618   if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1619     node->flags |= NODE_WARN;
1620
1621   return ok;
1622 }
1623
1624 /* Warn if a token in STRING matches one of a function-like MACRO's
1625    parameters.  */
1626 static void
1627 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
1628                             const cpp_string *string)
1629 {
1630   unsigned int i, len;
1631   const uchar *p, *q, *limit;
1632
1633   /* Loop over the string.  */
1634   limit = string->text + string->len - 1;
1635   for (p = string->text + 1; p < limit; p = q)
1636     {
1637       /* Find the start of an identifier.  */
1638       while (p < limit && !is_idstart (*p))
1639         p++;
1640
1641       /* Find the end of the identifier.  */
1642       q = p;
1643       while (q < limit && is_idchar (*q))
1644         q++;
1645
1646       len = q - p;
1647
1648       /* Loop over the function macro arguments to see if the
1649          identifier inside the string matches one of them.  */
1650       for (i = 0; i < macro->paramc; i++)
1651         {
1652           const cpp_hashnode *node = macro->params[i];
1653
1654           if (NODE_LEN (node) == len
1655               && !memcmp (p, NODE_NAME (node), len))
1656             {
1657               cpp_error (pfile, CPP_DL_WARNING,
1658            "macro argument \"%s\" would be stringified in traditional C",
1659                          NODE_NAME (node));
1660               break;
1661             }
1662         }
1663     }
1664 }
1665
1666 /* Returns the name, arguments and expansion of a macro, in a format
1667    suitable to be read back in again, and therefore also for DWARF 2
1668    debugging info.  e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1669    Caller is expected to generate the "#define" bit if needed.  The
1670    returned text is temporary, and automatically freed later.  */
1671 const unsigned char *
1672 cpp_macro_definition (cpp_reader *pfile, const cpp_hashnode *node)
1673 {
1674   unsigned int i, len;
1675   const cpp_macro *macro = node->value.macro;
1676   unsigned char *buffer;
1677
1678   if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1679     {
1680       cpp_error (pfile, CPP_DL_ICE,
1681                  "invalid hash type %d in cpp_macro_definition", node->type);
1682       return 0;
1683     }
1684
1685   /* Calculate length.  */
1686   len = NODE_LEN (node) + 2;                    /* ' ' and NUL.  */
1687   if (macro->fun_like)
1688     {
1689       len += 4;         /* "()" plus possible final ".." of named
1690                            varargs (we have + 1 below).  */
1691       for (i = 0; i < macro->paramc; i++)
1692         len += NODE_LEN (macro->params[i]) + 1; /* "," */
1693     }
1694
1695   /* This should match below where we fill in the buffer.  */
1696   if (CPP_OPTION (pfile, traditional))
1697     len += _cpp_replacement_text_len (macro);
1698   else
1699     {
1700       for (i = 0; i < macro->count; i++)
1701         {
1702           cpp_token *token = &macro->exp.tokens[i];
1703
1704           if (token->type == CPP_MACRO_ARG)
1705             len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1706           else
1707             len += cpp_token_len (token);
1708
1709           if (token->flags & STRINGIFY_ARG)
1710             len++;                      /* "#" */
1711           if (token->flags & PASTE_LEFT)
1712             len += 3;           /* " ##" */
1713           if (token->flags & PREV_WHITE)
1714             len++;              /* " " */
1715         }
1716     }
1717
1718   if (len > pfile->macro_buffer_len)
1719     {
1720       pfile->macro_buffer = XRESIZEVEC (unsigned char,
1721                                         pfile->macro_buffer, len);
1722       pfile->macro_buffer_len = len;
1723     }
1724
1725   /* Fill in the buffer.  Start with the macro name.  */
1726   buffer = pfile->macro_buffer;
1727   memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1728   buffer += NODE_LEN (node);
1729
1730   /* Parameter names.  */
1731   if (macro->fun_like)
1732     {
1733       *buffer++ = '(';
1734       for (i = 0; i < macro->paramc; i++)
1735         {
1736           cpp_hashnode *param = macro->params[i];
1737
1738           if (param != pfile->spec_nodes.n__VA_ARGS__)
1739             {
1740               memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1741               buffer += NODE_LEN (param);
1742             }
1743
1744           if (i + 1 < macro->paramc)
1745             /* Don't emit a space after the comma here; we're trying
1746                to emit a Dwarf-friendly definition, and the Dwarf spec
1747                forbids spaces in the argument list.  */
1748             *buffer++ = ',';
1749           else if (macro->variadic)
1750             *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1751         }
1752       *buffer++ = ')';
1753     }
1754
1755   /* The Dwarf spec requires a space after the macro name, even if the
1756      definition is the empty string.  */
1757   *buffer++ = ' ';
1758
1759   if (CPP_OPTION (pfile, traditional))
1760     buffer = _cpp_copy_replacement_text (macro, buffer);
1761   else if (macro->count)
1762   /* Expansion tokens.  */
1763     {
1764       for (i = 0; i < macro->count; i++)
1765         {
1766           cpp_token *token = &macro->exp.tokens[i];
1767
1768           if (token->flags & PREV_WHITE)
1769             *buffer++ = ' ';
1770           if (token->flags & STRINGIFY_ARG)
1771             *buffer++ = '#';
1772
1773           if (token->type == CPP_MACRO_ARG)
1774             {
1775               memcpy (buffer,
1776                       NODE_NAME (macro->params[token->val.arg_no - 1]),
1777                       NODE_LEN (macro->params[token->val.arg_no - 1]));
1778               buffer += NODE_LEN (macro->params[token->val.arg_no - 1]);
1779             }
1780           else
1781             buffer = cpp_spell_token (pfile, token, buffer, false);
1782
1783           if (token->flags & PASTE_LEFT)
1784             {
1785               *buffer++ = ' ';
1786               *buffer++ = '#';
1787               *buffer++ = '#';
1788               /* Next has PREV_WHITE; see _cpp_create_definition.  */
1789             }
1790         }
1791     }
1792
1793   *buffer = '\0';
1794   return pfile->macro_buffer;
1795 }