OSDN Git Service

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