re PR preprocessor/33919 (__BASE_FILE__ does not expand correctly when included from...
[platform/upstream/gcc.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,
4    2006, 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
5    Written by Per Bothner, 1994.
6    Based on CCCP program by Paul Rubin, June 1986
7    Adapted to ANSI C, Richard Stallman, Jan 1987
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 3, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.
22
23  In other words, you are welcome to use, share and improve this program.
24  You are forbidden to forbid anyone else to use, share and improve
25  what you give them.   Help stamp out software-hoarding!  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "cpplib.h"
30 #include "internal.h"
31
32 typedef struct macro_arg macro_arg;
33 /* This structure represents the tokens of a macro argument.  These
34    tokens can be macro themselves, in which case they can be either
35    expanded or unexpanded.  When they are expanded, this data
36    structure keeps both the expanded and unexpanded forms.  */
37 struct macro_arg
38 {
39   const cpp_token **first;      /* First token in unexpanded argument.  */
40   const cpp_token **expanded;   /* Macro-expanded argument.  */
41   const cpp_token *stringified; /* Stringified argument.  */
42   unsigned int count;           /* # of tokens in argument.  */
43   unsigned int expanded_count;  /* # of tokens in expanded argument.  */
44   source_location *virt_locs;   /* Where virtual locations for
45                                    unexpanded tokens are stored.  */
46   source_location *expanded_virt_locs; /* Where virtual locations for
47                                           expanded tokens are
48                                           stored.  */
49 };
50
51 /* The kind of macro tokens which the instance of
52    macro_arg_token_iter is supposed to iterate over.  */
53 enum macro_arg_token_kind {
54   MACRO_ARG_TOKEN_NORMAL,
55   /* This is a macro argument token that got transformed into a string
56      litteral, e.g. #foo.  */
57   MACRO_ARG_TOKEN_STRINGIFIED,
58   /* This is a token resulting from the expansion of a macro
59      argument that was itself a macro.  */
60   MACRO_ARG_TOKEN_EXPANDED
61 };
62
63 /* An iterator over tokens coming from a function-like macro
64    argument.  */
65 typedef struct macro_arg_token_iter macro_arg_token_iter;
66 struct macro_arg_token_iter
67 {
68   /* Whether or not -ftrack-macro-expansion is used.  */
69   bool track_macro_exp_p;
70   /* The kind of token over which we are supposed to iterate.  */
71   enum macro_arg_token_kind kind;
72   /* A pointer to the current token pointed to by the iterator.  */
73   const cpp_token **token_ptr;
74   /* A pointer to the "full" location of the current token.  If
75      -ftrack-macro-expansion is used this location tracks loci accross
76      macro expansion.  */
77   const source_location *location_ptr;
78 #ifdef ENABLE_CHECKING
79   /* The number of times the iterator went forward. This useful only
80      when checking is enabled.  */
81   size_t num_forwards;
82 #endif
83 };
84
85 /* Macro expansion.  */
86
87 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
88                                 const cpp_token *, source_location);
89 static int builtin_macro (cpp_reader *, cpp_hashnode *);
90 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
91                                  const cpp_token **, unsigned int);
92 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
93                                           _cpp_buff *, source_location *,
94                                           const cpp_token **, unsigned int);
95 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
96                                 _cpp_buff **, unsigned *);
97 static cpp_context *next_context (cpp_reader *);
98 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
99 static void expand_arg (cpp_reader *, macro_arg *);
100 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
101 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
102 static void paste_all_tokens (cpp_reader *, const cpp_token *);
103 static bool paste_tokens (cpp_reader *, const cpp_token **, const cpp_token *);
104 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
105 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
106 static void delete_macro_args (_cpp_buff*, unsigned num_args);
107 static void set_arg_token (macro_arg *, const cpp_token *,
108                            source_location, size_t,
109                            enum macro_arg_token_kind,
110                            bool);
111 static const source_location *get_arg_token_location (const macro_arg *,
112                                                       enum macro_arg_token_kind);
113 static const cpp_token **arg_token_ptr_at (const macro_arg *,
114                                            size_t,
115                                            enum macro_arg_token_kind,
116                                            source_location **virt_location);
117
118 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
119                                        enum macro_arg_token_kind,
120                                        const macro_arg *,
121                                        const cpp_token **);
122 static const cpp_token *macro_arg_token_iter_get_token
123 (const macro_arg_token_iter *it);
124 static source_location macro_arg_token_iter_get_location
125 (const macro_arg_token_iter *);
126 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
127 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
128                                    source_location **);
129 static size_t tokens_buff_count (_cpp_buff *);
130 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
131 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
132                                                           source_location *,
133                                                           const cpp_token *,
134                                                           source_location,
135                                                           source_location,
136                                                           const struct line_map *,
137                                                           unsigned int);
138
139 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
140                                                 source_location *,
141                                                 const cpp_token *,
142                                                 source_location,
143                                                 source_location,
144                                                 const struct line_map *,
145                                                 unsigned int);
146 static inline void tokens_buff_remove_last_token (_cpp_buff *);
147 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
148                           macro_arg *, source_location);
149 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
150                                         _cpp_buff **, unsigned *);
151 static bool create_iso_definition (cpp_reader *, cpp_macro *);
152
153 /* #define directive parsing and handling.  */
154
155 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
156 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
157 static bool warn_of_redefinition (cpp_reader *, cpp_hashnode *,
158                                   const cpp_macro *);
159 static bool parse_params (cpp_reader *, cpp_macro *);
160 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
161                                         const cpp_string *);
162 static bool reached_end_of_context (cpp_context *);
163 static void consume_next_token_from_context (cpp_reader *pfile,
164                                              const cpp_token **,
165                                              source_location *);
166 static const cpp_token* cpp_get_token_1 (cpp_reader *, source_location *);
167
168 /* Statistical counter tracking the number of macros that got
169    expanded.  */
170 unsigned num_expanded_macros_counter = 0;
171 /* Statistical counter tracking the total number tokens resulting
172    from macro expansion.  */
173 unsigned num_macro_tokens_counter = 0;
174
175 /* Emits a warning if NODE is a macro defined in the main file that
176    has not been used.  */
177 int
178 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
179                            void *v ATTRIBUTE_UNUSED)
180 {
181   if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
182     {
183       cpp_macro *macro = node->value.macro;
184
185       if (!macro->used
186           && MAIN_FILE_P (linemap_lookup (pfile->line_table, macro->line)))
187         cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
188                                "macro \"%s\" is not used", NODE_NAME (node));
189     }
190
191   return 1;
192 }
193
194 /* Allocates and returns a CPP_STRING token, containing TEXT of length
195    LEN, after null-terminating it.  TEXT must be in permanent storage.  */
196 static const cpp_token *
197 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
198 {
199   cpp_token *token = _cpp_temp_token (pfile);
200
201   text[len] = '\0';
202   token->type = CPP_STRING;
203   token->val.str.len = len;
204   token->val.str.text = text;
205   token->flags = 0;
206   return token;
207 }
208
209 static const char * const monthnames[] =
210 {
211   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
212   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
213 };
214
215 /* Helper function for builtin_macro.  Returns the text generated by
216    a builtin macro. */
217 const uchar *
218 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
219 {
220   const struct line_map *map;
221   const uchar *result = NULL;
222   linenum_type number = 1;
223
224   switch (node->value.builtin)
225     {
226     default:
227       cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
228                  NODE_NAME (node));
229       break;
230
231     case BT_TIMESTAMP:
232       {
233         cpp_buffer *pbuffer = cpp_get_buffer (pfile);
234         if (pbuffer->timestamp == NULL)
235           {
236             /* Initialize timestamp value of the assotiated file. */
237             struct _cpp_file *file = cpp_get_file (pbuffer);
238             if (file)
239               {
240                 /* Generate __TIMESTAMP__ string, that represents 
241                    the date and time of the last modification 
242                    of the current source file. The string constant 
243                    looks like "Sun Sep 16 01:03:52 1973".  */
244                 struct tm *tb = NULL;
245                 struct stat *st = _cpp_get_file_stat (file);
246                 if (st)
247                   tb = localtime (&st->st_mtime);
248                 if (tb)
249                   {
250                     char *str = asctime (tb);
251                     size_t len = strlen (str);
252                     unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
253                     buf[0] = '"';
254                     strcpy ((char *) buf + 1, str);
255                     buf[len] = '"';
256                     pbuffer->timestamp = buf;
257                   }
258                 else
259                   {
260                     cpp_errno (pfile, CPP_DL_WARNING,
261                         "could not determine file timestamp");
262                     pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
263                   }
264               }
265           }
266         result = pbuffer->timestamp;
267       }
268       break;
269     case BT_FILE:
270     case BT_BASE_FILE:
271       {
272         unsigned int len;
273         const char *name;
274         uchar *buf;
275         
276         if (node->value.builtin == BT_FILE)
277           name = linemap_get_expansion_filename (pfile->line_table,
278                                                  pfile->line_table->highest_line);
279         else
280           {
281             name = _cpp_get_file_name (pfile->main_file);
282             if (!name)
283               abort ();
284           }
285         len = strlen (name);
286         buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
287         result = buf;
288         *buf = '"';
289         buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
290         *buf++ = '"';
291         *buf = '\0';
292       }
293       break;
294
295     case BT_INCLUDE_LEVEL:
296       /* The line map depth counts the primary source as level 1, but
297          historically __INCLUDE_DEPTH__ has called the primary source
298          level 0.  */
299       number = pfile->line_table->depth - 1;
300       break;
301
302     case BT_SPECLINE:
303       map = LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table);
304       /* If __LINE__ is embedded in a macro, it must expand to the
305          line of the macro's invocation, not its definition.
306          Otherwise things like assert() will not work properly.  */
307       number = linemap_get_expansion_line (pfile->line_table,
308                                            CPP_OPTION (pfile, traditional)
309                                            ? pfile->line_table->highest_line
310                                            : pfile->cur_token[-1].src_loc);
311       break;
312
313       /* __STDC__ has the value 1 under normal circumstances.
314          However, if (a) we are in a system header, (b) the option
315          stdc_0_in_system_headers is true (set by target config), and
316          (c) we are not in strictly conforming mode, then it has the
317          value 0.  (b) and (c) are already checked in cpp_init_builtins.  */
318     case BT_STDC:
319       if (cpp_in_system_header (pfile))
320         number = 0;
321       else
322         number = 1;
323       break;
324
325     case BT_DATE:
326     case BT_TIME:
327       if (pfile->date == NULL)
328         {
329           /* Allocate __DATE__ and __TIME__ strings from permanent
330              storage.  We only do this once, and don't generate them
331              at init time, because time() and localtime() are very
332              slow on some systems.  */
333           time_t tt;
334           struct tm *tb = NULL;
335
336           /* (time_t) -1 is a legitimate value for "number of seconds
337              since the Epoch", so we have to do a little dance to
338              distinguish that from a genuine error.  */
339           errno = 0;
340           tt = time(NULL);
341           if (tt != (time_t)-1 || errno == 0)
342             tb = localtime (&tt);
343
344           if (tb)
345             {
346               pfile->date = _cpp_unaligned_alloc (pfile,
347                                                   sizeof ("\"Oct 11 1347\""));
348               sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
349                        monthnames[tb->tm_mon], tb->tm_mday,
350                        tb->tm_year + 1900);
351
352               pfile->time = _cpp_unaligned_alloc (pfile,
353                                                   sizeof ("\"12:34:56\""));
354               sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
355                        tb->tm_hour, tb->tm_min, tb->tm_sec);
356             }
357           else
358             {
359               cpp_errno (pfile, CPP_DL_WARNING,
360                          "could not determine date and time");
361                 
362               pfile->date = UC"\"??? ?? ????\"";
363               pfile->time = UC"\"??:??:??\"";
364             }
365         }
366
367       if (node->value.builtin == BT_DATE)
368         result = pfile->date;
369       else
370         result = pfile->time;
371       break;
372
373     case BT_COUNTER:
374       if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
375         cpp_error (pfile, CPP_DL_ERROR,
376             "__COUNTER__ expanded inside directive with -fdirectives-only");
377       number = pfile->counter++;
378       break;
379     }
380
381   if (result == NULL)
382     {
383       /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers.  */
384       result = _cpp_unaligned_alloc (pfile, 21);
385       sprintf ((char *) result, "%u", number);
386     }
387
388   return result;      
389 }
390
391 /* Convert builtin macros like __FILE__ to a token and push it on the
392    context stack.  Also handles _Pragma, for which a new token may not
393    be created.  Returns 1 if it generates a new token context, 0 to
394    return the token to the caller.  */
395 static int
396 builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
397 {
398   const uchar *buf;
399   size_t len;
400   char *nbuf;
401
402   if (node->value.builtin == BT_PRAGMA)
403     {
404       /* Don't interpret _Pragma within directives.  The standard is
405          not clear on this, but to me this makes most sense.  */
406       if (pfile->state.in_directive)
407         return 0;
408
409       return _cpp_do__Pragma (pfile);
410     }
411
412   buf = _cpp_builtin_macro_text (pfile, node);
413   len = ustrlen (buf);
414   nbuf = (char *) alloca (len + 1);
415   memcpy (nbuf, buf, len);
416   nbuf[len]='\n';
417
418   cpp_push_buffer (pfile, (uchar *) nbuf, len, /* 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   _cpp_push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
424   if (pfile->buffer->cur != pfile->buffer->rlimit)
425     cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
426                NODE_NAME (node));
427   _cpp_pop_buffer (pfile);
428
429   return 1;
430 }
431
432 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
433    backslashes and double quotes. DEST must be of sufficient size.
434    Returns a pointer to the end of the string.  */
435 uchar *
436 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
437 {
438   while (len--)
439     {
440       uchar c = *src++;
441
442       if (c == '\\' || c == '"')
443         {
444           *dest++ = '\\';
445           *dest++ = c;
446         }
447       else
448           *dest++ = c;
449     }
450
451   return dest;
452 }
453
454 /* Convert a token sequence ARG to a single string token according to
455    the rules of the ISO C #-operator.  */
456 static const cpp_token *
457 stringify_arg (cpp_reader *pfile, macro_arg *arg)
458 {
459   unsigned char *dest;
460   unsigned int i, escape_it, backslash_count = 0;
461   const cpp_token *source = NULL;
462   size_t len;
463
464   if (BUFF_ROOM (pfile->u_buff) < 3)
465     _cpp_extend_buff (pfile, &pfile->u_buff, 3);
466   dest = BUFF_FRONT (pfile->u_buff);
467   *dest++ = '"';
468
469   /* Loop, reading in the argument's tokens.  */
470   for (i = 0; i < arg->count; i++)
471     {
472       const cpp_token *token = arg->first[i];
473
474       if (token->type == CPP_PADDING)
475         {
476           if (source == NULL
477               || (!(source->flags & PREV_WHITE)
478                   && token->val.source == NULL))
479             source = token->val.source;
480           continue;
481         }
482
483       escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
484                    || token->type == CPP_WSTRING || token->type == CPP_WCHAR
485                    || token->type == CPP_STRING32 || token->type == CPP_CHAR32
486                    || token->type == CPP_STRING16 || token->type == CPP_CHAR16
487                    || token->type == CPP_UTF8STRING);
488
489       /* Room for each char being written in octal, initial space and
490          final quote and NUL.  */
491       len = cpp_token_len (token);
492       if (escape_it)
493         len *= 4;
494       len += 3;
495
496       if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
497         {
498           size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
499           _cpp_extend_buff (pfile, &pfile->u_buff, len);
500           dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
501         }
502
503       /* Leading white space?  */
504       if (dest - 1 != BUFF_FRONT (pfile->u_buff))
505         {
506           if (source == NULL)
507             source = token;
508           if (source->flags & PREV_WHITE)
509             *dest++ = ' ';
510         }
511       source = NULL;
512
513       if (escape_it)
514         {
515           _cpp_buff *buff = _cpp_get_buff (pfile, len);
516           unsigned char *buf = BUFF_FRONT (buff);
517           len = cpp_spell_token (pfile, token, buf, true) - buf;
518           dest = cpp_quote_string (dest, buf, len);
519           _cpp_release_buff (pfile, buff);
520         }
521       else
522         dest = cpp_spell_token (pfile, token, dest, true);
523
524       if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
525         backslash_count++;
526       else
527         backslash_count = 0;
528     }
529
530   /* Ignore the final \ of invalid string literals.  */
531   if (backslash_count & 1)
532     {
533       cpp_error (pfile, CPP_DL_WARNING,
534                  "invalid string literal, ignoring final '\\'");
535       dest--;
536     }
537
538   /* Commit the memory, including NUL, and return the token.  */
539   *dest++ = '"';
540   len = dest - BUFF_FRONT (pfile->u_buff);
541   BUFF_FRONT (pfile->u_buff) = dest + 1;
542   return new_string_token (pfile, dest - len, len);
543 }
544
545 /* Try to paste two tokens.  On success, return nonzero.  In any
546    case, PLHS is updated to point to the pasted token, which is
547    guaranteed to not have the PASTE_LEFT flag set.  */
548 static bool
549 paste_tokens (cpp_reader *pfile, const cpp_token **plhs, const cpp_token *rhs)
550 {
551   unsigned char *buf, *end, *lhsend;
552   cpp_token *lhs;
553   unsigned int len;
554
555   len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
556   buf = (unsigned char *) alloca (len);
557   end = lhsend = cpp_spell_token (pfile, *plhs, buf, false);
558
559   /* Avoid comment headers, since they are still processed in stage 3.
560      It is simpler to insert a space here, rather than modifying the
561      lexer to ignore comments in some circumstances.  Simply returning
562      false doesn't work, since we want to clear the PASTE_LEFT flag.  */
563   if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
564     *end++ = ' ';
565   /* In one obscure case we might see padding here.  */
566   if (rhs->type != CPP_PADDING)
567     end = cpp_spell_token (pfile, rhs, end, false);
568   *end = '\n';
569
570   cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
571   _cpp_clean_line (pfile);
572
573   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
574   pfile->cur_token = _cpp_temp_token (pfile);
575   lhs = _cpp_lex_direct (pfile);
576   if (pfile->buffer->cur != pfile->buffer->rlimit)
577     {
578       source_location saved_loc = lhs->src_loc;
579
580       _cpp_pop_buffer (pfile);
581       _cpp_backup_tokens (pfile, 1);
582       *lhsend = '\0';
583
584       /* We have to remove the PASTE_LEFT flag from the old lhs, but
585          we want to keep the new location.  */
586       *lhs = **plhs;
587       *plhs = lhs;
588       lhs->src_loc = saved_loc;
589       lhs->flags &= ~PASTE_LEFT;
590
591       /* Mandatory error for all apart from assembler.  */
592       if (CPP_OPTION (pfile, lang) != CLK_ASM)
593         cpp_error (pfile, CPP_DL_ERROR,
594          "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
595                    buf, cpp_token_as_text (pfile, rhs));
596       return false;
597     }
598
599   *plhs = lhs;
600   _cpp_pop_buffer (pfile);
601   return true;
602 }
603
604 /* Handles an arbitrarily long sequence of ## operators, with initial
605    operand LHS.  This implementation is left-associative,
606    non-recursive, and finishes a paste before handling succeeding
607    ones.  If a paste fails, we back up to the RHS of the failing ##
608    operator before pushing the context containing the result of prior
609    successful pastes, with the effect that the RHS appears in the
610    output stream after the pasted LHS normally.  */
611 static void
612 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
613 {
614   const cpp_token *rhs = NULL;
615   cpp_context *context = pfile->context;
616
617   do
618     {
619       /* Take the token directly from the current context.  We can do
620          this, because we are in the replacement list of either an
621          object-like macro, or a function-like macro with arguments
622          inserted.  In either case, the constraints to #define
623          guarantee we have at least one more token.  */
624       if (context->tokens_kind == TOKENS_KIND_DIRECT)
625         rhs = FIRST (context).token++;
626       else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
627         rhs = *FIRST (context).ptoken++;
628       else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
629         {
630           /* So we are in presence of an extended token context, which
631              means that each token in this context has a virtual
632              location attached to it.  So let's not forget to update
633              the pointer to the current virtual location of the
634              current token when we update the pointer to the current
635              token */
636
637           rhs = *FIRST (context).ptoken++;
638           /* context->c.mc must be non-null, as if we were not in a
639              macro context, context->tokens_kind could not be equal to
640              TOKENS_KIND_EXTENDED.  */
641           context->c.mc->cur_virt_loc++;
642         }
643
644       if (rhs->type == CPP_PADDING)
645         {
646           if (rhs->flags & PASTE_LEFT)
647             abort ();
648         }
649       if (!paste_tokens (pfile, &lhs, rhs))
650         break;
651     }
652   while (rhs->flags & PASTE_LEFT);
653
654   /* Put the resulting token in its own context.  */
655   _cpp_push_token_context (pfile, NULL, lhs, 1);
656 }
657
658 /* Returns TRUE if the number of arguments ARGC supplied in an
659    invocation of the MACRO referenced by NODE is valid.  An empty
660    invocation to a macro with no parameters should pass ARGC as zero.
661
662    Note that MACRO cannot necessarily be deduced from NODE, in case
663    NODE was redefined whilst collecting arguments.  */
664 bool
665 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
666 {
667   if (argc == macro->paramc)
668     return true;
669
670   if (argc < macro->paramc)
671     {
672       /* As an extension, a rest argument is allowed to not appear in
673          the invocation at all.
674          e.g. #define debug(format, args...) something
675          debug("string");
676
677          This is exactly the same as if there had been an empty rest
678          argument - debug("string", ).  */
679
680       if (argc + 1 == macro->paramc && macro->variadic)
681         {
682           if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
683             cpp_error (pfile, CPP_DL_PEDWARN,
684                        "ISO C99 requires rest arguments to be used");
685           return true;
686         }
687
688       cpp_error (pfile, CPP_DL_ERROR,
689                  "macro \"%s\" requires %u arguments, but only %u given",
690                  NODE_NAME (node), macro->paramc, argc);
691     }
692   else
693     cpp_error (pfile, CPP_DL_ERROR,
694                "macro \"%s\" passed %u arguments, but takes just %u",
695                NODE_NAME (node), argc, macro->paramc);
696
697   return false;
698 }
699
700 /* Reads and returns the arguments to a function-like macro
701    invocation.  Assumes the opening parenthesis has been processed.
702    If there is an error, emits an appropriate diagnostic and returns
703    NULL.  Each argument is terminated by a CPP_EOF token, for the
704    future benefit of expand_arg().  If there are any deferred
705    #pragma directives among macro arguments, store pointers to the
706    CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
707
708    What is returned is the buffer that contains the memory allocated
709    to hold the macro arguments.  NODE is the name of the macro this
710    function is dealing with.  If NUM_ARGS is non-NULL, *NUM_ARGS is
711    set to the actual number of macro arguments allocated in the
712    returned buffer.  */
713 static _cpp_buff *
714 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
715               _cpp_buff **pragma_buff, unsigned *num_args)
716 {
717   _cpp_buff *buff, *base_buff;
718   cpp_macro *macro;
719   macro_arg *args, *arg;
720   const cpp_token *token;
721   unsigned int argc;
722   source_location virt_loc;
723   bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
724   unsigned num_args_alloced = 0;
725
726   macro = node->value.macro;
727   if (macro->paramc)
728     argc = macro->paramc;
729   else
730     argc = 1;
731
732 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
733 #define ARG_TOKENS_EXTENT 1000
734
735   buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
736                                        * sizeof (cpp_token *)
737                                        + sizeof (macro_arg)));
738   base_buff = buff;
739   args = (macro_arg *) buff->base;
740   memset (args, 0, argc * sizeof (macro_arg));
741   buff->cur = (unsigned char *) &args[argc];
742   arg = args, argc = 0;
743
744   /* Collect the tokens making up each argument.  We don't yet know
745      how many arguments have been supplied, whether too many or too
746      few.  Hence the slightly bizarre usage of "argc" and "arg".  */
747   do
748     {
749       unsigned int paren_depth = 0;
750       unsigned int ntokens = 0;
751       unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
752       num_args_alloced++;
753
754       argc++;
755       arg->first = (const cpp_token **) buff->cur;
756       if (track_macro_expansion_p)
757         {
758           virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
759           arg->virt_locs = XNEWVEC (source_location,
760                                     virt_locs_capacity);
761         }
762
763       for (;;)
764         {
765           /* Require space for 2 new tokens (including a CPP_EOF).  */
766           if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
767             {
768               buff = _cpp_append_extend_buff (pfile, buff,
769                                               ARG_TOKENS_EXTENT
770                                               * sizeof (cpp_token *));
771               arg->first = (const cpp_token **) buff->cur;
772             }
773           if (track_macro_expansion_p
774               && (ntokens + 2 > virt_locs_capacity))
775             {
776               virt_locs_capacity += ARG_TOKENS_EXTENT;
777               arg->virt_locs = XRESIZEVEC (source_location,
778                                            arg->virt_locs,
779                                            virt_locs_capacity);
780             }
781
782           token = cpp_get_token_1 (pfile, &virt_loc);
783
784           if (token->type == CPP_PADDING)
785             {
786               /* Drop leading padding.  */
787               if (ntokens == 0)
788                 continue;
789             }
790           else if (token->type == CPP_OPEN_PAREN)
791             paren_depth++;
792           else if (token->type == CPP_CLOSE_PAREN)
793             {
794               if (paren_depth-- == 0)
795                 break;
796             }
797           else if (token->type == CPP_COMMA)
798             {
799               /* A comma does not terminate an argument within
800                  parentheses or as part of a variable argument.  */
801               if (paren_depth == 0
802                   && ! (macro->variadic && argc == macro->paramc))
803                 break;
804             }
805           else if (token->type == CPP_EOF
806                    || (token->type == CPP_HASH && token->flags & BOL))
807             break;
808           else if (token->type == CPP_PRAGMA)
809             {
810               cpp_token *newtok = _cpp_temp_token (pfile);
811
812               /* CPP_PRAGMA token lives in directive_result, which will
813                  be overwritten on the next directive.  */
814               *newtok = *token;
815               token = newtok;
816               do
817                 {
818                   if (*pragma_buff == NULL
819                       || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
820                     {
821                       _cpp_buff *next;
822                       if (*pragma_buff == NULL)
823                         *pragma_buff
824                           = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
825                       else
826                         {
827                           next = *pragma_buff;
828                           *pragma_buff
829                             = _cpp_get_buff (pfile,
830                                              (BUFF_FRONT (*pragma_buff)
831                                               - (*pragma_buff)->base) * 2);
832                           (*pragma_buff)->next = next;
833                         }
834                     }
835                   *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
836                   BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
837                   if (token->type == CPP_PRAGMA_EOL)
838                     break;
839                   token = cpp_get_token_1 (pfile, &virt_loc);
840                 }
841               while (token->type != CPP_EOF);
842
843               /* In deferred pragmas parsing_args and prevent_expansion
844                  had been changed, reset it.  */
845               pfile->state.parsing_args = 2;
846               pfile->state.prevent_expansion = 1;
847
848               if (token->type == CPP_EOF)
849                 break;
850               else
851                 continue;
852             }
853           set_arg_token (arg, token, virt_loc,
854                          ntokens, MACRO_ARG_TOKEN_NORMAL,
855                          CPP_OPTION (pfile, track_macro_expansion));
856           ntokens++;
857         }
858
859       /* Drop trailing padding.  */
860       while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
861         ntokens--;
862
863       arg->count = ntokens;
864       set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
865                      ntokens, MACRO_ARG_TOKEN_NORMAL,
866                      CPP_OPTION (pfile, track_macro_expansion));
867
868       /* Terminate the argument.  Excess arguments loop back and
869          overwrite the final legitimate argument, before failing.  */
870       if (argc <= macro->paramc)
871         {
872           buff->cur = (unsigned char *) &arg->first[ntokens + 1];
873           if (argc != macro->paramc)
874             arg++;
875         }
876     }
877   while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
878
879   if (token->type == CPP_EOF)
880     {
881       /* We still need the CPP_EOF to end directives, and to end
882          pre-expansion of a macro argument.  Step back is not
883          unconditional, since we don't want to return a CPP_EOF to our
884          callers at the end of an -include-d file.  */
885       if (pfile->context->prev || pfile->state.in_directive)
886         _cpp_backup_tokens (pfile, 1);
887       cpp_error (pfile, CPP_DL_ERROR,
888                  "unterminated argument list invoking macro \"%s\"",
889                  NODE_NAME (node));
890     }
891   else
892     {
893       /* A single empty argument is counted as no argument.  */
894       if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
895         argc = 0;
896       if (_cpp_arguments_ok (pfile, macro, node, argc))
897         {
898           /* GCC has special semantics for , ## b where b is a varargs
899              parameter: we remove the comma if b was omitted entirely.
900              If b was merely an empty argument, the comma is retained.
901              If the macro takes just one (varargs) parameter, then we
902              retain the comma only if we are standards conforming.
903
904              If FIRST is NULL replace_args () swallows the comma.  */
905           if (macro->variadic && (argc < macro->paramc
906                                   || (argc == 1 && args[0].count == 0
907                                       && !CPP_OPTION (pfile, std))))
908             args[macro->paramc - 1].first = NULL;
909           if (num_args)
910             *num_args = num_args_alloced;
911           return base_buff;
912         }
913     }
914
915   /* An error occurred.  */
916   _cpp_release_buff (pfile, base_buff);
917   return NULL;
918 }
919
920 /* Search for an opening parenthesis to the macro of NODE, in such a
921    way that, if none is found, we don't lose the information in any
922    intervening padding tokens.  If we find the parenthesis, collect
923    the arguments and return the buffer containing them.  PRAGMA_BUFF
924    argument is the same as in collect_args.  If NUM_ARGS is non-NULL,
925    *NUM_ARGS is set to the number of arguments contained in the
926    returned buffer.  */
927 static _cpp_buff *
928 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
929                       _cpp_buff **pragma_buff, unsigned *num_args)
930 {
931   const cpp_token *token, *padding = NULL;
932
933   for (;;)
934     {
935       token = cpp_get_token (pfile);
936       if (token->type != CPP_PADDING)
937         break;
938       if (padding == NULL
939           || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
940         padding = token;
941     }
942
943   if (token->type == CPP_OPEN_PAREN)
944     {
945       pfile->state.parsing_args = 2;
946       return collect_args (pfile, node, pragma_buff, num_args);
947     }
948
949   /* CPP_EOF can be the end of macro arguments, or the end of the
950      file.  We mustn't back up over the latter.  Ugh.  */
951   if (token->type != CPP_EOF || token == &pfile->eof)
952     {
953       /* Back up.  We may have skipped padding, in which case backing
954          up more than one token when expanding macros is in general
955          too difficult.  We re-insert it in its own context.  */
956       _cpp_backup_tokens (pfile, 1);
957       if (padding)
958         _cpp_push_token_context (pfile, NULL, padding, 1);
959     }
960
961   return NULL;
962 }
963
964 /* Return the real number of tokens in the expansion of MACRO.  */
965 static inline unsigned int
966 macro_real_token_count (const cpp_macro *macro)
967 {
968   unsigned int i;
969   if (__builtin_expect (!macro->extra_tokens, true))
970     return macro->count;
971   for (i = 0; i < macro->count; i++)
972     if (macro->exp.tokens[i].type == CPP_PASTE)
973       return i;
974   abort ();
975 }
976
977 /* Push the context of a macro with hash entry NODE onto the context
978    stack.  If we can successfully expand the macro, we push a context
979    containing its yet-to-be-rescanned replacement list and return one.
980    If there were additionally any unexpanded deferred #pragma
981    directives among macro arguments, push another context containing
982    the pragma tokens before the yet-to-be-rescanned replacement list
983    and return two.  Otherwise, we don't push a context and return
984    zero. LOCATION is the location of the expansion point of the
985    macro.  */
986 static int
987 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
988                      const cpp_token *result, source_location location)
989 {
990   /* The presence of a macro invalidates a file's controlling macro.  */
991   pfile->mi_valid = false;
992
993   pfile->state.angled_headers = false;
994
995   if ((node->flags & NODE_BUILTIN) && !(node->flags & NODE_USED))
996     {
997       node->flags |= NODE_USED;
998       if ((!pfile->cb.user_builtin_macro
999            || !pfile->cb.user_builtin_macro (pfile, node))
1000           && pfile->cb.used_define)
1001         pfile->cb.used_define (pfile, pfile->directive_line, node);
1002     }
1003
1004   /* Handle standard macros.  */
1005   if (! (node->flags & NODE_BUILTIN))
1006     {
1007       cpp_macro *macro = node->value.macro;
1008       _cpp_buff *pragma_buff = NULL;
1009
1010       if (macro->fun_like)
1011         {
1012           _cpp_buff *buff;
1013           unsigned num_args = 0;
1014
1015           pfile->state.prevent_expansion++;
1016           pfile->keep_tokens++;
1017           pfile->state.parsing_args = 1;
1018           buff = funlike_invocation_p (pfile, node, &pragma_buff,
1019                                        &num_args);
1020           pfile->state.parsing_args = 0;
1021           pfile->keep_tokens--;
1022           pfile->state.prevent_expansion--;
1023
1024           if (buff == NULL)
1025             {
1026               if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1027                 cpp_warning (pfile, CPP_W_TRADITIONAL,
1028  "function-like macro \"%s\" must be used with arguments in traditional C",
1029                              NODE_NAME (node));
1030
1031               if (pragma_buff)
1032                 _cpp_release_buff (pfile, pragma_buff);
1033
1034               return 0;
1035             }
1036
1037           if (macro->paramc > 0)
1038             replace_args (pfile, node, macro,
1039                           (macro_arg *) buff->base,
1040                           location);
1041           /* Free the memory used by the arguments of this
1042              function-like macro.  This memory has been allocated by
1043              funlike_invocation_p and by replace_args.  */
1044           delete_macro_args (buff, num_args);
1045         }
1046
1047       /* Disable the macro within its expansion.  */
1048       node->flags |= NODE_DISABLED;
1049
1050       if (!(node->flags & NODE_USED))
1051         {
1052           node->flags |= NODE_USED;
1053           if (pfile->cb.used_define)
1054             pfile->cb.used_define (pfile, pfile->directive_line, node);
1055         }
1056
1057       if (pfile->cb.used)
1058         pfile->cb.used (pfile, location, node);
1059
1060       macro->used = 1;
1061
1062       if (macro->paramc == 0)
1063         {
1064           if (CPP_OPTION (pfile, track_macro_expansion))
1065             {
1066               unsigned int i, count = macro->count;
1067               const cpp_token *src = macro->exp.tokens;
1068               const struct line_map *map;
1069               source_location *virt_locs = NULL;
1070               _cpp_buff *macro_tokens =
1071                 tokens_buff_new (pfile, count, &virt_locs);
1072
1073               /* Create a macro map to record the locations of the
1074                  tokens that are involved in the expansion. LOCATION
1075                  is the location of the macro expansion point.  */
1076               map  = linemap_enter_macro (pfile->line_table,
1077                                           node, location, count);
1078               for (i = 0; i < count; ++i)
1079                 {
1080                   tokens_buff_add_token (macro_tokens, virt_locs,
1081                                          src, src->src_loc,
1082                                          src->src_loc, map, i);
1083                   ++src;
1084                 }
1085               push_extended_tokens_context (pfile, node,
1086                                             macro_tokens,
1087                                             virt_locs,
1088                                             (const cpp_token **)
1089                                             macro_tokens->base,
1090                                             count);
1091               num_macro_tokens_counter += count;
1092             }
1093           else
1094             {
1095               unsigned tokens_count = macro_real_token_count (macro);
1096               _cpp_push_token_context (pfile, node, macro->exp.tokens,
1097                                        tokens_count);
1098               num_macro_tokens_counter += tokens_count;
1099             }
1100         }
1101
1102       if (pragma_buff)
1103         {
1104           if (!pfile->state.in_directive)
1105             _cpp_push_token_context (pfile, NULL,
1106                                      padding_token (pfile, result), 1);
1107           do
1108             {
1109               unsigned tokens_count;
1110               _cpp_buff *tail = pragma_buff->next;
1111               pragma_buff->next = NULL;
1112               tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1113                               - (const cpp_token **) pragma_buff->base);
1114               push_ptoken_context (pfile, NULL, pragma_buff,
1115                                    (const cpp_token **) pragma_buff->base,
1116                                    tokens_count);
1117               pragma_buff = tail;
1118               if (!CPP_OPTION (pfile, track_macro_expansion))
1119                 num_macro_tokens_counter += tokens_count;
1120
1121             }
1122           while (pragma_buff != NULL);
1123           return 2;
1124         }
1125
1126       return 1;
1127     }
1128
1129   /* Handle built-in macros and the _Pragma operator.  */
1130   return builtin_macro (pfile, node);
1131 }
1132
1133 /* De-allocate the memory used by BUFF which is an array of instances
1134    of macro_arg.  NUM_ARGS is the number of instances of macro_arg
1135    present in BUFF.  */
1136 static void
1137 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1138 {
1139   macro_arg *macro_args;
1140   unsigned i;
1141
1142   if (buff == NULL)
1143     return;
1144
1145   macro_args = (macro_arg *) buff->base;
1146
1147   /* Walk instances of macro_arg to free their expanded tokens as well
1148      as their macro_arg::virt_locs members.  */
1149   for (i = 0; i < num_args; ++i)
1150     {
1151       if (macro_args[i].expanded)
1152         {
1153           free (macro_args[i].expanded);
1154           macro_args[i].expanded = NULL;
1155         }
1156       if (macro_args[i].virt_locs)
1157         {
1158           free (macro_args[i].virt_locs);
1159           macro_args[i].virt_locs = NULL;
1160         }
1161       if (macro_args[i].expanded_virt_locs)
1162         {
1163           free (macro_args[i].expanded_virt_locs);
1164           macro_args[i].expanded_virt_locs = NULL;
1165         }
1166     }
1167   _cpp_free_buff (buff);
1168 }
1169
1170 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1171    to set, LOCATION is its virtual location.  "Virtual" location means
1172    the location that encodes loci accross macro expansion. Otherwise
1173    it has to be TOKEN->SRC_LOC.  KIND is the kind of tokens the
1174    argument ARG is supposed to contain.  Note that ARG must be
1175    tailored so that it has enough room to contain INDEX + 1 numbers of
1176    tokens, at least.  */
1177 static void
1178 set_arg_token (macro_arg *arg, const cpp_token *token,
1179                source_location location, size_t index,
1180                enum macro_arg_token_kind kind,
1181                bool track_macro_exp_p)
1182 {
1183   const cpp_token **token_ptr;
1184   source_location *loc = NULL;
1185
1186   token_ptr =
1187     arg_token_ptr_at (arg, index, kind,
1188                       track_macro_exp_p ? &loc : NULL);
1189   *token_ptr = token;
1190
1191   if (loc != NULL)
1192     {
1193 #ifdef ENABLE_CHECKING
1194       if (kind == MACRO_ARG_TOKEN_STRINGIFIED
1195           || !track_macro_exp_p)
1196         /* We can't set the location of a stringified argument
1197            token and we can't set any location if we aren't tracking
1198            macro expansion locations.   */
1199         abort ();
1200 #endif
1201       *loc = location;
1202     }
1203 }
1204
1205 /* Get the pointer to the location of the argument token of the
1206    function-like macro argument ARG.  This function must be called
1207    only when we -ftrack-macro-expansion is on.  */
1208 static const source_location *
1209 get_arg_token_location (const macro_arg *arg,
1210                         enum macro_arg_token_kind kind)
1211 {
1212   const source_location *loc = NULL;
1213   const cpp_token **token_ptr =
1214     arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1215
1216   if (token_ptr == NULL)
1217     return NULL;
1218
1219   return loc;
1220 }
1221
1222 /* Return the pointer to the INDEXth token of the macro argument ARG.
1223    KIND specifies the kind of token the macro argument ARG contains.
1224    If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1225    of the virtual location of the returned token if the
1226    -ftrack-macro-expansion flag is on; otherwise, it's set to the
1227    spelling location of the returned token.  */
1228 static const cpp_token **
1229 arg_token_ptr_at (const macro_arg *arg, size_t index,
1230                   enum macro_arg_token_kind kind,
1231                   source_location **virt_location)
1232 {
1233   const cpp_token **tokens_ptr = NULL;
1234
1235   switch (kind)
1236     {
1237     case MACRO_ARG_TOKEN_NORMAL:
1238       tokens_ptr = arg->first;
1239       break;
1240     case MACRO_ARG_TOKEN_STRINGIFIED:      
1241       tokens_ptr = (const cpp_token **) &arg->stringified;
1242       break;
1243     case MACRO_ARG_TOKEN_EXPANDED:
1244         tokens_ptr = arg->expanded;
1245       break;
1246     }
1247
1248   if (tokens_ptr == NULL)
1249     /* This can happen for e.g, an empty token argument to a
1250        funtion-like macro.  */
1251     return tokens_ptr;
1252
1253   if (virt_location)
1254     {
1255       if (kind == MACRO_ARG_TOKEN_NORMAL)
1256         *virt_location = &arg->virt_locs[index];
1257       else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1258         *virt_location = &arg->expanded_virt_locs[index];
1259       else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1260         *virt_location =
1261           (source_location *) &tokens_ptr[index]->src_loc;
1262     }
1263   return &tokens_ptr[index];
1264 }
1265
1266 /* Initialize an iterator so that it iterates over the tokens of a
1267    function-like macro argument.  KIND is the kind of tokens we want
1268    ITER to iterate over. TOKEN_PTR points the first token ITER will
1269    iterate over.  */
1270 static void
1271 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1272                            bool track_macro_exp_p,
1273                            enum macro_arg_token_kind kind,
1274                            const macro_arg *arg,
1275                            const cpp_token **token_ptr)
1276 {
1277   iter->track_macro_exp_p = track_macro_exp_p;
1278   iter->kind = kind;
1279   iter->token_ptr = token_ptr;
1280   /* Unconditionally initialize this so that the compiler doesn't warn
1281      about iter->location_ptr being possibly uninitialized later after
1282      this code has been inlined somewhere.  */
1283   iter->location_ptr = NULL;
1284   if (track_macro_exp_p)
1285     iter->location_ptr = get_arg_token_location (arg, kind);
1286 #ifdef ENABLE_CHECKING
1287   iter->num_forwards = 0;
1288   if (track_macro_exp_p
1289       && token_ptr != NULL
1290       && iter->location_ptr == NULL)
1291     abort ();
1292 #endif
1293 }
1294
1295 /* Move the iterator one token forward. Note that if IT was
1296    initialized on an argument that has a stringified token, moving it
1297    foward doesn't make sense as a stringified token is essentially one
1298    string.  */
1299 static void
1300 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1301 {
1302   switch (it->kind)
1303     {
1304     case MACRO_ARG_TOKEN_NORMAL:
1305     case MACRO_ARG_TOKEN_EXPANDED:
1306       it->token_ptr++;
1307       if (it->track_macro_exp_p)
1308         it->location_ptr++;
1309       break;
1310     case MACRO_ARG_TOKEN_STRINGIFIED:
1311 #ifdef ENABLE_CHECKING
1312       if (it->num_forwards > 0)
1313         abort ();
1314 #endif
1315       break;
1316     }
1317
1318 #ifdef ENABLE_CHECKING
1319   it->num_forwards++;
1320 #endif
1321 }
1322
1323 /* Return the token pointed to by the iterator.  */
1324 static const cpp_token *
1325 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1326 {
1327 #ifdef ENABLE_CHECKING
1328   if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1329       && it->num_forwards > 0)
1330     abort ();
1331 #endif
1332   if (it->token_ptr == NULL)
1333     return NULL;
1334   return *it->token_ptr;
1335 }
1336
1337 /* Return the location of the token pointed to by the iterator.*/
1338 static source_location
1339 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1340 {
1341 #ifdef ENABLE_CHECKING
1342   if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1343       && it->num_forwards > 0)
1344     abort ();
1345 #endif
1346   if (it->track_macro_exp_p)
1347     return *it->location_ptr;
1348   else
1349     return (*it->token_ptr)->src_loc;
1350 }
1351
1352 /* Return the index of a token [resulting from macro expansion] inside
1353    the total list of tokens resulting from a given macro
1354    expansion. The index can be different depending on whether if we
1355    want each tokens resulting from function-like macro arguments
1356    expansion to have a different location or not.
1357
1358    E.g, consider this function-like macro: 
1359
1360         #define M(x) x - 3
1361
1362    Then consider us "calling" it (and thus expanding it) like:
1363    
1364        M(1+4)
1365
1366    It will be expanded into:
1367
1368        1+4-3
1369
1370    Let's consider the case of the token '4'.
1371
1372    Its index can be 2 (it's the third token of the set of tokens
1373    resulting from the expansion) or it can be 0 if we consider that
1374    all tokens resulting from the expansion of the argument "1+2" have
1375    the same index, which is 0. In this later case, the index of token
1376    '-' would then be 1 and the index of token '3' would be 2.
1377
1378    The later case is useful to use less memory e.g, for the case of
1379    the user using the option -ftrack-macro-expansion=1.
1380
1381    ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1382    are interested in.  CUR_REPLACEMENT_TOKEN is the token of the macro
1383    parameter (inside the macro replacement list) that corresponds to
1384    the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1385    of.
1386
1387    If we refer to the example above, for the '4' argument token,
1388    ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1389    would be set to the token 'x', in the replacement list "x - 3" of
1390    macro M.
1391
1392    This is a subroutine of replace_args.  */
1393 inline static unsigned
1394 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1395                       const cpp_token *cur_replacement_token,
1396                       unsigned absolute_token_index)
1397 {
1398   if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1399     return absolute_token_index;
1400   return cur_replacement_token - macro->exp.tokens;
1401 }
1402
1403 /* Replace the parameters in a function-like macro of NODE with the
1404    actual ARGS, and place the result in a newly pushed token context.
1405    Expand each argument before replacing, unless it is operated upon
1406    by the # or ## operators. EXPANSION_POINT_LOC is the location of
1407    the expansion point of the macro. E.g, the location of the
1408    function-like macro invocation.  */
1409 static void
1410 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1411               macro_arg *args, source_location expansion_point_loc)
1412 {
1413   unsigned int i, total;
1414   const cpp_token *src, *limit;
1415   const cpp_token **first = NULL;
1416   macro_arg *arg;
1417   _cpp_buff *buff = NULL;
1418   source_location *virt_locs = NULL;
1419   unsigned int exp_count;
1420   const struct line_map *map = NULL;
1421   int track_macro_exp;
1422
1423   /* First, fully macro-expand arguments, calculating the number of
1424      tokens in the final expansion as we go.  The ordering of the if
1425      statements below is subtle; we must handle stringification before
1426      pasting.  */
1427
1428   /* EXP_COUNT is the number of tokens in the macro replacement
1429      list.  TOTAL is the number of tokens /after/ macro parameters
1430      have been replaced by their arguments.   */
1431   exp_count = macro_real_token_count (macro);
1432   total = exp_count;
1433   limit = macro->exp.tokens + exp_count;
1434
1435   for (src = macro->exp.tokens; src < limit; src++)
1436     if (src->type == CPP_MACRO_ARG)
1437       {
1438         /* Leading and trailing padding tokens.  */
1439         total += 2;
1440         /* Account for leading and padding tokens in exp_count too.
1441            This is going to be important later down this function,
1442            when we want to handle the case of (track_macro_exp <
1443            2).  */
1444         exp_count += 2;
1445
1446         /* We have an argument.  If it is not being stringified or
1447            pasted it is macro-replaced before insertion.  */
1448         arg = &args[src->val.macro_arg.arg_no - 1];
1449
1450         if (src->flags & STRINGIFY_ARG)
1451           {
1452             if (!arg->stringified)
1453               arg->stringified = stringify_arg (pfile, arg);
1454           }
1455         else if ((src->flags & PASTE_LEFT)
1456                  || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1457           total += arg->count - 1;
1458         else
1459           {
1460             if (!arg->expanded)
1461               expand_arg (pfile, arg);
1462             total += arg->expanded_count - 1;
1463           }
1464       }
1465
1466   /* When the compiler is called with the -ftrack-macro-expansion
1467      flag, we need to keep track of the location of each token that
1468      results from macro expansion.
1469
1470      A token resulting from macro expansion is not a new token. It is
1471      simply the same token as the token coming from the macro
1472      definition.  The new things that are allocated are the buffer
1473      that holds the tokens resulting from macro expansion and a new
1474      location that records many things like the locus of the expansion
1475      point as well as the original locus inside the definition of the
1476      macro.  This location is called a virtual location.
1477      
1478      So the buffer BUFF holds a set of cpp_token*, and the buffer
1479      VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1480
1481      Both of these two buffers are going to be hung off of the macro
1482      context, when the latter is pushed.  The memory allocated to
1483      store the tokens and their locations is going to be freed once
1484      the context of macro expansion is popped.
1485      
1486      As far as tokens are concerned, the memory overhead of
1487      -ftrack-macro-expansion is proportional to the number of
1488      macros that get expanded multiplied by sizeof (source_location).
1489      The good news is that extra memory gets freed when the macro
1490      context is freed, i.e shortly after the macro got expanded.  */
1491
1492   /* Is the -ftrack-macro-expansion flag in effect?  */
1493   track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1494
1495   /* Now allocate memory space for tokens and locations resulting from
1496      the macro expansion, copy the tokens and replace the arguments.
1497      This memory must be freed when the context of the macro MACRO is
1498      popped.  */
1499   buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1500
1501   first = (const cpp_token **) buff->base;
1502
1503   /* Create a macro map to record the locations of the tokens that are
1504      involved in the expansion.  Note that the expansion point is set
1505      to the location of the closing parenthesis.  Otherwise, the
1506      subsequent map created for the first token that comes after the
1507      macro map might have a wrong line number.  That would lead to
1508      tokens with wrong line numbers after the macro expansion.  This
1509      adds up to the memory overhead of the -ftrack-macro-expansion
1510      flag; for every macro that is expanded, a "macro map" is
1511      created.  */
1512   if (track_macro_exp)
1513     {
1514       int num_macro_tokens = total;
1515       if (track_macro_exp < 2)
1516         /* Then the number of macro tokens won't take in account the
1517            fact that function-like macro arguments can expand to
1518            multiple tokens. This is to save memory at the expense of
1519            accuracy.
1520
1521            Suppose we have #define SQARE(A) A * A
1522
1523            And then we do SQARE(2+3)
1524
1525            Then the tokens 2, +, 3, will have the same location,
1526            saying they come from the expansion of the argument A.  */
1527         num_macro_tokens = exp_count;
1528       map = linemap_enter_macro (pfile->line_table, node,
1529                                  expansion_point_loc,
1530                                  num_macro_tokens);
1531     }
1532   i = 0;
1533   for (src = macro->exp.tokens; src < limit; src++)
1534     {
1535       unsigned int arg_tokens_count;
1536       macro_arg_token_iter from;
1537       const cpp_token **paste_flag = NULL;
1538       const cpp_token **tmp_token_ptr;
1539
1540       if (src->type != CPP_MACRO_ARG)
1541         {
1542           /* Allocate a virtual location for token SRC, and add that
1543              token and its virtual location into the buffers BUFF and
1544              VIRT_LOCS.  */
1545           unsigned index = expanded_token_index (pfile, macro, src, i);
1546           tokens_buff_add_token (buff, virt_locs, src,
1547                                  src->src_loc, src->src_loc,
1548                                  map, index);
1549           i += 1;
1550           continue;
1551         }
1552
1553       paste_flag = 0;
1554       arg = &args[src->val.macro_arg.arg_no - 1];
1555       /* SRC is a macro parameter that we need to replace with its
1556          corresponding argument.  So at some point we'll need to
1557          iterate over the tokens of the macro argument and copy them
1558          into the "place" now holding the correspondig macro
1559          parameter.  We are going to use the iterator type
1560          macro_argo_token_iter to handle that iterating.  The 'if'
1561          below is to initialize the iterator depending on the type of
1562          tokens the macro argument has.  It also does some adjustment
1563          related to padding tokens and some pasting corner cases.  */
1564       if (src->flags & STRINGIFY_ARG)
1565         {
1566           arg_tokens_count = 1;
1567           macro_arg_token_iter_init (&from,
1568                                      CPP_OPTION (pfile,
1569                                                  track_macro_expansion),
1570                                      MACRO_ARG_TOKEN_STRINGIFIED,
1571                                      arg, &arg->stringified);
1572         }
1573       else if (src->flags & PASTE_LEFT)
1574         {
1575           arg_tokens_count = arg->count;
1576           macro_arg_token_iter_init (&from,
1577                                      CPP_OPTION (pfile,
1578                                                  track_macro_expansion),
1579                                      MACRO_ARG_TOKEN_NORMAL,
1580                                      arg, arg->first);
1581         }
1582       else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1583         {
1584           int num_toks;
1585           arg_tokens_count = arg->count;
1586           macro_arg_token_iter_init (&from,
1587                                      CPP_OPTION (pfile,
1588                                                  track_macro_expansion),
1589                                      MACRO_ARG_TOKEN_NORMAL,
1590                                      arg, arg->first);
1591
1592           num_toks = tokens_buff_count (buff);
1593
1594           if (num_toks != 0)
1595             {
1596               /* So the current parameter token is pasted to the previous
1597                  token in the replacement list.  Let's look at what
1598                  we have as previous and current arguments.  */
1599
1600               /* This is the previous argument's token ...  */
1601               tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1602
1603               if ((*tmp_token_ptr)->type == CPP_COMMA
1604                   && macro->variadic
1605                   && src->val.macro_arg.arg_no == macro->paramc)
1606                 {
1607                   /* ... which is a comma; and the current parameter
1608                      is the last parameter of a variadic function-like
1609                      macro.  If the argument to the current last
1610                      parameter is NULL, then swallow the comma,
1611                      otherwise drop the paste flag.  */
1612                   if (macro_arg_token_iter_get_token (&from) == NULL)
1613                     tokens_buff_remove_last_token (buff);
1614                   else
1615                     paste_flag = tmp_token_ptr;
1616                 }
1617               /* Remove the paste flag if the RHS is a placemarker.  */
1618               else if (arg_tokens_count == 0)
1619                 paste_flag = tmp_token_ptr;
1620             }
1621         }
1622       else
1623         {
1624           arg_tokens_count = arg->expanded_count;
1625           macro_arg_token_iter_init (&from,
1626                                      CPP_OPTION (pfile,
1627                                                  track_macro_expansion),
1628                                      MACRO_ARG_TOKEN_EXPANDED,
1629                                      arg, arg->expanded);
1630         }
1631
1632       /* Padding on the left of an argument (unless RHS of ##).  */
1633       if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1634           && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1635         {
1636           const cpp_token *t = padding_token (pfile, src);
1637           unsigned index = expanded_token_index (pfile, macro, src, i);
1638           /* Allocate a virtual location for the padding token and
1639              append the token and its location to BUFF and
1640              VIRT_LOCS.   */
1641           tokens_buff_add_token (buff, virt_locs, t,
1642                                  t->src_loc, t->src_loc,
1643                                  map, index);
1644         }
1645
1646       if (arg_tokens_count)
1647         {
1648           /* So now we've got the number of tokens that make up the
1649              argument that is going to replace the current parameter
1650              in the macro's replacement list.  */
1651           unsigned int j;
1652           for (j = 0; j < arg_tokens_count; ++j)
1653             {
1654               /* So if track_macro_exp is < 2, the user wants to
1655                  save extra memory while tracking macro expansion
1656                  locations.  So in that case here is what we do:
1657
1658                  Suppose we have #define SQARE(A) A * A
1659
1660                  And then we do SQARE(2+3)
1661
1662                  Then the tokens 2, +, 3, will have the same location,
1663                  saying they come from the expansion of the argument
1664                  A.
1665
1666               So that means we are going to ignore the COUNT tokens
1667               resulting from the expansion of the current macro
1668               arugment. In other words all the ARG_TOKENS_COUNT tokens
1669               resulting from the expansion of the macro argument will
1670               have the index I. Normally, each of those token should
1671               have index I+J.  */
1672               unsigned token_index = i;
1673               unsigned index;
1674               if (track_macro_exp > 1)
1675                 token_index += j;
1676
1677               index = expanded_token_index (pfile, macro, src, token_index);
1678               tokens_buff_add_token (buff, virt_locs,
1679                                      macro_arg_token_iter_get_token (&from),
1680                                      macro_arg_token_iter_get_location (&from),
1681                                      src->src_loc, map, index);
1682               macro_arg_token_iter_forward (&from);
1683             }
1684
1685           /* With a non-empty argument on the LHS of ##, the last
1686              token should be flagged PASTE_LEFT.  */
1687           if (src->flags & PASTE_LEFT)
1688             paste_flag =
1689               (const cpp_token **) tokens_buff_last_token_ptr (buff);
1690         }
1691       else if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1692                && ! CPP_OPTION (pfile, c99)
1693                && ! cpp_in_system_header (pfile))
1694         {
1695           cpp_error (pfile, CPP_DL_PEDWARN,
1696                      "invoking macro %s argument %d: "
1697                      "empty macro arguments are undefined"
1698                      " in ISO C90 and ISO C++98",
1699                      NODE_NAME (node),
1700                      src->val.macro_arg.arg_no);
1701         }
1702
1703       /* Avoid paste on RHS (even case count == 0).  */
1704       if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
1705         {
1706           const cpp_token *t = &pfile->avoid_paste;
1707           tokens_buff_add_token (buff, virt_locs,
1708                                  t, t->src_loc, t->src_loc,
1709                                  NULL, 0);
1710         }
1711
1712       /* Add a new paste flag, or remove an unwanted one.  */
1713       if (paste_flag)
1714         {
1715           cpp_token *token = _cpp_temp_token (pfile);
1716           token->type = (*paste_flag)->type;
1717           token->val = (*paste_flag)->val;
1718           if (src->flags & PASTE_LEFT)
1719             token->flags = (*paste_flag)->flags | PASTE_LEFT;
1720           else
1721             token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1722           *paste_flag = token;
1723         }
1724
1725       i += arg_tokens_count;
1726     }
1727
1728   if (track_macro_exp)
1729     push_extended_tokens_context (pfile, node, buff, virt_locs, first,
1730                                   tokens_buff_count (buff));
1731   else
1732     push_ptoken_context (pfile, node, buff, first,
1733                          tokens_buff_count (buff));
1734
1735   num_macro_tokens_counter += tokens_buff_count (buff);
1736 }
1737
1738 /* Return a special padding token, with padding inherited from SOURCE.  */
1739 static const cpp_token *
1740 padding_token (cpp_reader *pfile, const cpp_token *source)
1741 {
1742   cpp_token *result = _cpp_temp_token (pfile);
1743
1744   result->type = CPP_PADDING;
1745
1746   /* Data in GCed data structures cannot be made const so far, so we
1747      need a cast here.  */
1748   result->val.source = (cpp_token *) source;
1749   result->flags = 0;
1750   return result;
1751 }
1752
1753 /* Get a new uninitialized context.  Create a new one if we cannot
1754    re-use an old one.  */
1755 static cpp_context *
1756 next_context (cpp_reader *pfile)
1757 {
1758   cpp_context *result = pfile->context->next;
1759
1760   if (result == 0)
1761     {
1762       result = XNEW (cpp_context);
1763       memset (result, 0, sizeof (cpp_context));
1764       result->prev = pfile->context;
1765       result->next = 0;
1766       pfile->context->next = result;
1767     }
1768
1769   pfile->context = result;
1770   return result;
1771 }
1772
1773 /* Push a list of pointers to tokens.  */
1774 static void
1775 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
1776                      const cpp_token **first, unsigned int count)
1777 {
1778   cpp_context *context = next_context (pfile);
1779
1780   context->tokens_kind = TOKENS_KIND_INDIRECT;
1781   context->c.macro = macro;
1782   context->buff = buff;
1783   FIRST (context).ptoken = first;
1784   LAST (context).ptoken = first + count;
1785 }
1786
1787 /* Push a list of tokens.  */
1788 void
1789 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
1790                          const cpp_token *first, unsigned int count)
1791 {
1792    cpp_context *context = next_context (pfile);
1793  
1794    context->tokens_kind = TOKENS_KIND_DIRECT;
1795    context->c.macro = macro;
1796    context->buff = NULL;
1797   FIRST (context).token = first;
1798   LAST (context).token = first + count;
1799 }
1800
1801 /* Build a context containing a list of tokens as well as their
1802    virtual locations and push it.  TOKENS_BUFF is the buffer that
1803    contains the tokens pointed to by FIRST.  If TOKENS_BUFF is
1804    non-NULL, it means that the context owns it, meaning that
1805    _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
1806    contains the virtual locations.  */
1807 static void
1808 push_extended_tokens_context (cpp_reader *pfile,
1809                               cpp_hashnode *macro,
1810                               _cpp_buff *token_buff,
1811                               source_location *virt_locs,
1812                               const cpp_token **first,
1813                               unsigned int count)
1814 {
1815   cpp_context *context = next_context (pfile);
1816   macro_context *m;
1817
1818   context->tokens_kind = TOKENS_KIND_EXTENDED;
1819   context->buff = token_buff;
1820
1821   m = XNEW (macro_context);
1822   m->macro_node = macro;
1823   m->virt_locs = virt_locs;
1824   m->cur_virt_loc = virt_locs;
1825   context->c.mc = m;
1826   FIRST (context).ptoken = first;
1827   LAST (context).ptoken = first + count;
1828 }
1829
1830 /* Push a traditional macro's replacement text.  */
1831 void
1832 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
1833                         const uchar *start, size_t len)
1834 {
1835   cpp_context *context = next_context (pfile);
1836
1837   context->tokens_kind = TOKENS_KIND_DIRECT;
1838   context->c.macro = macro;
1839   context->buff = NULL;
1840   CUR (context) = start;
1841   RLIMIT (context) = start + len;
1842   macro->flags |= NODE_DISABLED;
1843 }
1844
1845 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
1846    for the purpose of storing them on a cpp_context. If VIRT_LOCS is
1847    non-null (which means that -ftrack-macro-expansion is on),
1848    *VIRT_LOCS is set to a newly allocated buffer that is supposed to
1849    hold the virtual locations of the tokens resulting from macro
1850    expansion.  */
1851 static _cpp_buff*
1852 tokens_buff_new (cpp_reader *pfile, size_t len,
1853                  source_location **virt_locs)
1854 {
1855   size_t tokens_size = len * sizeof (cpp_token *);
1856   size_t locs_size = len * sizeof (source_location);
1857
1858   if (virt_locs != NULL)
1859     *virt_locs = XNEWVEC (source_location, locs_size);
1860   return _cpp_get_buff (pfile, tokens_size);
1861 }
1862
1863 /* Returns the number of tokens contained in a token buffer.  The
1864    buffer holds a set of cpp_token*.  */
1865 static size_t
1866 tokens_buff_count (_cpp_buff *buff)
1867 {
1868   return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
1869 }
1870
1871 /* Return a pointer to the last token contained in the token buffer
1872    BUFF.  */
1873 static const cpp_token **
1874 tokens_buff_last_token_ptr (_cpp_buff *buff)
1875 {
1876   return &((const cpp_token **) BUFF_FRONT (buff))[-1];
1877 }
1878
1879 /* Remove the last token contained in the token buffer TOKENS_BUFF.
1880    If VIRT_LOCS_BUFF is non-NULL,  it should point at the buffer
1881    containing the virtual locations of the tokens in TOKENS_BUFF; in
1882    which case the function updates that buffer as well.   */
1883 static inline void
1884 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
1885
1886 {
1887   if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
1888     BUFF_FRONT (tokens_buff) =
1889       (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
1890 }
1891
1892 /* Insert a token into the token buffer at the position pointed to by
1893    DEST.  Note that the buffer is not enlarged so the previous token
1894    that was at *DEST is overwritten.  VIRT_LOC_DEST, if non-null,
1895    means -ftrack-macro-expansion is effect; it then points to where to
1896    insert the virtual location of TOKEN.  TOKEN is the token to
1897    insert.  VIRT_LOC is the virtual location of the token, i.e, the
1898    location possibly encoding its locus accross macro expansion.  If
1899    TOKEN is an argument of a function-like macro (inside a macro
1900    replacement list), PARM_DEF_LOC is the spelling location of the
1901    macro parameter that TOKEN is replacing, in the replacement list of
1902    the macro.  If TOKEN is not an argument of a function-like macro or
1903    if it doesn't come from a macro expansion, then VIRT_LOC can just
1904    be set to the same value as PARM_DEF_LOC.  If MAP is non null, it
1905    means TOKEN comes from a macro expansion and MAP is the macro map
1906    associated to the macro.  MACRO_TOKEN_INDEX points to the index of
1907    the token in the macro map; it is not considered if MAP is NULL.
1908
1909    Upon successful completion this function returns the a pointer to
1910    the position of the token coming right after the insertion
1911    point.  */
1912 static inline const cpp_token **
1913 tokens_buff_put_token_to (const cpp_token **dest,
1914                           source_location *virt_loc_dest,
1915                           const cpp_token *token,
1916                           source_location virt_loc,
1917                           source_location parm_def_loc,                   
1918                           const struct line_map *map,
1919                           unsigned int macro_token_index)
1920 {
1921   source_location macro_loc = virt_loc;
1922   const cpp_token **result;
1923
1924   if (virt_loc_dest)
1925     {
1926       /* -ftrack-macro-expansion is on.  */
1927       if (map)
1928         macro_loc = linemap_add_macro_token (map, macro_token_index,
1929                                              virt_loc, parm_def_loc);
1930       *virt_loc_dest = macro_loc;
1931     }
1932   *dest = token;
1933   result = &dest[1];
1934
1935   return result;
1936 }
1937
1938 /* Adds a token at the end of the tokens contained in BUFFER.  Note
1939    that this function doesn't enlarge BUFFER when the number of tokens
1940    reaches BUFFER's size; it aborts in that situation.
1941
1942    TOKEN is the token to append. VIRT_LOC is the virtual location of
1943    the token, i.e, the location possibly encoding its locus accross
1944    macro expansion. If TOKEN is an argument of a function-like macro
1945    (inside a macro replacement list), PARM_DEF_LOC is the location of
1946    the macro parameter that TOKEN is replacing.  If TOKEN doesn't come
1947    from a macro expansion, then VIRT_LOC can just be set to the same
1948    value as PARM_DEF_LOC.  If MAP is non null, it means TOKEN comes
1949    from a macro expansion and MAP is the macro map associated to the
1950    macro.  MACRO_TOKEN_INDEX points to the index of the token in the
1951    macro map; It is not considered if MAP is NULL.  If VIRT_LOCS is
1952    non-null, it means -ftrack-macro-expansion is on; in which case
1953    this function adds the virtual location DEF_LOC to the VIRT_LOCS
1954    array, at the same index as the one of TOKEN in BUFFER.  Upon
1955    successful completion this function returns the a pointer to the
1956    position of the token coming right after the insertion point.  */
1957 static const cpp_token **
1958 tokens_buff_add_token (_cpp_buff *buffer,
1959                        source_location *virt_locs,
1960                        const cpp_token *token,
1961                        source_location virt_loc,
1962                        source_location parm_def_loc,
1963                        const struct line_map *map,
1964                        unsigned int macro_token_index)
1965 {
1966   const cpp_token **result;
1967   source_location *virt_loc_dest = NULL;
1968   unsigned token_index = 
1969     (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
1970
1971   /* Abort if we pass the end the buffer.  */
1972   if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
1973     abort ();
1974
1975   if (virt_locs != NULL)
1976     virt_loc_dest = &virt_locs[token_index];
1977
1978   result =
1979     tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
1980                               virt_loc_dest, token, virt_loc, parm_def_loc,
1981                               map, macro_token_index);
1982
1983   BUFF_FRONT (buffer) = (unsigned char *) result;
1984   return result;
1985 }
1986
1987 /* Allocate space for the function-like macro argument ARG to store
1988    the tokens resulting from the macro-expansion of the tokens that
1989    make up ARG itself. That space is allocated in ARG->expanded and
1990    needs to be freed using free.  */
1991 static void
1992 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
1993 {
1994 #ifdef ENABLE_CHECKING
1995   if (arg->expanded != NULL
1996       || arg->expanded_virt_locs != NULL)
1997     abort ();
1998 #endif
1999   arg->expanded = XNEWVEC (const cpp_token *, capacity);
2000   if (CPP_OPTION (pfile, track_macro_expansion))
2001     arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2002
2003 }
2004
2005 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2006    tokens.  */
2007 static void
2008 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2009                           size_t size, size_t *expanded_capacity)
2010 {
2011   if (size <= *expanded_capacity)
2012     return;
2013
2014   size *= 2;
2015
2016   arg->expanded =
2017     XRESIZEVEC (const cpp_token *, arg->expanded, size);
2018   *expanded_capacity = size;
2019
2020   if (CPP_OPTION (pfile, track_macro_expansion))
2021     {
2022       if (arg->expanded_virt_locs == NULL)
2023         arg->expanded_virt_locs = XNEWVEC (source_location, size);
2024       else
2025         arg->expanded_virt_locs = XRESIZEVEC (source_location,
2026                                               arg->expanded_virt_locs,
2027                                               size);
2028     }
2029 }
2030
2031 /* Expand an argument ARG before replacing parameters in a
2032    function-like macro.  This works by pushing a context with the
2033    argument's tokens, and then expanding that into a temporary buffer
2034    as if it were a normal part of the token stream.  collect_args()
2035    has terminated the argument's tokens with a CPP_EOF so that we know
2036    when we have fully expanded the argument.  */
2037 static void
2038 expand_arg (cpp_reader *pfile, macro_arg *arg)
2039 {
2040   size_t capacity;
2041   bool saved_warn_trad;
2042   bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2043
2044   if (arg->count == 0
2045       || arg->expanded != NULL)
2046     return;
2047
2048   /* Don't warn about funlike macros when pre-expanding.  */
2049   saved_warn_trad = CPP_WTRADITIONAL (pfile);
2050   CPP_WTRADITIONAL (pfile) = 0;
2051
2052   /* Loop, reading in the tokens of the argument.  */
2053   capacity = 256;
2054   alloc_expanded_arg_mem (pfile, arg, capacity);
2055
2056   if (track_macro_exp_p)
2057     push_extended_tokens_context (pfile, NULL, NULL,
2058                                   arg->virt_locs,
2059                                   arg->first,
2060                                   arg->count + 1);
2061   else
2062     push_ptoken_context (pfile, NULL, NULL,
2063                          arg->first, arg->count + 1);
2064
2065   for (;;)
2066     {
2067       const cpp_token *token;
2068       source_location location;
2069
2070       ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2071                                 &capacity);
2072
2073       token = cpp_get_token_1 (pfile, &location);
2074
2075       if (token->type == CPP_EOF)
2076         break;
2077
2078       set_arg_token (arg, token, location,
2079                      arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2080                      CPP_OPTION (pfile, track_macro_expansion));
2081       arg->expanded_count++;
2082     }
2083
2084   _cpp_pop_context (pfile);
2085
2086   CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2087 }
2088
2089 /* Pop the current context off the stack, re-enabling the macro if the
2090    context represented a macro's replacement list.  Initially the
2091    context structure was not freed so that we can re-use it later, but
2092    now we do free it to reduce peak memory consumption.  */
2093 void
2094 _cpp_pop_context (cpp_reader *pfile)
2095 {
2096   cpp_context *context = pfile->context;
2097
2098   if (context->c.macro)
2099     {
2100       cpp_hashnode *macro;
2101       if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2102         {
2103           macro_context *mc = context->c.mc;
2104           macro = mc->macro_node;
2105           /* If context->buff is set, it means the life time of tokens
2106              is bound to the life time of this context; so we must
2107              free the tokens; that means we must free the virtual
2108              locations of these tokens too.  */
2109           if (context->buff && mc->virt_locs)
2110             {
2111               free (mc->virt_locs);
2112               mc->virt_locs = NULL;
2113             }
2114           free (mc);
2115           context->c.mc = NULL;
2116         }
2117       else
2118         macro = context->c.macro;
2119
2120       /* Beware that MACRO can be NULL in cases like when we are
2121          called from expand_arg.  In those cases, a dummy context with
2122          tokens is pushed just for the purpose of walking them using
2123          cpp_get_token_1.  In that case, no 'macro' field is set into
2124          the dummy context.  */
2125       if (macro != NULL)
2126         macro->flags &= ~NODE_DISABLED;
2127     }
2128
2129   if (context->buff)
2130     {
2131       /* Decrease memory peak consumption by freeing the memory used
2132          by the context.  */
2133       _cpp_free_buff (context->buff);
2134     }
2135
2136   pfile->context = context->prev;
2137   /* decrease peak memory consumption by feeing the context.  */
2138   pfile->context->next = NULL;
2139   free (context);
2140 }
2141
2142 /* Return TRUE if we reached the end of the set of tokens stored in
2143    CONTEXT, FALSE otherwise.  */
2144 static inline bool
2145 reached_end_of_context (cpp_context *context)
2146 {
2147   if (context->tokens_kind == TOKENS_KIND_DIRECT)
2148       return FIRST (context).token == LAST (context).token;
2149   else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2150            || context->tokens_kind == TOKENS_KIND_EXTENDED)
2151     return FIRST (context).ptoken == LAST (context).ptoken;
2152   else
2153     abort ();
2154 }
2155
2156 /* Consume the next token contained in the current context of PFILE,
2157    and return it in *TOKEN. It's "full location" is returned in
2158    *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2159    means the location encoding the locus of the token accross macro
2160    expansion; otherwise it's just is the "normal" location of the
2161    token which (*TOKEN)->src_loc.  */
2162 static inline void
2163 consume_next_token_from_context (cpp_reader *pfile,
2164                                  const cpp_token ** token,
2165                                  source_location *location)
2166 {
2167   cpp_context *c = pfile->context;
2168
2169   if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2170     {
2171       *token = FIRST (c).token;
2172       *location = (*token)->src_loc;
2173       FIRST (c).token++;
2174     }
2175   else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)            
2176     {
2177       *token = *FIRST (c).ptoken;
2178       *location = (*token)->src_loc;
2179       FIRST (c).ptoken++;
2180     }
2181   else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2182     {
2183       macro_context *m = c->c.mc;
2184       *token = *FIRST (c).ptoken;
2185       if (m->virt_locs)
2186         {
2187           *location = *m->cur_virt_loc;
2188           m->cur_virt_loc++;
2189         }
2190       else
2191         *location = (*token)->src_loc;
2192       FIRST (c).ptoken++;
2193     }
2194   else
2195     abort ();
2196 }
2197
2198 /* In the traditional mode of the preprocessor, if we are currently in
2199    a directive, the location of a token must be the location of the
2200    start of the directive line.  This function returns the proper
2201    location if we are in the traditional mode, and just returns
2202    LOCATION otherwise.  */
2203
2204 static inline source_location
2205 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2206 {
2207   if (CPP_OPTION (pfile, traditional))
2208     {
2209       if (pfile->state.in_directive)
2210         return pfile->directive_line;
2211     }
2212   return location;
2213 }
2214
2215 /* Routine to get a token as well as its location.
2216
2217    Macro expansions and directives are transparently handled,
2218    including entering included files.  Thus tokens are post-macro
2219    expansion, and after any intervening directives.  External callers
2220    see CPP_EOF only at EOF.  Internal callers also see it when meeting
2221    a directive inside a macro call, when at the end of a directive and
2222    state.in_directive is still 1, and at the end of argument
2223    pre-expansion.
2224
2225    LOC is an out parameter; *LOC is set to the location "as expected
2226    by the user".  Please read the comment of
2227    cpp_get_token_with_location to learn more about the meaning of this
2228    location.  */
2229 static const cpp_token*
2230 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2231 {
2232   const cpp_token *result;
2233   bool can_set = pfile->set_invocation_location;
2234   /* This token is a virtual token that either encodes a location
2235      related to macro expansion or a spelling location.  */
2236   source_location virt_loc = 0;
2237   pfile->set_invocation_location = false;
2238
2239   for (;;)
2240     {
2241       cpp_hashnode *node;
2242       cpp_context *context = pfile->context;
2243
2244       /* Context->prev == 0 <=> base context.  */
2245       if (!context->prev)
2246         {
2247           result = _cpp_lex_token (pfile);
2248           virt_loc = result->src_loc;
2249         }
2250       else if (!reached_end_of_context (context))
2251         {
2252           consume_next_token_from_context (pfile, &result,
2253                                            &virt_loc);
2254           if (result->flags & PASTE_LEFT)
2255             {
2256               paste_all_tokens (pfile, result);
2257               if (pfile->state.in_directive)
2258                 continue;
2259               result = padding_token (pfile, result);
2260               goto out;
2261             }
2262         }
2263       else
2264         {
2265           if (pfile->context->c.macro)
2266             ++num_expanded_macros_counter;
2267           _cpp_pop_context (pfile);
2268           if (pfile->state.in_directive)
2269             continue;
2270           result = &pfile->avoid_paste;
2271           goto out;
2272         }
2273
2274       if (pfile->state.in_directive && result->type == CPP_COMMENT)
2275         continue;
2276
2277       if (result->type != CPP_NAME)
2278         break;
2279
2280       node = result->val.node.node;
2281
2282       if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2283         break;
2284
2285       if (!(node->flags & NODE_DISABLED))
2286         {
2287           int ret = 0;
2288           /* If not in a macro context, and we're going to start an
2289              expansion, record the location.  */
2290           if (can_set && !context->c.macro)
2291             pfile->invocation_location = result->src_loc;
2292           if (pfile->state.prevent_expansion)
2293             break;
2294
2295           /* Conditional macros require that a predicate be evaluated
2296              first.  */
2297           if ((node->flags & NODE_CONDITIONAL) != 0)
2298             {
2299               if (pfile->cb.macro_to_expand)
2300                 {
2301                   bool whitespace_after;
2302                   const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2303
2304                   whitespace_after = (peek_tok->type == CPP_PADDING
2305                                       || (peek_tok->flags & PREV_WHITE));
2306                   node = pfile->cb.macro_to_expand (pfile, result);
2307                   if (node)
2308                     ret = enter_macro_context (pfile, node, result,
2309                                                virt_loc);
2310                   else if (whitespace_after)
2311                     {
2312                       /* If macro_to_expand hook returned NULL and it
2313                          ate some tokens, see if we don't need to add
2314                          a padding token in between this and the
2315                          next token.  */
2316                       peek_tok = cpp_peek_token (pfile, 0);
2317                       if (peek_tok->type != CPP_PADDING
2318                           && (peek_tok->flags & PREV_WHITE) == 0)
2319                         _cpp_push_token_context (pfile, NULL,
2320                                                  padding_token (pfile,
2321                                                                 peek_tok), 1);
2322                     }
2323                 }
2324             }
2325           else
2326             ret = enter_macro_context (pfile, node, result, 
2327                                        virt_loc);
2328           if (ret)
2329             {
2330               if (pfile->state.in_directive || ret == 2)
2331                 continue;
2332               result = padding_token (pfile, result);
2333               goto out;
2334             }
2335         }
2336       else
2337         {
2338           /* Flag this token as always unexpandable.  FIXME: move this
2339              to collect_args()?.  */
2340           cpp_token *t = _cpp_temp_token (pfile);
2341           t->type = result->type;
2342           t->flags = result->flags | NO_EXPAND;
2343           t->val = result->val;
2344           result = t;
2345         }
2346
2347       break;
2348     }
2349
2350  out:
2351   if (location != NULL)
2352     {
2353       if (virt_loc == 0)
2354         virt_loc = result->src_loc;
2355       *location = virt_loc;
2356
2357       if (!CPP_OPTION (pfile, track_macro_expansion)
2358           && can_set
2359           && pfile->context->c.macro != NULL)
2360         /* We are in a macro expansion context, are not tracking
2361            virtual location, but were asked to report the location
2362            of the expansion point of the macro being expanded.  */
2363         *location = pfile->invocation_location;
2364
2365       *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2366     }
2367   return result;
2368 }
2369
2370 /* External routine to get a token.  Also used nearly everywhere
2371    internally, except for places where we know we can safely call
2372    _cpp_lex_token directly, such as lexing a directive name.
2373
2374    Macro expansions and directives are transparently handled,
2375    including entering included files.  Thus tokens are post-macro
2376    expansion, and after any intervening directives.  External callers
2377    see CPP_EOF only at EOF.  Internal callers also see it when meeting
2378    a directive inside a macro call, when at the end of a directive and
2379    state.in_directive is still 1, and at the end of argument
2380    pre-expansion.  */
2381 const cpp_token *
2382 cpp_get_token (cpp_reader *pfile)
2383 {
2384   return cpp_get_token_1 (pfile, NULL);
2385 }
2386
2387 /* Like cpp_get_token, but also returns a virtual token location
2388    separate from the spelling location carried by the returned token.
2389
2390    LOC is an out parameter; *LOC is set to the location "as expected
2391    by the user".  This matters when a token results from macro
2392    expansion; in that case the token's spelling location indicates the
2393    locus of the token in the definition of the macro but *LOC
2394    virtually encodes all the other meaningful locuses associated to
2395    the token.
2396
2397    What? virtual location? Yes, virtual location.
2398
2399    If the token results from macro expansion and if macro expansion
2400    location tracking is enabled its virtual location encodes (at the
2401    same time):
2402
2403    - the spelling location of the token
2404
2405    - the locus of the macro expansion point
2406
2407    - the locus of the point where the token got instantiated as part
2408      of the macro expansion process.
2409
2410    You have to use the linemap API to get the locus you are interested
2411    in from a given virtual location.
2412
2413    Note however that virtual locations are not necessarily ordered for
2414    relations '<' and '>'.  One must use the function
2415    linemap_location_before_p instead of using the relational operator
2416    '<'.
2417
2418    If macro expansion tracking is off and if the token results from
2419    macro expansion the virtual location is the expansion point of the
2420    macro that got expanded.
2421
2422    When the token doesn't result from macro expansion, the virtual
2423    location is just the same thing as its spelling location.  */
2424
2425 const cpp_token *
2426 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2427 {
2428   const cpp_token *result;
2429
2430   pfile->set_invocation_location = true;
2431   result = cpp_get_token_1 (pfile, loc);
2432   return result;
2433 }
2434
2435 /* Returns true if we're expanding an object-like macro that was
2436    defined in a system header.  Just checks the macro at the top of
2437    the stack.  Used for diagnostic suppression.  */
2438 int
2439 cpp_sys_macro_p (cpp_reader *pfile)
2440 {
2441   cpp_hashnode *node = pfile->context->c.macro;
2442
2443   return node && node->value.macro && node->value.macro->syshdr;
2444 }
2445
2446 /* Read each token in, until end of the current file.  Directives are
2447    transparently processed.  */
2448 void
2449 cpp_scan_nooutput (cpp_reader *pfile)
2450 {
2451   /* Request a CPP_EOF token at the end of this file, rather than
2452      transparently continuing with the including file.  */
2453   pfile->buffer->return_at_eof = true;
2454
2455   pfile->state.discarding_output++;
2456   pfile->state.prevent_expansion++;
2457
2458   if (CPP_OPTION (pfile, traditional))
2459     while (_cpp_read_logical_line_trad (pfile))
2460       ;
2461   else
2462     while (cpp_get_token (pfile)->type != CPP_EOF)
2463       ;
2464
2465   pfile->state.discarding_output--;
2466   pfile->state.prevent_expansion--;
2467 }
2468
2469 /* Step back one or more tokens obtained from the lexer.  */
2470 void
2471 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2472 {
2473   pfile->lookaheads += count;
2474   while (count--)
2475     {
2476       pfile->cur_token--;
2477       if (pfile->cur_token == pfile->cur_run->base
2478           /* Possible with -fpreprocessed and no leading #line.  */
2479           && pfile->cur_run->prev != NULL)
2480         {
2481           pfile->cur_run = pfile->cur_run->prev;
2482           pfile->cur_token = pfile->cur_run->limit;
2483         }
2484     }
2485 }
2486
2487 /* Step back one (or more) tokens.  Can only step back more than 1 if
2488    they are from the lexer, and not from macro expansion.  */
2489 void
2490 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2491 {
2492   if (pfile->context->prev == NULL)
2493     _cpp_backup_tokens_direct (pfile, count);
2494   else
2495     {
2496       if (count != 1)
2497         abort ();
2498       if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2499         FIRST (pfile->context).token--;
2500       else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2501         FIRST (pfile->context).ptoken--;
2502       else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2503         {
2504           FIRST (pfile->context).ptoken--;
2505           if (pfile->context->c.macro)
2506             {
2507               macro_context *m = pfile->context->c.mc;
2508               m->cur_virt_loc--;
2509 #ifdef ENABLE_CHECKING
2510               if (m->cur_virt_loc < m->virt_locs)
2511                 abort ();
2512 #endif
2513             }
2514           else
2515             abort ();
2516         }
2517       else
2518         abort ();
2519     }
2520 }
2521
2522 /* #define directive parsing and handling.  */
2523
2524 /* Returns nonzero if a macro redefinition warning is required.  */
2525 static bool
2526 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2527                       const cpp_macro *macro2)
2528 {
2529   const cpp_macro *macro1;
2530   unsigned int i;
2531
2532   /* Some redefinitions need to be warned about regardless.  */
2533   if (node->flags & NODE_WARN)
2534     return true;
2535
2536   /* Suppress warnings for builtins that lack the NODE_WARN flag.  */
2537   if (node->flags & NODE_BUILTIN)
2538     {
2539       if (!pfile->cb.user_builtin_macro
2540           || !pfile->cb.user_builtin_macro (pfile, node))
2541         return false;
2542     }
2543
2544   /* Redefinitions of conditional (context-sensitive) macros, on
2545      the other hand, must be allowed silently.  */
2546   if (node->flags & NODE_CONDITIONAL)
2547     return false;
2548
2549   /* Redefinition of a macro is allowed if and only if the old and new
2550      definitions are the same.  (6.10.3 paragraph 2).  */
2551   macro1 = node->value.macro;
2552
2553   /* Don't check count here as it can be different in valid
2554      traditional redefinitions with just whitespace differences.  */
2555   if (macro1->paramc != macro2->paramc
2556       || macro1->fun_like != macro2->fun_like
2557       || macro1->variadic != macro2->variadic)
2558     return true;
2559
2560   /* Check parameter spellings.  */
2561   for (i = 0; i < macro1->paramc; i++)
2562     if (macro1->params[i] != macro2->params[i])
2563       return true;
2564
2565   /* Check the replacement text or tokens.  */
2566   if (CPP_OPTION (pfile, traditional))
2567     return _cpp_expansions_different_trad (macro1, macro2);
2568
2569   if (macro1->count != macro2->count)
2570     return true;
2571
2572   for (i = 0; i < macro1->count; i++)
2573     if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2574       return true;
2575
2576   return false;
2577 }
2578
2579 /* Free the definition of hashnode H.  */
2580 void
2581 _cpp_free_definition (cpp_hashnode *h)
2582 {
2583   /* Macros and assertions no longer have anything to free.  */
2584   h->type = NT_VOID;
2585   /* Clear builtin flag in case of redefinition.  */
2586   h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2587 }
2588
2589 /* Save parameter NODE to the parameter list of macro MACRO.  Returns
2590    zero on success, nonzero if the parameter is a duplicate.  */
2591 bool
2592 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
2593 {
2594   unsigned int len;
2595   /* Constraint 6.10.3.6 - duplicate parameter names.  */
2596   if (node->flags & NODE_MACRO_ARG)
2597     {
2598       cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2599                  NODE_NAME (node));
2600       return true;
2601     }
2602
2603   if (BUFF_ROOM (pfile->a_buff)
2604       < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2605     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2606
2607   ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
2608   node->flags |= NODE_MACRO_ARG;
2609   len = macro->paramc * sizeof (union _cpp_hashnode_value);
2610   if (len > pfile->macro_buffer_len)
2611     {
2612       pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2613                                         len);
2614       pfile->macro_buffer_len = len;
2615     }
2616   ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
2617     = node->value;
2618   
2619   node->value.arg_index  = macro->paramc;
2620   return false;
2621 }
2622
2623 /* Check the syntax of the parameters in a MACRO definition.  Returns
2624    false if an error occurs.  */
2625 static bool
2626 parse_params (cpp_reader *pfile, cpp_macro *macro)
2627 {
2628   unsigned int prev_ident = 0;
2629
2630   for (;;)
2631     {
2632       const cpp_token *token = _cpp_lex_token (pfile);
2633
2634       switch (token->type)
2635         {
2636         default:
2637           /* Allow/ignore comments in parameter lists if we are
2638              preserving comments in macro expansions.  */
2639           if (token->type == CPP_COMMENT
2640               && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
2641             continue;
2642
2643           cpp_error (pfile, CPP_DL_ERROR,
2644                      "\"%s\" may not appear in macro parameter list",
2645                      cpp_token_as_text (pfile, token));
2646           return false;
2647
2648         case CPP_NAME:
2649           if (prev_ident)
2650             {
2651               cpp_error (pfile, CPP_DL_ERROR,
2652                          "macro parameters must be comma-separated");
2653               return false;
2654             }
2655           prev_ident = 1;
2656
2657           if (_cpp_save_parameter (pfile, macro, token->val.node.node))
2658             return false;
2659           continue;
2660
2661         case CPP_CLOSE_PAREN:
2662           if (prev_ident || macro->paramc == 0)
2663             return true;
2664
2665           /* Fall through to pick up the error.  */
2666         case CPP_COMMA:
2667           if (!prev_ident)
2668             {
2669               cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
2670               return false;
2671             }
2672           prev_ident = 0;
2673           continue;
2674
2675         case CPP_ELLIPSIS:
2676           macro->variadic = 1;
2677           if (!prev_ident)
2678             {
2679               _cpp_save_parameter (pfile, macro,
2680                                    pfile->spec_nodes.n__VA_ARGS__);
2681               pfile->state.va_args_ok = 1;
2682               if (! CPP_OPTION (pfile, c99)
2683                   && CPP_OPTION (pfile, cpp_pedantic)
2684                   && CPP_OPTION (pfile, warn_variadic_macros))
2685                 cpp_pedwarning
2686                   (pfile, CPP_W_VARIADIC_MACROS,
2687                    "anonymous variadic macros were introduced in C99");
2688             }
2689           else if (CPP_OPTION (pfile, cpp_pedantic)
2690                    && CPP_OPTION (pfile, warn_variadic_macros))
2691             cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2692                             "ISO C does not permit named variadic macros");
2693
2694           /* We're at the end, and just expect a closing parenthesis.  */
2695           token = _cpp_lex_token (pfile);
2696           if (token->type == CPP_CLOSE_PAREN)
2697             return true;
2698           /* Fall through.  */
2699
2700         case CPP_EOF:
2701           cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
2702           return false;
2703         }
2704     }
2705 }
2706
2707 /* Allocate room for a token from a macro's replacement list.  */
2708 static cpp_token *
2709 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2710 {
2711   if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
2712     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
2713
2714   return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
2715 }
2716
2717 /* Lex a token from the expansion of MACRO, but mark parameters as we
2718    find them and warn of traditional stringification.  */
2719 static cpp_token *
2720 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2721 {
2722   cpp_token *token, *saved_cur_token;
2723
2724   saved_cur_token = pfile->cur_token;
2725   pfile->cur_token = alloc_expansion_token (pfile, macro);
2726   token = _cpp_lex_direct (pfile);
2727   pfile->cur_token = saved_cur_token;
2728
2729   /* Is this a parameter?  */
2730   if (token->type == CPP_NAME
2731       && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
2732     {
2733       token->type = CPP_MACRO_ARG;
2734       token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
2735     }
2736   else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
2737            && (token->type == CPP_STRING || token->type == CPP_CHAR))
2738     check_trad_stringification (pfile, macro, &token->val.str);
2739
2740   return token;
2741 }
2742
2743 static bool
2744 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
2745 {
2746   cpp_token *token;
2747   const cpp_token *ctoken;
2748   bool following_paste_op = false;
2749   const char *paste_op_error_msg =
2750     N_("'##' cannot appear at either end of a macro expansion");
2751   unsigned int num_extra_tokens = 0;
2752
2753   /* Get the first token of the expansion (or the '(' of a
2754      function-like macro).  */
2755   ctoken = _cpp_lex_token (pfile);
2756
2757   if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
2758     {
2759       bool ok = parse_params (pfile, macro);
2760       macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
2761       if (!ok)
2762         return false;
2763
2764       /* Success.  Commit or allocate the parameter array.  */
2765       if (pfile->hash_table->alloc_subobject)
2766         {
2767           cpp_hashnode **params =
2768             (cpp_hashnode **) pfile->hash_table->alloc_subobject
2769             (sizeof (cpp_hashnode *) * macro->paramc);
2770           memcpy (params, macro->params,
2771                   sizeof (cpp_hashnode *) * macro->paramc);
2772           macro->params = params;
2773         }
2774       else
2775         BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
2776       macro->fun_like = 1;
2777     }
2778   else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
2779     {
2780       /* While ISO C99 requires whitespace before replacement text
2781          in a macro definition, ISO C90 with TC1 allows there characters
2782          from the basic source character set.  */
2783       if (CPP_OPTION (pfile, c99))
2784         cpp_error (pfile, CPP_DL_PEDWARN,
2785                    "ISO C99 requires whitespace after the macro name");
2786       else
2787         {
2788           int warntype = CPP_DL_WARNING;
2789           switch (ctoken->type)
2790             {
2791             case CPP_ATSIGN:
2792             case CPP_AT_NAME:
2793             case CPP_OBJC_STRING:
2794               /* '@' is not in basic character set.  */
2795               warntype = CPP_DL_PEDWARN;
2796               break;
2797             case CPP_OTHER:
2798               /* Basic character set sans letters, digits and _.  */
2799               if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
2800                           ctoken->val.str.text[0]) == NULL)
2801                 warntype = CPP_DL_PEDWARN;
2802               break;
2803             default:
2804               /* All other tokens start with a character from basic
2805                  character set.  */
2806               break;
2807             }
2808           cpp_error (pfile, warntype,
2809                      "missing whitespace after the macro name");
2810         }
2811     }
2812
2813   if (macro->fun_like)
2814     token = lex_expansion_token (pfile, macro);
2815   else
2816     {
2817       token = alloc_expansion_token (pfile, macro);
2818       *token = *ctoken;
2819     }
2820
2821   for (;;)
2822     {
2823       /* Check the stringifying # constraint 6.10.3.2.1 of
2824          function-like macros when lexing the subsequent token.  */
2825       if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
2826         {
2827           if (token->type == CPP_MACRO_ARG)
2828             {
2829               if (token->flags & PREV_WHITE)
2830                 token->flags |= SP_PREV_WHITE;
2831               if (token[-1].flags & DIGRAPH)
2832                 token->flags |= SP_DIGRAPH;
2833               token->flags &= ~PREV_WHITE;
2834               token->flags |= STRINGIFY_ARG;
2835               token->flags |= token[-1].flags & PREV_WHITE;
2836               token[-1] = token[0];
2837               macro->count--;
2838             }
2839           /* Let assembler get away with murder.  */
2840           else if (CPP_OPTION (pfile, lang) != CLK_ASM)
2841             {
2842               cpp_error (pfile, CPP_DL_ERROR,
2843                          "'#' is not followed by a macro parameter");
2844               return false;
2845             }
2846         }
2847
2848       if (token->type == CPP_EOF)
2849         {
2850           /* Paste operator constraint 6.10.3.3.1:
2851              Token-paste ##, can appear in both object-like and
2852              function-like macros, but not at the end.  */
2853           if (following_paste_op)
2854             {
2855               cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
2856               return false;
2857             }
2858           break;
2859         }
2860
2861       /* Paste operator constraint 6.10.3.3.1.  */
2862       if (token->type == CPP_PASTE)
2863         {
2864           /* Token-paste ##, can appear in both object-like and
2865              function-like macros, but not at the beginning.  */
2866           if (macro->count == 1)
2867             {
2868               cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
2869               return false;
2870             }
2871
2872           if (token[-1].flags & PASTE_LEFT)
2873             {
2874               macro->extra_tokens = 1;
2875               num_extra_tokens++;
2876               token->val.token_no = macro->count - 1;
2877             }
2878           else
2879             {
2880               --macro->count;
2881               token[-1].flags |= PASTE_LEFT;
2882               if (token->flags & DIGRAPH)
2883                 token[-1].flags |= SP_DIGRAPH;
2884               if (token->flags & PREV_WHITE)
2885                 token[-1].flags |= SP_PREV_WHITE;
2886             }
2887         }
2888
2889       following_paste_op = (token->type == CPP_PASTE);
2890       token = lex_expansion_token (pfile, macro);
2891     }
2892
2893   macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
2894   macro->traditional = 0;
2895
2896   /* Don't count the CPP_EOF.  */
2897   macro->count--;
2898
2899   /* Clear whitespace on first token for warn_of_redefinition().  */
2900   if (macro->count)
2901     macro->exp.tokens[0].flags &= ~PREV_WHITE;
2902
2903   /* Commit or allocate the memory.  */
2904   if (pfile->hash_table->alloc_subobject)
2905     {
2906       cpp_token *tokns =
2907         (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
2908                                                           * macro->count);
2909       if (num_extra_tokens)
2910         {
2911           /* Place second and subsequent ## or %:%: tokens in
2912              sequences of consecutive such tokens at the end of the
2913              list to preserve information about where they appear, how
2914              they are spelt and whether they are preceded by
2915              whitespace without otherwise interfering with macro
2916              expansion.  */
2917           cpp_token *normal_dest = tokns;
2918           cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
2919           unsigned int i;
2920           for (i = 0; i < macro->count; i++)
2921             {
2922               if (macro->exp.tokens[i].type == CPP_PASTE)
2923                 *extra_dest++ = macro->exp.tokens[i];
2924               else
2925                 *normal_dest++ = macro->exp.tokens[i];
2926             }
2927         }
2928       else
2929         memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
2930       macro->exp.tokens = tokns;
2931     }
2932   else
2933     BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
2934
2935   return true;
2936 }
2937
2938 /* Parse a macro and save its expansion.  Returns nonzero on success.  */
2939 bool
2940 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
2941 {
2942   cpp_macro *macro;
2943   unsigned int i;
2944   bool ok;
2945
2946   if (pfile->hash_table->alloc_subobject)
2947     macro = (cpp_macro *) pfile->hash_table->alloc_subobject
2948       (sizeof (cpp_macro));
2949   else
2950     macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
2951   macro->line = pfile->directive_line;
2952   macro->params = 0;
2953   macro->paramc = 0;
2954   macro->variadic = 0;
2955   macro->used = !CPP_OPTION (pfile, warn_unused_macros);
2956   macro->count = 0;
2957   macro->fun_like = 0;
2958   macro->extra_tokens = 0;
2959   /* To suppress some diagnostics.  */
2960   macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
2961
2962   if (CPP_OPTION (pfile, traditional))
2963     ok = _cpp_create_trad_definition (pfile, macro);
2964   else
2965     {
2966       ok = create_iso_definition (pfile, macro);
2967
2968       /* We set the type for SEEN_EOL() in directives.c.
2969
2970          Longer term we should lex the whole line before coming here,
2971          and just copy the expansion.  */
2972
2973       /* Stop the lexer accepting __VA_ARGS__.  */
2974       pfile->state.va_args_ok = 0;
2975     }
2976
2977   /* Clear the fast argument lookup indices.  */
2978   for (i = macro->paramc; i-- > 0; )
2979     {
2980       struct cpp_hashnode *node = macro->params[i];
2981       node->flags &= ~ NODE_MACRO_ARG;
2982       node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
2983     }
2984
2985   if (!ok)
2986     return ok;
2987
2988   if (node->type == NT_MACRO)
2989     {
2990       if (CPP_OPTION (pfile, warn_unused_macros))
2991         _cpp_warn_if_unused_macro (pfile, node, NULL);
2992
2993       if (warn_of_redefinition (pfile, node, macro))
2994         {
2995           const int reason = (node->flags & NODE_BUILTIN)
2996                              ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
2997           bool warned;
2998
2999           warned = cpp_pedwarning_with_line (pfile, reason,
3000                                              pfile->directive_line, 0,
3001                                              "\"%s\" redefined",
3002                                              NODE_NAME (node));
3003
3004           if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3005             cpp_error_with_line (pfile, CPP_DL_NOTE,
3006                                  node->value.macro->line, 0,
3007                          "this is the location of the previous definition");
3008         }
3009     }
3010
3011   if (node->type != NT_VOID)
3012     _cpp_free_definition (node);
3013
3014   /* Enter definition in hash table.  */
3015   node->type = NT_MACRO;
3016   node->value.macro = macro;
3017   if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3018       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3019       /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3020          in the C standard, as something that one must use in C++.
3021          However DR#593 indicates that these aren't actually mentioned
3022          in the C++ standard.  We special-case them anyway.  */
3023       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3024       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3025     node->flags |= NODE_WARN;
3026
3027   /* If user defines one of the conditional macros, remove the
3028      conditional flag */
3029   node->flags &= ~NODE_CONDITIONAL;
3030
3031   return ok;
3032 }
3033
3034 /* Warn if a token in STRING matches one of a function-like MACRO's
3035    parameters.  */
3036 static void
3037 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3038                             const cpp_string *string)
3039 {
3040   unsigned int i, len;
3041   const uchar *p, *q, *limit;
3042
3043   /* Loop over the string.  */
3044   limit = string->text + string->len - 1;
3045   for (p = string->text + 1; p < limit; p = q)
3046     {
3047       /* Find the start of an identifier.  */
3048       while (p < limit && !is_idstart (*p))
3049         p++;
3050
3051       /* Find the end of the identifier.  */
3052       q = p;
3053       while (q < limit && is_idchar (*q))
3054         q++;
3055
3056       len = q - p;
3057
3058       /* Loop over the function macro arguments to see if the
3059          identifier inside the string matches one of them.  */
3060       for (i = 0; i < macro->paramc; i++)
3061         {
3062           const cpp_hashnode *node = macro->params[i];
3063
3064           if (NODE_LEN (node) == len
3065               && !memcmp (p, NODE_NAME (node), len))
3066             {
3067               cpp_error (pfile, CPP_DL_WARNING,
3068            "macro argument \"%s\" would be stringified in traditional C",
3069                          NODE_NAME (node));
3070               break;
3071             }
3072         }
3073     }
3074 }
3075
3076 /* Returns the name, arguments and expansion of a macro, in a format
3077    suitable to be read back in again, and therefore also for DWARF 2
3078    debugging info.  e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3079    Caller is expected to generate the "#define" bit if needed.  The
3080    returned text is temporary, and automatically freed later.  */
3081 const unsigned char *
3082 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3083 {
3084   unsigned int i, len;
3085   const cpp_macro *macro;
3086   unsigned char *buffer;
3087
3088   if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3089     {
3090       if (node->type != NT_MACRO
3091           || !pfile->cb.user_builtin_macro
3092           || !pfile->cb.user_builtin_macro (pfile, node))
3093         {
3094           cpp_error (pfile, CPP_DL_ICE,
3095                      "invalid hash type %d in cpp_macro_definition",
3096                      node->type);
3097           return 0;
3098         }
3099     }
3100
3101   macro = node->value.macro;
3102   /* Calculate length.  */
3103   len = NODE_LEN (node) + 2;                    /* ' ' and NUL.  */
3104   if (macro->fun_like)
3105     {
3106       len += 4;         /* "()" plus possible final ".." of named
3107                            varargs (we have + 1 below).  */
3108       for (i = 0; i < macro->paramc; i++)
3109         len += NODE_LEN (macro->params[i]) + 1; /* "," */
3110     }
3111
3112   /* This should match below where we fill in the buffer.  */
3113   if (CPP_OPTION (pfile, traditional))
3114     len += _cpp_replacement_text_len (macro);
3115   else
3116     {
3117       unsigned int count = macro_real_token_count (macro);
3118       for (i = 0; i < count; i++)
3119         {
3120           cpp_token *token = &macro->exp.tokens[i];
3121
3122           if (token->type == CPP_MACRO_ARG)
3123             len += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3124           else
3125             len += cpp_token_len (token);
3126
3127           if (token->flags & STRINGIFY_ARG)
3128             len++;                      /* "#" */
3129           if (token->flags & PASTE_LEFT)
3130             len += 3;           /* " ##" */
3131           if (token->flags & PREV_WHITE)
3132             len++;              /* " " */
3133         }
3134     }
3135
3136   if (len > pfile->macro_buffer_len)
3137     {
3138       pfile->macro_buffer = XRESIZEVEC (unsigned char,
3139                                         pfile->macro_buffer, len);
3140       pfile->macro_buffer_len = len;
3141     }
3142
3143   /* Fill in the buffer.  Start with the macro name.  */
3144   buffer = pfile->macro_buffer;
3145   memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
3146   buffer += NODE_LEN (node);
3147
3148   /* Parameter names.  */
3149   if (macro->fun_like)
3150     {
3151       *buffer++ = '(';
3152       for (i = 0; i < macro->paramc; i++)
3153         {
3154           cpp_hashnode *param = macro->params[i];
3155
3156           if (param != pfile->spec_nodes.n__VA_ARGS__)
3157             {
3158               memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3159               buffer += NODE_LEN (param);
3160             }
3161
3162           if (i + 1 < macro->paramc)
3163             /* Don't emit a space after the comma here; we're trying
3164                to emit a Dwarf-friendly definition, and the Dwarf spec
3165                forbids spaces in the argument list.  */
3166             *buffer++ = ',';
3167           else if (macro->variadic)
3168             *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3169         }
3170       *buffer++ = ')';
3171     }
3172
3173   /* The Dwarf spec requires a space after the macro name, even if the
3174      definition is the empty string.  */
3175   *buffer++ = ' ';
3176
3177   if (CPP_OPTION (pfile, traditional))
3178     buffer = _cpp_copy_replacement_text (macro, buffer);
3179   else if (macro->count)
3180   /* Expansion tokens.  */
3181     {
3182       unsigned int count = macro_real_token_count (macro);
3183       for (i = 0; i < count; i++)
3184         {
3185           cpp_token *token = &macro->exp.tokens[i];
3186
3187           if (token->flags & PREV_WHITE)
3188             *buffer++ = ' ';
3189           if (token->flags & STRINGIFY_ARG)
3190             *buffer++ = '#';
3191
3192           if (token->type == CPP_MACRO_ARG)
3193             {
3194               memcpy (buffer,
3195                       NODE_NAME (macro->params[token->val.macro_arg.arg_no - 1]),
3196                       NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]));
3197               buffer += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3198             }
3199           else
3200             buffer = cpp_spell_token (pfile, token, buffer, false);
3201
3202           if (token->flags & PASTE_LEFT)
3203             {
3204               *buffer++ = ' ';
3205               *buffer++ = '#';
3206               *buffer++ = '#';
3207               /* Next has PREV_WHITE; see _cpp_create_definition.  */
3208             }
3209         }
3210     }
3211
3212   *buffer = '\0';
3213   return pfile->macro_buffer;
3214 }