OSDN Git Service

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