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