OSDN Git Service

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