OSDN Git Service

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