OSDN Git Service

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