OSDN Git Service

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