OSDN Git Service

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