OSDN Git Service

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