OSDN Git Service

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