OSDN Git Service

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