OSDN Git Service

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