OSDN Git Service

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