OSDN Git Service

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