Support location tracking for built-in macro tokens
[official-gcc.git] / libcpp / macro.c
blob3b8fa4069352918166dc1cbf434d1de5028ea677
1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986-2014 Free Software Foundation, Inc.
3 Written by Per Bothner, 1994.
4 Based on CCCP program by Paul Rubin, June 1986
5 Adapted to ANSI C, Richard Stallman, Jan 1987
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>.
21 In other words, you are welcome to use, share and improve this program.
22 You are forbidden to forbid anyone else to use, share and improve
23 what you give them. Help stamp out software-hoarding! */
25 #include "config.h"
26 #include "system.h"
27 #include "cpplib.h"
28 #include "internal.h"
30 typedef struct macro_arg macro_arg;
31 /* This structure represents the tokens of a macro argument. These
32 tokens can be macro themselves, in which case they can be either
33 expanded or unexpanded. When they are expanded, this data
34 structure keeps both the expanded and unexpanded forms. */
35 struct macro_arg
37 const cpp_token **first; /* First token in unexpanded argument. */
38 const cpp_token **expanded; /* Macro-expanded argument. */
39 const cpp_token *stringified; /* Stringified argument. */
40 unsigned int count; /* # of tokens in argument. */
41 unsigned int expanded_count; /* # of tokens in expanded argument. */
42 source_location *virt_locs; /* Where virtual locations for
43 unexpanded tokens are stored. */
44 source_location *expanded_virt_locs; /* Where virtual locations for
45 expanded tokens are
46 stored. */
49 /* The kind of macro tokens which the instance of
50 macro_arg_token_iter is supposed to iterate over. */
51 enum macro_arg_token_kind {
52 MACRO_ARG_TOKEN_NORMAL,
53 /* This is a macro argument token that got transformed into a string
54 litteral, e.g. #foo. */
55 MACRO_ARG_TOKEN_STRINGIFIED,
56 /* This is a token resulting from the expansion of a macro
57 argument that was itself a macro. */
58 MACRO_ARG_TOKEN_EXPANDED
61 /* An iterator over tokens coming from a function-like macro
62 argument. */
63 typedef struct macro_arg_token_iter macro_arg_token_iter;
64 struct macro_arg_token_iter
66 /* Whether or not -ftrack-macro-expansion is used. */
67 bool track_macro_exp_p;
68 /* The kind of token over which we are supposed to iterate. */
69 enum macro_arg_token_kind kind;
70 /* A pointer to the current token pointed to by the iterator. */
71 const cpp_token **token_ptr;
72 /* A pointer to the "full" location of the current token. If
73 -ftrack-macro-expansion is used this location tracks loci across
74 macro expansion. */
75 const source_location *location_ptr;
76 #ifdef ENABLE_CHECKING
77 /* The number of times the iterator went forward. This useful only
78 when checking is enabled. */
79 size_t num_forwards;
80 #endif
83 /* Macro expansion. */
85 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
86 const cpp_token *, source_location);
87 static int builtin_macro (cpp_reader *, cpp_hashnode *);
88 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
89 const cpp_token **, unsigned int);
90 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
91 _cpp_buff *, source_location *,
92 const cpp_token **, unsigned int);
93 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
94 _cpp_buff **, unsigned *);
95 static cpp_context *next_context (cpp_reader *);
96 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
97 static void expand_arg (cpp_reader *, macro_arg *);
98 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
99 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
100 static void paste_all_tokens (cpp_reader *, const cpp_token *);
101 static bool paste_tokens (cpp_reader *, source_location,
102 const cpp_token **, const cpp_token *);
103 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
104 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
105 static void delete_macro_args (_cpp_buff*, unsigned num_args);
106 static void set_arg_token (macro_arg *, const cpp_token *,
107 source_location, size_t,
108 enum macro_arg_token_kind,
109 bool);
110 static const source_location *get_arg_token_location (const macro_arg *,
111 enum macro_arg_token_kind);
112 static const cpp_token **arg_token_ptr_at (const macro_arg *,
113 size_t,
114 enum macro_arg_token_kind,
115 source_location **virt_location);
117 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
118 enum macro_arg_token_kind,
119 const macro_arg *,
120 const cpp_token **);
121 static const cpp_token *macro_arg_token_iter_get_token
122 (const macro_arg_token_iter *it);
123 static source_location macro_arg_token_iter_get_location
124 (const macro_arg_token_iter *);
125 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
126 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
127 source_location **);
128 static size_t tokens_buff_count (_cpp_buff *);
129 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
130 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
131 source_location *,
132 const cpp_token *,
133 source_location,
134 source_location,
135 const struct line_map *,
136 unsigned int);
138 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
139 source_location *,
140 const cpp_token *,
141 source_location,
142 source_location,
143 const struct line_map *,
144 unsigned int);
145 static inline void tokens_buff_remove_last_token (_cpp_buff *);
146 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
147 macro_arg *, source_location);
148 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
149 _cpp_buff **, unsigned *);
150 static bool create_iso_definition (cpp_reader *, cpp_macro *);
152 /* #define directive parsing and handling. */
154 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
155 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
156 static bool warn_of_redefinition (cpp_reader *, cpp_hashnode *,
157 const cpp_macro *);
158 static bool parse_params (cpp_reader *, cpp_macro *);
159 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
160 const cpp_string *);
161 static bool reached_end_of_context (cpp_context *);
162 static void consume_next_token_from_context (cpp_reader *pfile,
163 const cpp_token **,
164 source_location *);
165 static const cpp_token* cpp_get_token_1 (cpp_reader *, source_location *);
167 static cpp_hashnode* macro_of_context (cpp_context *context);
169 static bool in_macro_expansion_p (cpp_reader *pfile);
171 /* Statistical counter tracking the number of macros that got
172 expanded. */
173 unsigned num_expanded_macros_counter = 0;
174 /* Statistical counter tracking the total number tokens resulting
175 from macro expansion. */
176 unsigned num_macro_tokens_counter = 0;
178 /* Emits a warning if NODE is a macro defined in the main file that
179 has not been used. */
181 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
182 void *v ATTRIBUTE_UNUSED)
184 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
186 cpp_macro *macro = node->value.macro;
188 if (!macro->used
189 && MAIN_FILE_P (linemap_lookup (pfile->line_table, macro->line)))
190 cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
191 "macro \"%s\" is not used", NODE_NAME (node));
194 return 1;
197 /* Allocates and returns a CPP_STRING token, containing TEXT of length
198 LEN, after null-terminating it. TEXT must be in permanent storage. */
199 static const cpp_token *
200 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
202 cpp_token *token = _cpp_temp_token (pfile);
204 text[len] = '\0';
205 token->type = CPP_STRING;
206 token->val.str.len = len;
207 token->val.str.text = text;
208 token->flags = 0;
209 return token;
212 static const char * const monthnames[] =
214 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
215 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
218 /* Helper function for builtin_macro. Returns the text generated by
219 a builtin macro. */
220 const uchar *
221 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
223 const uchar *result = NULL;
224 linenum_type number = 1;
226 switch (node->value.builtin)
228 default:
229 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
230 NODE_NAME (node));
231 break;
233 case BT_TIMESTAMP:
235 if (CPP_OPTION (pfile, warn_date_time))
236 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
237 "reproducible builds", NODE_NAME (node));
239 cpp_buffer *pbuffer = cpp_get_buffer (pfile);
240 if (pbuffer->timestamp == NULL)
242 /* Initialize timestamp value of the assotiated file. */
243 struct _cpp_file *file = cpp_get_file (pbuffer);
244 if (file)
246 /* Generate __TIMESTAMP__ string, that represents
247 the date and time of the last modification
248 of the current source file. The string constant
249 looks like "Sun Sep 16 01:03:52 1973". */
250 struct tm *tb = NULL;
251 struct stat *st = _cpp_get_file_stat (file);
252 if (st)
253 tb = localtime (&st->st_mtime);
254 if (tb)
256 char *str = asctime (tb);
257 size_t len = strlen (str);
258 unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
259 buf[0] = '"';
260 strcpy ((char *) buf + 1, str);
261 buf[len] = '"';
262 pbuffer->timestamp = buf;
264 else
266 cpp_errno (pfile, CPP_DL_WARNING,
267 "could not determine file timestamp");
268 pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
272 result = pbuffer->timestamp;
274 break;
275 case BT_FILE:
276 case BT_BASE_FILE:
278 unsigned int len;
279 const char *name;
280 uchar *buf;
282 if (node->value.builtin == BT_FILE)
283 name = linemap_get_expansion_filename (pfile->line_table,
284 pfile->line_table->highest_line);
285 else
287 name = _cpp_get_file_name (pfile->main_file);
288 if (!name)
289 abort ();
291 len = strlen (name);
292 buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
293 result = buf;
294 *buf = '"';
295 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
296 *buf++ = '"';
297 *buf = '\0';
299 break;
301 case BT_INCLUDE_LEVEL:
302 /* The line map depth counts the primary source as level 1, but
303 historically __INCLUDE_DEPTH__ has called the primary source
304 level 0. */
305 number = pfile->line_table->depth - 1;
306 break;
308 case BT_SPECLINE:
309 /* If __LINE__ is embedded in a macro, it must expand to the
310 line of the macro's invocation, not its definition.
311 Otherwise things like assert() will not work properly. */
312 number = linemap_get_expansion_line (pfile->line_table,
313 CPP_OPTION (pfile, traditional)
314 ? pfile->line_table->highest_line
315 : pfile->cur_token[-1].src_loc);
316 break;
318 /* __STDC__ has the value 1 under normal circumstances.
319 However, if (a) we are in a system header, (b) the option
320 stdc_0_in_system_headers is true (set by target config), and
321 (c) we are not in strictly conforming mode, then it has the
322 value 0. (b) and (c) are already checked in cpp_init_builtins. */
323 case BT_STDC:
324 if (cpp_in_system_header (pfile))
325 number = 0;
326 else
327 number = 1;
328 break;
330 case BT_DATE:
331 case BT_TIME:
332 if (CPP_OPTION (pfile, warn_date_time))
333 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
334 "reproducible builds", NODE_NAME (node));
335 if (pfile->date == NULL)
337 /* Allocate __DATE__ and __TIME__ strings from permanent
338 storage. We only do this once, and don't generate them
339 at init time, because time() and localtime() are very
340 slow on some systems. */
341 time_t tt;
342 struct tm *tb = NULL;
344 /* (time_t) -1 is a legitimate value for "number of seconds
345 since the Epoch", so we have to do a little dance to
346 distinguish that from a genuine error. */
347 errno = 0;
348 tt = time(NULL);
349 if (tt != (time_t)-1 || errno == 0)
350 tb = localtime (&tt);
352 if (tb)
354 pfile->date = _cpp_unaligned_alloc (pfile,
355 sizeof ("\"Oct 11 1347\""));
356 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
357 monthnames[tb->tm_mon], tb->tm_mday,
358 tb->tm_year + 1900);
360 pfile->time = _cpp_unaligned_alloc (pfile,
361 sizeof ("\"12:34:56\""));
362 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
363 tb->tm_hour, tb->tm_min, tb->tm_sec);
365 else
367 cpp_errno (pfile, CPP_DL_WARNING,
368 "could not determine date and time");
370 pfile->date = UC"\"??? ?? ????\"";
371 pfile->time = UC"\"??:??:??\"";
375 if (node->value.builtin == BT_DATE)
376 result = pfile->date;
377 else
378 result = pfile->time;
379 break;
381 case BT_COUNTER:
382 if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
383 cpp_error (pfile, CPP_DL_ERROR,
384 "__COUNTER__ expanded inside directive with -fdirectives-only");
385 number = pfile->counter++;
386 break;
389 if (result == NULL)
391 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
392 result = _cpp_unaligned_alloc (pfile, 21);
393 sprintf ((char *) result, "%u", number);
396 return result;
399 /* Convert builtin macros like __FILE__ to a token and push it on the
400 context stack. Also handles _Pragma, for which a new token may not
401 be created. Returns 1 if it generates a new token context, 0 to
402 return the token to the caller. */
403 static int
404 builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
406 const uchar *buf;
407 size_t len;
408 char *nbuf;
410 if (node->value.builtin == BT_PRAGMA)
412 /* Don't interpret _Pragma within directives. The standard is
413 not clear on this, but to me this makes most sense. */
414 if (pfile->state.in_directive)
415 return 0;
417 return _cpp_do__Pragma (pfile);
420 buf = _cpp_builtin_macro_text (pfile, node);
421 len = ustrlen (buf);
422 nbuf = (char *) alloca (len + 1);
423 memcpy (nbuf, buf, len);
424 nbuf[len]='\n';
426 cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
427 _cpp_clean_line (pfile);
429 /* Set pfile->cur_token as required by _cpp_lex_direct. */
430 pfile->cur_token = _cpp_temp_token (pfile);
431 cpp_token *token = _cpp_lex_direct (pfile);
432 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
434 /* We are tracking tokens resulting from macro expansion.
435 Create a macro line map and generate a virtual location for
436 the token resulting from the expansion of the built-in
437 macro. */
438 source_location *virt_locs = NULL;
439 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
440 const line_map * map =
441 linemap_enter_macro (pfile->line_table, node,
442 token->src_loc, 1);
443 tokens_buff_add_token (token_buf, virt_locs, token,
444 pfile->line_table->builtin_location,
445 pfile->line_table->builtin_location,
446 map, /*macro_token_index=*/0);
447 push_extended_tokens_context (pfile, node, token_buf, virt_locs,
448 (const cpp_token **)token_buf->base,
451 else
452 _cpp_push_token_context (pfile, NULL, token, 1);
453 if (pfile->buffer->cur != pfile->buffer->rlimit)
454 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
455 NODE_NAME (node));
456 _cpp_pop_buffer (pfile);
458 return 1;
461 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
462 backslashes and double quotes. DEST must be of sufficient size.
463 Returns a pointer to the end of the string. */
464 uchar *
465 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
467 while (len--)
469 uchar c = *src++;
471 if (c == '\\' || c == '"')
473 *dest++ = '\\';
474 *dest++ = c;
476 else
477 *dest++ = c;
480 return dest;
483 /* Convert a token sequence ARG to a single string token according to
484 the rules of the ISO C #-operator. */
485 static const cpp_token *
486 stringify_arg (cpp_reader *pfile, macro_arg *arg)
488 unsigned char *dest;
489 unsigned int i, escape_it, backslash_count = 0;
490 const cpp_token *source = NULL;
491 size_t len;
493 if (BUFF_ROOM (pfile->u_buff) < 3)
494 _cpp_extend_buff (pfile, &pfile->u_buff, 3);
495 dest = BUFF_FRONT (pfile->u_buff);
496 *dest++ = '"';
498 /* Loop, reading in the argument's tokens. */
499 for (i = 0; i < arg->count; i++)
501 const cpp_token *token = arg->first[i];
503 if (token->type == CPP_PADDING)
505 if (source == NULL
506 || (!(source->flags & PREV_WHITE)
507 && token->val.source == NULL))
508 source = token->val.source;
509 continue;
512 escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
513 || token->type == CPP_WSTRING || token->type == CPP_WCHAR
514 || token->type == CPP_STRING32 || token->type == CPP_CHAR32
515 || token->type == CPP_STRING16 || token->type == CPP_CHAR16
516 || token->type == CPP_UTF8STRING
517 || cpp_userdef_string_p (token->type)
518 || cpp_userdef_char_p (token->type));
520 /* Room for each char being written in octal, initial space and
521 final quote and NUL. */
522 len = cpp_token_len (token);
523 if (escape_it)
524 len *= 4;
525 len += 3;
527 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
529 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
530 _cpp_extend_buff (pfile, &pfile->u_buff, len);
531 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
534 /* Leading white space? */
535 if (dest - 1 != BUFF_FRONT (pfile->u_buff))
537 if (source == NULL)
538 source = token;
539 if (source->flags & PREV_WHITE)
540 *dest++ = ' ';
542 source = NULL;
544 if (escape_it)
546 _cpp_buff *buff = _cpp_get_buff (pfile, len);
547 unsigned char *buf = BUFF_FRONT (buff);
548 len = cpp_spell_token (pfile, token, buf, true) - buf;
549 dest = cpp_quote_string (dest, buf, len);
550 _cpp_release_buff (pfile, buff);
552 else
553 dest = cpp_spell_token (pfile, token, dest, true);
555 if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
556 backslash_count++;
557 else
558 backslash_count = 0;
561 /* Ignore the final \ of invalid string literals. */
562 if (backslash_count & 1)
564 cpp_error (pfile, CPP_DL_WARNING,
565 "invalid string literal, ignoring final '\\'");
566 dest--;
569 /* Commit the memory, including NUL, and return the token. */
570 *dest++ = '"';
571 len = dest - BUFF_FRONT (pfile->u_buff);
572 BUFF_FRONT (pfile->u_buff) = dest + 1;
573 return new_string_token (pfile, dest - len, len);
576 /* Try to paste two tokens. On success, return nonzero. In any
577 case, PLHS is updated to point to the pasted token, which is
578 guaranteed to not have the PASTE_LEFT flag set. LOCATION is
579 the virtual location used for error reporting. */
580 static bool
581 paste_tokens (cpp_reader *pfile, source_location location,
582 const cpp_token **plhs, const cpp_token *rhs)
584 unsigned char *buf, *end, *lhsend;
585 cpp_token *lhs;
586 unsigned int len;
588 len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
589 buf = (unsigned char *) alloca (len);
590 end = lhsend = cpp_spell_token (pfile, *plhs, buf, false);
592 /* Avoid comment headers, since they are still processed in stage 3.
593 It is simpler to insert a space here, rather than modifying the
594 lexer to ignore comments in some circumstances. Simply returning
595 false doesn't work, since we want to clear the PASTE_LEFT flag. */
596 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
597 *end++ = ' ';
598 /* In one obscure case we might see padding here. */
599 if (rhs->type != CPP_PADDING)
600 end = cpp_spell_token (pfile, rhs, end, false);
601 *end = '\n';
603 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
604 _cpp_clean_line (pfile);
606 /* Set pfile->cur_token as required by _cpp_lex_direct. */
607 pfile->cur_token = _cpp_temp_token (pfile);
608 lhs = _cpp_lex_direct (pfile);
609 if (pfile->buffer->cur != pfile->buffer->rlimit)
611 source_location saved_loc = lhs->src_loc;
613 _cpp_pop_buffer (pfile);
614 _cpp_backup_tokens (pfile, 1);
615 *lhsend = '\0';
617 /* We have to remove the PASTE_LEFT flag from the old lhs, but
618 we want to keep the new location. */
619 *lhs = **plhs;
620 *plhs = lhs;
621 lhs->src_loc = saved_loc;
622 lhs->flags &= ~PASTE_LEFT;
624 /* Mandatory error for all apart from assembler. */
625 if (CPP_OPTION (pfile, lang) != CLK_ASM)
626 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
627 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
628 buf, cpp_token_as_text (pfile, rhs));
629 return false;
632 *plhs = lhs;
633 _cpp_pop_buffer (pfile);
634 return true;
637 /* Handles an arbitrarily long sequence of ## operators, with initial
638 operand LHS. This implementation is left-associative,
639 non-recursive, and finishes a paste before handling succeeding
640 ones. If a paste fails, we back up to the RHS of the failing ##
641 operator before pushing the context containing the result of prior
642 successful pastes, with the effect that the RHS appears in the
643 output stream after the pasted LHS normally. */
644 static void
645 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
647 const cpp_token *rhs = NULL;
648 cpp_context *context = pfile->context;
649 source_location virt_loc = 0;
651 /* We are expanding a macro and we must have been called on a token
652 that appears at the left hand side of a ## operator. */
653 if (macro_of_context (pfile->context) == NULL
654 || (!(lhs->flags & PASTE_LEFT)))
655 abort ();
657 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
658 /* The caller must have called consume_next_token_from_context
659 right before calling us. That has incremented the pointer to
660 the current virtual location. So it now points to the location
661 of the token that comes right after *LHS. We want the
662 resulting pasted token to have the location of the current
663 *LHS, though. */
664 virt_loc = context->c.mc->cur_virt_loc[-1];
665 else
666 /* We are not tracking macro expansion. So the best virtual
667 location we can get here is the expansion point of the macro we
668 are currently expanding. */
669 virt_loc = pfile->invocation_location;
673 /* Take the token directly from the current context. We can do
674 this, because we are in the replacement list of either an
675 object-like macro, or a function-like macro with arguments
676 inserted. In either case, the constraints to #define
677 guarantee we have at least one more token. */
678 if (context->tokens_kind == TOKENS_KIND_DIRECT)
679 rhs = FIRST (context).token++;
680 else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
681 rhs = *FIRST (context).ptoken++;
682 else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
684 /* So we are in presence of an extended token context, which
685 means that each token in this context has a virtual
686 location attached to it. So let's not forget to update
687 the pointer to the current virtual location of the
688 current token when we update the pointer to the current
689 token */
691 rhs = *FIRST (context).ptoken++;
692 /* context->c.mc must be non-null, as if we were not in a
693 macro context, context->tokens_kind could not be equal to
694 TOKENS_KIND_EXTENDED. */
695 context->c.mc->cur_virt_loc++;
698 if (rhs->type == CPP_PADDING)
700 if (rhs->flags & PASTE_LEFT)
701 abort ();
703 if (!paste_tokens (pfile, virt_loc, &lhs, rhs))
704 break;
706 while (rhs->flags & PASTE_LEFT);
708 /* Put the resulting token in its own context. */
709 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
711 source_location *virt_locs = NULL;
712 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
713 tokens_buff_add_token (token_buf, virt_locs, lhs,
714 virt_loc, 0, NULL, 0);
715 push_extended_tokens_context (pfile, context->c.mc->macro_node,
716 token_buf, virt_locs,
717 (const cpp_token **)token_buf->base, 1);
719 else
720 _cpp_push_token_context (pfile, NULL, lhs, 1);
723 /* Returns TRUE if the number of arguments ARGC supplied in an
724 invocation of the MACRO referenced by NODE is valid. An empty
725 invocation to a macro with no parameters should pass ARGC as zero.
727 Note that MACRO cannot necessarily be deduced from NODE, in case
728 NODE was redefined whilst collecting arguments. */
729 bool
730 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
732 if (argc == macro->paramc)
733 return true;
735 if (argc < macro->paramc)
737 /* As an extension, variadic arguments are allowed to not appear in
738 the invocation at all.
739 e.g. #define debug(format, args...) something
740 debug("string");
742 This is exactly the same as if an empty variadic list had been
743 supplied - debug("string", ). */
745 if (argc + 1 == macro->paramc && macro->variadic)
747 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
749 if (CPP_OPTION (pfile, cplusplus))
750 cpp_error (pfile, CPP_DL_PEDWARN,
751 "ISO C++11 requires at least one argument "
752 "for the \"...\" in a variadic macro");
753 else
754 cpp_error (pfile, CPP_DL_PEDWARN,
755 "ISO C99 requires at least one argument "
756 "for the \"...\" in a variadic macro");
758 return true;
761 cpp_error (pfile, CPP_DL_ERROR,
762 "macro \"%s\" requires %u arguments, but only %u given",
763 NODE_NAME (node), macro->paramc, argc);
765 else
766 cpp_error (pfile, CPP_DL_ERROR,
767 "macro \"%s\" passed %u arguments, but takes just %u",
768 NODE_NAME (node), argc, macro->paramc);
770 return false;
773 /* Reads and returns the arguments to a function-like macro
774 invocation. Assumes the opening parenthesis has been processed.
775 If there is an error, emits an appropriate diagnostic and returns
776 NULL. Each argument is terminated by a CPP_EOF token, for the
777 future benefit of expand_arg(). If there are any deferred
778 #pragma directives among macro arguments, store pointers to the
779 CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
781 What is returned is the buffer that contains the memory allocated
782 to hold the macro arguments. NODE is the name of the macro this
783 function is dealing with. If NUM_ARGS is non-NULL, *NUM_ARGS is
784 set to the actual number of macro arguments allocated in the
785 returned buffer. */
786 static _cpp_buff *
787 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
788 _cpp_buff **pragma_buff, unsigned *num_args)
790 _cpp_buff *buff, *base_buff;
791 cpp_macro *macro;
792 macro_arg *args, *arg;
793 const cpp_token *token;
794 unsigned int argc;
795 source_location virt_loc;
796 bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
797 unsigned num_args_alloced = 0;
799 macro = node->value.macro;
800 if (macro->paramc)
801 argc = macro->paramc;
802 else
803 argc = 1;
805 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
806 #define ARG_TOKENS_EXTENT 1000
808 buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
809 * sizeof (cpp_token *)
810 + sizeof (macro_arg)));
811 base_buff = buff;
812 args = (macro_arg *) buff->base;
813 memset (args, 0, argc * sizeof (macro_arg));
814 buff->cur = (unsigned char *) &args[argc];
815 arg = args, argc = 0;
817 /* Collect the tokens making up each argument. We don't yet know
818 how many arguments have been supplied, whether too many or too
819 few. Hence the slightly bizarre usage of "argc" and "arg". */
822 unsigned int paren_depth = 0;
823 unsigned int ntokens = 0;
824 unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
825 num_args_alloced++;
827 argc++;
828 arg->first = (const cpp_token **) buff->cur;
829 if (track_macro_expansion_p)
831 virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
832 arg->virt_locs = XNEWVEC (source_location,
833 virt_locs_capacity);
836 for (;;)
838 /* Require space for 2 new tokens (including a CPP_EOF). */
839 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
841 buff = _cpp_append_extend_buff (pfile, buff,
842 ARG_TOKENS_EXTENT
843 * sizeof (cpp_token *));
844 arg->first = (const cpp_token **) buff->cur;
846 if (track_macro_expansion_p
847 && (ntokens + 2 > virt_locs_capacity))
849 virt_locs_capacity += ARG_TOKENS_EXTENT;
850 arg->virt_locs = XRESIZEVEC (source_location,
851 arg->virt_locs,
852 virt_locs_capacity);
855 token = cpp_get_token_1 (pfile, &virt_loc);
857 if (token->type == CPP_PADDING)
859 /* Drop leading padding. */
860 if (ntokens == 0)
861 continue;
863 else if (token->type == CPP_OPEN_PAREN)
864 paren_depth++;
865 else if (token->type == CPP_CLOSE_PAREN)
867 if (paren_depth-- == 0)
868 break;
870 else if (token->type == CPP_COMMA)
872 /* A comma does not terminate an argument within
873 parentheses or as part of a variable argument. */
874 if (paren_depth == 0
875 && ! (macro->variadic && argc == macro->paramc))
876 break;
878 else if (token->type == CPP_EOF
879 || (token->type == CPP_HASH && token->flags & BOL))
880 break;
881 else if (token->type == CPP_PRAGMA)
883 cpp_token *newtok = _cpp_temp_token (pfile);
885 /* CPP_PRAGMA token lives in directive_result, which will
886 be overwritten on the next directive. */
887 *newtok = *token;
888 token = newtok;
891 if (*pragma_buff == NULL
892 || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
894 _cpp_buff *next;
895 if (*pragma_buff == NULL)
896 *pragma_buff
897 = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
898 else
900 next = *pragma_buff;
901 *pragma_buff
902 = _cpp_get_buff (pfile,
903 (BUFF_FRONT (*pragma_buff)
904 - (*pragma_buff)->base) * 2);
905 (*pragma_buff)->next = next;
908 *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
909 BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
910 if (token->type == CPP_PRAGMA_EOL)
911 break;
912 token = cpp_get_token_1 (pfile, &virt_loc);
914 while (token->type != CPP_EOF);
916 /* In deferred pragmas parsing_args and prevent_expansion
917 had been changed, reset it. */
918 pfile->state.parsing_args = 2;
919 pfile->state.prevent_expansion = 1;
921 if (token->type == CPP_EOF)
922 break;
923 else
924 continue;
926 set_arg_token (arg, token, virt_loc,
927 ntokens, MACRO_ARG_TOKEN_NORMAL,
928 CPP_OPTION (pfile, track_macro_expansion));
929 ntokens++;
932 /* Drop trailing padding. */
933 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
934 ntokens--;
936 arg->count = ntokens;
937 set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
938 ntokens, MACRO_ARG_TOKEN_NORMAL,
939 CPP_OPTION (pfile, track_macro_expansion));
941 /* Terminate the argument. Excess arguments loop back and
942 overwrite the final legitimate argument, before failing. */
943 if (argc <= macro->paramc)
945 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
946 if (argc != macro->paramc)
947 arg++;
950 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
952 if (token->type == CPP_EOF)
954 /* We still need the CPP_EOF to end directives, and to end
955 pre-expansion of a macro argument. Step back is not
956 unconditional, since we don't want to return a CPP_EOF to our
957 callers at the end of an -include-d file. */
958 if (pfile->context->prev || pfile->state.in_directive)
959 _cpp_backup_tokens (pfile, 1);
960 cpp_error (pfile, CPP_DL_ERROR,
961 "unterminated argument list invoking macro \"%s\"",
962 NODE_NAME (node));
964 else
966 /* A single empty argument is counted as no argument. */
967 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
968 argc = 0;
969 if (_cpp_arguments_ok (pfile, macro, node, argc))
971 /* GCC has special semantics for , ## b where b is a varargs
972 parameter: we remove the comma if b was omitted entirely.
973 If b was merely an empty argument, the comma is retained.
974 If the macro takes just one (varargs) parameter, then we
975 retain the comma only if we are standards conforming.
977 If FIRST is NULL replace_args () swallows the comma. */
978 if (macro->variadic && (argc < macro->paramc
979 || (argc == 1 && args[0].count == 0
980 && !CPP_OPTION (pfile, std))))
981 args[macro->paramc - 1].first = NULL;
982 if (num_args)
983 *num_args = num_args_alloced;
984 return base_buff;
988 /* An error occurred. */
989 _cpp_release_buff (pfile, base_buff);
990 return NULL;
993 /* Search for an opening parenthesis to the macro of NODE, in such a
994 way that, if none is found, we don't lose the information in any
995 intervening padding tokens. If we find the parenthesis, collect
996 the arguments and return the buffer containing them. PRAGMA_BUFF
997 argument is the same as in collect_args. If NUM_ARGS is non-NULL,
998 *NUM_ARGS is set to the number of arguments contained in the
999 returned buffer. */
1000 static _cpp_buff *
1001 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
1002 _cpp_buff **pragma_buff, unsigned *num_args)
1004 const cpp_token *token, *padding = NULL;
1006 for (;;)
1008 token = cpp_get_token (pfile);
1009 if (token->type != CPP_PADDING)
1010 break;
1011 if (padding == NULL
1012 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
1013 padding = token;
1016 if (token->type == CPP_OPEN_PAREN)
1018 pfile->state.parsing_args = 2;
1019 return collect_args (pfile, node, pragma_buff, num_args);
1022 /* CPP_EOF can be the end of macro arguments, or the end of the
1023 file. We mustn't back up over the latter. Ugh. */
1024 if (token->type != CPP_EOF || token == &pfile->eof)
1026 /* Back up. We may have skipped padding, in which case backing
1027 up more than one token when expanding macros is in general
1028 too difficult. We re-insert it in its own context. */
1029 _cpp_backup_tokens (pfile, 1);
1030 if (padding)
1031 _cpp_push_token_context (pfile, NULL, padding, 1);
1034 return NULL;
1037 /* Return the real number of tokens in the expansion of MACRO. */
1038 static inline unsigned int
1039 macro_real_token_count (const cpp_macro *macro)
1041 unsigned int i;
1042 if (__builtin_expect (!macro->extra_tokens, true))
1043 return macro->count;
1044 for (i = 0; i < macro->count; i++)
1045 if (macro->exp.tokens[i].type == CPP_PASTE)
1046 return i;
1047 abort ();
1050 /* Push the context of a macro with hash entry NODE onto the context
1051 stack. If we can successfully expand the macro, we push a context
1052 containing its yet-to-be-rescanned replacement list and return one.
1053 If there were additionally any unexpanded deferred #pragma
1054 directives among macro arguments, push another context containing
1055 the pragma tokens before the yet-to-be-rescanned replacement list
1056 and return two. Otherwise, we don't push a context and return
1057 zero. LOCATION is the location of the expansion point of the
1058 macro. */
1059 static int
1060 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1061 const cpp_token *result, source_location location)
1063 /* The presence of a macro invalidates a file's controlling macro. */
1064 pfile->mi_valid = false;
1066 pfile->state.angled_headers = false;
1068 /* From here to when we push the context for the macro later down
1069 this function, we need to flag the fact that we are about to
1070 expand a macro. This is useful when -ftrack-macro-expansion is
1071 turned off. In that case, we need to record the location of the
1072 expansion point of the top-most macro we are about to to expand,
1073 into pfile->invocation_location. But we must not record any such
1074 location once the process of expanding the macro starts; that is,
1075 we must not do that recording between now and later down this
1076 function where set this flag to FALSE. */
1077 pfile->about_to_expand_macro_p = true;
1079 if ((node->flags & NODE_BUILTIN) && !(node->flags & NODE_USED))
1081 node->flags |= NODE_USED;
1082 if ((!pfile->cb.user_builtin_macro
1083 || !pfile->cb.user_builtin_macro (pfile, node))
1084 && pfile->cb.used_define)
1085 pfile->cb.used_define (pfile, pfile->directive_line, node);
1088 /* Handle standard macros. */
1089 if (! (node->flags & NODE_BUILTIN))
1091 cpp_macro *macro = node->value.macro;
1092 _cpp_buff *pragma_buff = NULL;
1094 if (macro->fun_like)
1096 _cpp_buff *buff;
1097 unsigned num_args = 0;
1099 pfile->state.prevent_expansion++;
1100 pfile->keep_tokens++;
1101 pfile->state.parsing_args = 1;
1102 buff = funlike_invocation_p (pfile, node, &pragma_buff,
1103 &num_args);
1104 pfile->state.parsing_args = 0;
1105 pfile->keep_tokens--;
1106 pfile->state.prevent_expansion--;
1108 if (buff == NULL)
1110 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1111 cpp_warning (pfile, CPP_W_TRADITIONAL,
1112 "function-like macro \"%s\" must be used with arguments in traditional C",
1113 NODE_NAME (node));
1115 if (pragma_buff)
1116 _cpp_release_buff (pfile, pragma_buff);
1118 pfile->about_to_expand_macro_p = false;
1119 return 0;
1122 if (macro->paramc > 0)
1123 replace_args (pfile, node, macro,
1124 (macro_arg *) buff->base,
1125 location);
1126 /* Free the memory used by the arguments of this
1127 function-like macro. This memory has been allocated by
1128 funlike_invocation_p and by replace_args. */
1129 delete_macro_args (buff, num_args);
1132 /* Disable the macro within its expansion. */
1133 node->flags |= NODE_DISABLED;
1135 if (!(node->flags & NODE_USED))
1137 node->flags |= NODE_USED;
1138 if (pfile->cb.used_define)
1139 pfile->cb.used_define (pfile, pfile->directive_line, node);
1142 if (pfile->cb.used)
1143 pfile->cb.used (pfile, location, node);
1145 macro->used = 1;
1147 if (macro->paramc == 0)
1149 unsigned tokens_count = macro_real_token_count (macro);
1150 if (CPP_OPTION (pfile, track_macro_expansion))
1152 unsigned int i;
1153 const cpp_token *src = macro->exp.tokens;
1154 const struct line_map *map;
1155 source_location *virt_locs = NULL;
1156 _cpp_buff *macro_tokens
1157 = tokens_buff_new (pfile, tokens_count, &virt_locs);
1159 /* Create a macro map to record the locations of the
1160 tokens that are involved in the expansion. LOCATION
1161 is the location of the macro expansion point. */
1162 map = linemap_enter_macro (pfile->line_table,
1163 node, location, tokens_count);
1164 for (i = 0; i < tokens_count; ++i)
1166 tokens_buff_add_token (macro_tokens, virt_locs,
1167 src, src->src_loc,
1168 src->src_loc, map, i);
1169 ++src;
1171 push_extended_tokens_context (pfile, node,
1172 macro_tokens,
1173 virt_locs,
1174 (const cpp_token **)
1175 macro_tokens->base,
1176 tokens_count);
1178 else
1179 _cpp_push_token_context (pfile, node, macro->exp.tokens,
1180 tokens_count);
1181 num_macro_tokens_counter += tokens_count;
1184 if (pragma_buff)
1186 if (!pfile->state.in_directive)
1187 _cpp_push_token_context (pfile, NULL,
1188 padding_token (pfile, result), 1);
1191 unsigned tokens_count;
1192 _cpp_buff *tail = pragma_buff->next;
1193 pragma_buff->next = NULL;
1194 tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1195 - (const cpp_token **) pragma_buff->base);
1196 push_ptoken_context (pfile, NULL, pragma_buff,
1197 (const cpp_token **) pragma_buff->base,
1198 tokens_count);
1199 pragma_buff = tail;
1200 if (!CPP_OPTION (pfile, track_macro_expansion))
1201 num_macro_tokens_counter += tokens_count;
1204 while (pragma_buff != NULL);
1205 pfile->about_to_expand_macro_p = false;
1206 return 2;
1209 pfile->about_to_expand_macro_p = false;
1210 return 1;
1213 pfile->about_to_expand_macro_p = false;
1214 /* Handle built-in macros and the _Pragma operator. */
1215 return builtin_macro (pfile, node);
1218 /* De-allocate the memory used by BUFF which is an array of instances
1219 of macro_arg. NUM_ARGS is the number of instances of macro_arg
1220 present in BUFF. */
1221 static void
1222 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1224 macro_arg *macro_args;
1225 unsigned i;
1227 if (buff == NULL)
1228 return;
1230 macro_args = (macro_arg *) buff->base;
1232 /* Walk instances of macro_arg to free their expanded tokens as well
1233 as their macro_arg::virt_locs members. */
1234 for (i = 0; i < num_args; ++i)
1236 if (macro_args[i].expanded)
1238 free (macro_args[i].expanded);
1239 macro_args[i].expanded = NULL;
1241 if (macro_args[i].virt_locs)
1243 free (macro_args[i].virt_locs);
1244 macro_args[i].virt_locs = NULL;
1246 if (macro_args[i].expanded_virt_locs)
1248 free (macro_args[i].expanded_virt_locs);
1249 macro_args[i].expanded_virt_locs = NULL;
1252 _cpp_free_buff (buff);
1255 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1256 to set, LOCATION is its virtual location. "Virtual" location means
1257 the location that encodes loci across macro expansion. Otherwise
1258 it has to be TOKEN->SRC_LOC. KIND is the kind of tokens the
1259 argument ARG is supposed to contain. Note that ARG must be
1260 tailored so that it has enough room to contain INDEX + 1 numbers of
1261 tokens, at least. */
1262 static void
1263 set_arg_token (macro_arg *arg, const cpp_token *token,
1264 source_location location, size_t index,
1265 enum macro_arg_token_kind kind,
1266 bool track_macro_exp_p)
1268 const cpp_token **token_ptr;
1269 source_location *loc = NULL;
1271 token_ptr =
1272 arg_token_ptr_at (arg, index, kind,
1273 track_macro_exp_p ? &loc : NULL);
1274 *token_ptr = token;
1276 if (loc != NULL)
1278 #ifdef ENABLE_CHECKING
1279 if (kind == MACRO_ARG_TOKEN_STRINGIFIED
1280 || !track_macro_exp_p)
1281 /* We can't set the location of a stringified argument
1282 token and we can't set any location if we aren't tracking
1283 macro expansion locations. */
1284 abort ();
1285 #endif
1286 *loc = location;
1290 /* Get the pointer to the location of the argument token of the
1291 function-like macro argument ARG. This function must be called
1292 only when we -ftrack-macro-expansion is on. */
1293 static const source_location *
1294 get_arg_token_location (const macro_arg *arg,
1295 enum macro_arg_token_kind kind)
1297 const source_location *loc = NULL;
1298 const cpp_token **token_ptr =
1299 arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1301 if (token_ptr == NULL)
1302 return NULL;
1304 return loc;
1307 /* Return the pointer to the INDEXth token of the macro argument ARG.
1308 KIND specifies the kind of token the macro argument ARG contains.
1309 If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1310 of the virtual location of the returned token if the
1311 -ftrack-macro-expansion flag is on; otherwise, it's set to the
1312 spelling location of the returned token. */
1313 static const cpp_token **
1314 arg_token_ptr_at (const macro_arg *arg, size_t index,
1315 enum macro_arg_token_kind kind,
1316 source_location **virt_location)
1318 const cpp_token **tokens_ptr = NULL;
1320 switch (kind)
1322 case MACRO_ARG_TOKEN_NORMAL:
1323 tokens_ptr = arg->first;
1324 break;
1325 case MACRO_ARG_TOKEN_STRINGIFIED:
1326 tokens_ptr = (const cpp_token **) &arg->stringified;
1327 break;
1328 case MACRO_ARG_TOKEN_EXPANDED:
1329 tokens_ptr = arg->expanded;
1330 break;
1333 if (tokens_ptr == NULL)
1334 /* This can happen for e.g, an empty token argument to a
1335 funtion-like macro. */
1336 return tokens_ptr;
1338 if (virt_location)
1340 if (kind == MACRO_ARG_TOKEN_NORMAL)
1341 *virt_location = &arg->virt_locs[index];
1342 else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1343 *virt_location = &arg->expanded_virt_locs[index];
1344 else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1345 *virt_location =
1346 (source_location *) &tokens_ptr[index]->src_loc;
1348 return &tokens_ptr[index];
1351 /* Initialize an iterator so that it iterates over the tokens of a
1352 function-like macro argument. KIND is the kind of tokens we want
1353 ITER to iterate over. TOKEN_PTR points the first token ITER will
1354 iterate over. */
1355 static void
1356 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1357 bool track_macro_exp_p,
1358 enum macro_arg_token_kind kind,
1359 const macro_arg *arg,
1360 const cpp_token **token_ptr)
1362 iter->track_macro_exp_p = track_macro_exp_p;
1363 iter->kind = kind;
1364 iter->token_ptr = token_ptr;
1365 /* Unconditionally initialize this so that the compiler doesn't warn
1366 about iter->location_ptr being possibly uninitialized later after
1367 this code has been inlined somewhere. */
1368 iter->location_ptr = NULL;
1369 if (track_macro_exp_p)
1370 iter->location_ptr = get_arg_token_location (arg, kind);
1371 #ifdef ENABLE_CHECKING
1372 iter->num_forwards = 0;
1373 if (track_macro_exp_p
1374 && token_ptr != NULL
1375 && iter->location_ptr == NULL)
1376 abort ();
1377 #endif
1380 /* Move the iterator one token forward. Note that if IT was
1381 initialized on an argument that has a stringified token, moving it
1382 forward doesn't make sense as a stringified token is essentially one
1383 string. */
1384 static void
1385 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1387 switch (it->kind)
1389 case MACRO_ARG_TOKEN_NORMAL:
1390 case MACRO_ARG_TOKEN_EXPANDED:
1391 it->token_ptr++;
1392 if (it->track_macro_exp_p)
1393 it->location_ptr++;
1394 break;
1395 case MACRO_ARG_TOKEN_STRINGIFIED:
1396 #ifdef ENABLE_CHECKING
1397 if (it->num_forwards > 0)
1398 abort ();
1399 #endif
1400 break;
1403 #ifdef ENABLE_CHECKING
1404 it->num_forwards++;
1405 #endif
1408 /* Return the token pointed to by the iterator. */
1409 static const cpp_token *
1410 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1412 #ifdef ENABLE_CHECKING
1413 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1414 && it->num_forwards > 0)
1415 abort ();
1416 #endif
1417 if (it->token_ptr == NULL)
1418 return NULL;
1419 return *it->token_ptr;
1422 /* Return the location of the token pointed to by the iterator.*/
1423 static source_location
1424 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1426 #ifdef ENABLE_CHECKING
1427 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1428 && it->num_forwards > 0)
1429 abort ();
1430 #endif
1431 if (it->track_macro_exp_p)
1432 return *it->location_ptr;
1433 else
1434 return (*it->token_ptr)->src_loc;
1437 /* Return the index of a token [resulting from macro expansion] inside
1438 the total list of tokens resulting from a given macro
1439 expansion. The index can be different depending on whether if we
1440 want each tokens resulting from function-like macro arguments
1441 expansion to have a different location or not.
1443 E.g, consider this function-like macro:
1445 #define M(x) x - 3
1447 Then consider us "calling" it (and thus expanding it) like:
1449 M(1+4)
1451 It will be expanded into:
1453 1+4-3
1455 Let's consider the case of the token '4'.
1457 Its index can be 2 (it's the third token of the set of tokens
1458 resulting from the expansion) or it can be 0 if we consider that
1459 all tokens resulting from the expansion of the argument "1+2" have
1460 the same index, which is 0. In this later case, the index of token
1461 '-' would then be 1 and the index of token '3' would be 2.
1463 The later case is useful to use less memory e.g, for the case of
1464 the user using the option -ftrack-macro-expansion=1.
1466 ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1467 are interested in. CUR_REPLACEMENT_TOKEN is the token of the macro
1468 parameter (inside the macro replacement list) that corresponds to
1469 the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1472 If we refer to the example above, for the '4' argument token,
1473 ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1474 would be set to the token 'x', in the replacement list "x - 3" of
1475 macro M.
1477 This is a subroutine of replace_args. */
1478 inline static unsigned
1479 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1480 const cpp_token *cur_replacement_token,
1481 unsigned absolute_token_index)
1483 if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1484 return absolute_token_index;
1485 return cur_replacement_token - macro->exp.tokens;
1488 /* Replace the parameters in a function-like macro of NODE with the
1489 actual ARGS, and place the result in a newly pushed token context.
1490 Expand each argument before replacing, unless it is operated upon
1491 by the # or ## operators. EXPANSION_POINT_LOC is the location of
1492 the expansion point of the macro. E.g, the location of the
1493 function-like macro invocation. */
1494 static void
1495 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1496 macro_arg *args, source_location expansion_point_loc)
1498 unsigned int i, total;
1499 const cpp_token *src, *limit;
1500 const cpp_token **first = NULL;
1501 macro_arg *arg;
1502 _cpp_buff *buff = NULL;
1503 source_location *virt_locs = NULL;
1504 unsigned int exp_count;
1505 const struct line_map *map = NULL;
1506 int track_macro_exp;
1508 /* First, fully macro-expand arguments, calculating the number of
1509 tokens in the final expansion as we go. The ordering of the if
1510 statements below is subtle; we must handle stringification before
1511 pasting. */
1513 /* EXP_COUNT is the number of tokens in the macro replacement
1514 list. TOTAL is the number of tokens /after/ macro parameters
1515 have been replaced by their arguments. */
1516 exp_count = macro_real_token_count (macro);
1517 total = exp_count;
1518 limit = macro->exp.tokens + exp_count;
1520 for (src = macro->exp.tokens; src < limit; src++)
1521 if (src->type == CPP_MACRO_ARG)
1523 /* Leading and trailing padding tokens. */
1524 total += 2;
1525 /* Account for leading and padding tokens in exp_count too.
1526 This is going to be important later down this function,
1527 when we want to handle the case of (track_macro_exp <
1528 2). */
1529 exp_count += 2;
1531 /* We have an argument. If it is not being stringified or
1532 pasted it is macro-replaced before insertion. */
1533 arg = &args[src->val.macro_arg.arg_no - 1];
1535 if (src->flags & STRINGIFY_ARG)
1537 if (!arg->stringified)
1538 arg->stringified = stringify_arg (pfile, arg);
1540 else if ((src->flags & PASTE_LEFT)
1541 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1542 total += arg->count - 1;
1543 else
1545 if (!arg->expanded)
1546 expand_arg (pfile, arg);
1547 total += arg->expanded_count - 1;
1551 /* When the compiler is called with the -ftrack-macro-expansion
1552 flag, we need to keep track of the location of each token that
1553 results from macro expansion.
1555 A token resulting from macro expansion is not a new token. It is
1556 simply the same token as the token coming from the macro
1557 definition. The new things that are allocated are the buffer
1558 that holds the tokens resulting from macro expansion and a new
1559 location that records many things like the locus of the expansion
1560 point as well as the original locus inside the definition of the
1561 macro. This location is called a virtual location.
1563 So the buffer BUFF holds a set of cpp_token*, and the buffer
1564 VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1566 Both of these two buffers are going to be hung off of the macro
1567 context, when the latter is pushed. The memory allocated to
1568 store the tokens and their locations is going to be freed once
1569 the context of macro expansion is popped.
1571 As far as tokens are concerned, the memory overhead of
1572 -ftrack-macro-expansion is proportional to the number of
1573 macros that get expanded multiplied by sizeof (source_location).
1574 The good news is that extra memory gets freed when the macro
1575 context is freed, i.e shortly after the macro got expanded. */
1577 /* Is the -ftrack-macro-expansion flag in effect? */
1578 track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1580 /* Now allocate memory space for tokens and locations resulting from
1581 the macro expansion, copy the tokens and replace the arguments.
1582 This memory must be freed when the context of the macro MACRO is
1583 popped. */
1584 buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1586 first = (const cpp_token **) buff->base;
1588 /* Create a macro map to record the locations of the tokens that are
1589 involved in the expansion. Note that the expansion point is set
1590 to the location of the closing parenthesis. Otherwise, the
1591 subsequent map created for the first token that comes after the
1592 macro map might have a wrong line number. That would lead to
1593 tokens with wrong line numbers after the macro expansion. This
1594 adds up to the memory overhead of the -ftrack-macro-expansion
1595 flag; for every macro that is expanded, a "macro map" is
1596 created. */
1597 if (track_macro_exp)
1599 int num_macro_tokens = total;
1600 if (track_macro_exp < 2)
1601 /* Then the number of macro tokens won't take in account the
1602 fact that function-like macro arguments can expand to
1603 multiple tokens. This is to save memory at the expense of
1604 accuracy.
1606 Suppose we have #define SQARE(A) A * A
1608 And then we do SQARE(2+3)
1610 Then the tokens 2, +, 3, will have the same location,
1611 saying they come from the expansion of the argument A. */
1612 num_macro_tokens = exp_count;
1613 map = linemap_enter_macro (pfile->line_table, node,
1614 expansion_point_loc,
1615 num_macro_tokens);
1617 i = 0;
1618 for (src = macro->exp.tokens; src < limit; src++)
1620 unsigned int arg_tokens_count;
1621 macro_arg_token_iter from;
1622 const cpp_token **paste_flag = NULL;
1623 const cpp_token **tmp_token_ptr;
1625 if (src->type != CPP_MACRO_ARG)
1627 /* Allocate a virtual location for token SRC, and add that
1628 token and its virtual location into the buffers BUFF and
1629 VIRT_LOCS. */
1630 unsigned index = expanded_token_index (pfile, macro, src, i);
1631 tokens_buff_add_token (buff, virt_locs, src,
1632 src->src_loc, src->src_loc,
1633 map, index);
1634 i += 1;
1635 continue;
1638 paste_flag = 0;
1639 arg = &args[src->val.macro_arg.arg_no - 1];
1640 /* SRC is a macro parameter that we need to replace with its
1641 corresponding argument. So at some point we'll need to
1642 iterate over the tokens of the macro argument and copy them
1643 into the "place" now holding the correspondig macro
1644 parameter. We are going to use the iterator type
1645 macro_argo_token_iter to handle that iterating. The 'if'
1646 below is to initialize the iterator depending on the type of
1647 tokens the macro argument has. It also does some adjustment
1648 related to padding tokens and some pasting corner cases. */
1649 if (src->flags & STRINGIFY_ARG)
1651 arg_tokens_count = 1;
1652 macro_arg_token_iter_init (&from,
1653 CPP_OPTION (pfile,
1654 track_macro_expansion),
1655 MACRO_ARG_TOKEN_STRINGIFIED,
1656 arg, &arg->stringified);
1658 else if (src->flags & PASTE_LEFT)
1660 arg_tokens_count = arg->count;
1661 macro_arg_token_iter_init (&from,
1662 CPP_OPTION (pfile,
1663 track_macro_expansion),
1664 MACRO_ARG_TOKEN_NORMAL,
1665 arg, arg->first);
1667 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1669 int num_toks;
1670 arg_tokens_count = arg->count;
1671 macro_arg_token_iter_init (&from,
1672 CPP_OPTION (pfile,
1673 track_macro_expansion),
1674 MACRO_ARG_TOKEN_NORMAL,
1675 arg, arg->first);
1677 num_toks = tokens_buff_count (buff);
1679 if (num_toks != 0)
1681 /* So the current parameter token is pasted to the previous
1682 token in the replacement list. Let's look at what
1683 we have as previous and current arguments. */
1685 /* This is the previous argument's token ... */
1686 tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1688 if ((*tmp_token_ptr)->type == CPP_COMMA
1689 && macro->variadic
1690 && src->val.macro_arg.arg_no == macro->paramc)
1692 /* ... which is a comma; and the current parameter
1693 is the last parameter of a variadic function-like
1694 macro. If the argument to the current last
1695 parameter is NULL, then swallow the comma,
1696 otherwise drop the paste flag. */
1697 if (macro_arg_token_iter_get_token (&from) == NULL)
1698 tokens_buff_remove_last_token (buff);
1699 else
1700 paste_flag = tmp_token_ptr;
1702 /* Remove the paste flag if the RHS is a placemarker. */
1703 else if (arg_tokens_count == 0)
1704 paste_flag = tmp_token_ptr;
1707 else
1709 arg_tokens_count = arg->expanded_count;
1710 macro_arg_token_iter_init (&from,
1711 CPP_OPTION (pfile,
1712 track_macro_expansion),
1713 MACRO_ARG_TOKEN_EXPANDED,
1714 arg, arg->expanded);
1717 /* Padding on the left of an argument (unless RHS of ##). */
1718 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1719 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1721 const cpp_token *t = padding_token (pfile, src);
1722 unsigned index = expanded_token_index (pfile, macro, src, i);
1723 /* Allocate a virtual location for the padding token and
1724 append the token and its location to BUFF and
1725 VIRT_LOCS. */
1726 tokens_buff_add_token (buff, virt_locs, t,
1727 t->src_loc, t->src_loc,
1728 map, index);
1731 if (arg_tokens_count)
1733 /* So now we've got the number of tokens that make up the
1734 argument that is going to replace the current parameter
1735 in the macro's replacement list. */
1736 unsigned int j;
1737 for (j = 0; j < arg_tokens_count; ++j)
1739 /* So if track_macro_exp is < 2, the user wants to
1740 save extra memory while tracking macro expansion
1741 locations. So in that case here is what we do:
1743 Suppose we have #define SQARE(A) A * A
1745 And then we do SQARE(2+3)
1747 Then the tokens 2, +, 3, will have the same location,
1748 saying they come from the expansion of the argument
1751 So that means we are going to ignore the COUNT tokens
1752 resulting from the expansion of the current macro
1753 arugment. In other words all the ARG_TOKENS_COUNT tokens
1754 resulting from the expansion of the macro argument will
1755 have the index I. Normally, each of those token should
1756 have index I+J. */
1757 unsigned token_index = i;
1758 unsigned index;
1759 if (track_macro_exp > 1)
1760 token_index += j;
1762 index = expanded_token_index (pfile, macro, src, token_index);
1763 tokens_buff_add_token (buff, virt_locs,
1764 macro_arg_token_iter_get_token (&from),
1765 macro_arg_token_iter_get_location (&from),
1766 src->src_loc, map, index);
1767 macro_arg_token_iter_forward (&from);
1770 /* With a non-empty argument on the LHS of ##, the last
1771 token should be flagged PASTE_LEFT. */
1772 if (src->flags & PASTE_LEFT)
1773 paste_flag =
1774 (const cpp_token **) tokens_buff_last_token_ptr (buff);
1776 else if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1777 && ! CPP_OPTION (pfile, c99)
1778 && ! cpp_in_system_header (pfile))
1780 if (CPP_OPTION (pfile, cplusplus))
1781 cpp_error (pfile, CPP_DL_PEDWARN,
1782 "invoking macro %s argument %d: "
1783 "empty macro arguments are undefined"
1784 " in ISO C++98",
1785 NODE_NAME (node),
1786 src->val.macro_arg.arg_no);
1787 else
1788 cpp_error (pfile, CPP_DL_PEDWARN,
1789 "invoking macro %s argument %d: "
1790 "empty macro arguments are undefined"
1791 " in ISO C90",
1792 NODE_NAME (node),
1793 src->val.macro_arg.arg_no);
1796 /* Avoid paste on RHS (even case count == 0). */
1797 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
1799 const cpp_token *t = &pfile->avoid_paste;
1800 tokens_buff_add_token (buff, virt_locs,
1801 t, t->src_loc, t->src_loc,
1802 NULL, 0);
1805 /* Add a new paste flag, or remove an unwanted one. */
1806 if (paste_flag)
1808 cpp_token *token = _cpp_temp_token (pfile);
1809 token->type = (*paste_flag)->type;
1810 token->val = (*paste_flag)->val;
1811 if (src->flags & PASTE_LEFT)
1812 token->flags = (*paste_flag)->flags | PASTE_LEFT;
1813 else
1814 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1815 *paste_flag = token;
1818 i += arg_tokens_count;
1821 if (track_macro_exp)
1822 push_extended_tokens_context (pfile, node, buff, virt_locs, first,
1823 tokens_buff_count (buff));
1824 else
1825 push_ptoken_context (pfile, node, buff, first,
1826 tokens_buff_count (buff));
1828 num_macro_tokens_counter += tokens_buff_count (buff);
1831 /* Return a special padding token, with padding inherited from SOURCE. */
1832 static const cpp_token *
1833 padding_token (cpp_reader *pfile, const cpp_token *source)
1835 cpp_token *result = _cpp_temp_token (pfile);
1837 result->type = CPP_PADDING;
1839 /* Data in GCed data structures cannot be made const so far, so we
1840 need a cast here. */
1841 result->val.source = (cpp_token *) source;
1842 result->flags = 0;
1843 return result;
1846 /* Get a new uninitialized context. Create a new one if we cannot
1847 re-use an old one. */
1848 static cpp_context *
1849 next_context (cpp_reader *pfile)
1851 cpp_context *result = pfile->context->next;
1853 if (result == 0)
1855 result = XNEW (cpp_context);
1856 memset (result, 0, sizeof (cpp_context));
1857 result->prev = pfile->context;
1858 result->next = 0;
1859 pfile->context->next = result;
1862 pfile->context = result;
1863 return result;
1866 /* Push a list of pointers to tokens. */
1867 static void
1868 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
1869 const cpp_token **first, unsigned int count)
1871 cpp_context *context = next_context (pfile);
1873 context->tokens_kind = TOKENS_KIND_INDIRECT;
1874 context->c.macro = macro;
1875 context->buff = buff;
1876 FIRST (context).ptoken = first;
1877 LAST (context).ptoken = first + count;
1880 /* Push a list of tokens.
1882 A NULL macro means that we should continue the current macro
1883 expansion, in essence. That means that if we are currently in a
1884 macro expansion context, we'll make the new pfile->context refer to
1885 the current macro. */
1886 void
1887 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
1888 const cpp_token *first, unsigned int count)
1890 cpp_context *context;
1892 if (macro == NULL)
1893 macro = macro_of_context (pfile->context);
1895 context = next_context (pfile);
1896 context->tokens_kind = TOKENS_KIND_DIRECT;
1897 context->c.macro = macro;
1898 context->buff = NULL;
1899 FIRST (context).token = first;
1900 LAST (context).token = first + count;
1903 /* Build a context containing a list of tokens as well as their
1904 virtual locations and push it. TOKENS_BUFF is the buffer that
1905 contains the tokens pointed to by FIRST. If TOKENS_BUFF is
1906 non-NULL, it means that the context owns it, meaning that
1907 _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
1908 contains the virtual locations.
1910 A NULL macro means that we should continue the current macro
1911 expansion, in essence. That means that if we are currently in a
1912 macro expansion context, we'll make the new pfile->context refer to
1913 the current macro. */
1914 static void
1915 push_extended_tokens_context (cpp_reader *pfile,
1916 cpp_hashnode *macro,
1917 _cpp_buff *token_buff,
1918 source_location *virt_locs,
1919 const cpp_token **first,
1920 unsigned int count)
1922 cpp_context *context;
1923 macro_context *m;
1925 if (macro == NULL)
1926 macro = macro_of_context (pfile->context);
1928 context = next_context (pfile);
1929 context->tokens_kind = TOKENS_KIND_EXTENDED;
1930 context->buff = token_buff;
1932 m = XNEW (macro_context);
1933 m->macro_node = macro;
1934 m->virt_locs = virt_locs;
1935 m->cur_virt_loc = virt_locs;
1936 context->c.mc = m;
1937 FIRST (context).ptoken = first;
1938 LAST (context).ptoken = first + count;
1941 /* Push a traditional macro's replacement text. */
1942 void
1943 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
1944 const uchar *start, size_t len)
1946 cpp_context *context = next_context (pfile);
1948 context->tokens_kind = TOKENS_KIND_DIRECT;
1949 context->c.macro = macro;
1950 context->buff = NULL;
1951 CUR (context) = start;
1952 RLIMIT (context) = start + len;
1953 macro->flags |= NODE_DISABLED;
1956 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
1957 for the purpose of storing them on a cpp_context. If VIRT_LOCS is
1958 non-null (which means that -ftrack-macro-expansion is on),
1959 *VIRT_LOCS is set to a newly allocated buffer that is supposed to
1960 hold the virtual locations of the tokens resulting from macro
1961 expansion. */
1962 static _cpp_buff*
1963 tokens_buff_new (cpp_reader *pfile, size_t len,
1964 source_location **virt_locs)
1966 size_t tokens_size = len * sizeof (cpp_token *);
1967 size_t locs_size = len * sizeof (source_location);
1969 if (virt_locs != NULL)
1970 *virt_locs = XNEWVEC (source_location, locs_size);
1971 return _cpp_get_buff (pfile, tokens_size);
1974 /* Returns the number of tokens contained in a token buffer. The
1975 buffer holds a set of cpp_token*. */
1976 static size_t
1977 tokens_buff_count (_cpp_buff *buff)
1979 return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
1982 /* Return a pointer to the last token contained in the token buffer
1983 BUFF. */
1984 static const cpp_token **
1985 tokens_buff_last_token_ptr (_cpp_buff *buff)
1987 return &((const cpp_token **) BUFF_FRONT (buff))[-1];
1990 /* Remove the last token contained in the token buffer TOKENS_BUFF.
1991 If VIRT_LOCS_BUFF is non-NULL, it should point at the buffer
1992 containing the virtual locations of the tokens in TOKENS_BUFF; in
1993 which case the function updates that buffer as well. */
1994 static inline void
1995 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
1998 if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
1999 BUFF_FRONT (tokens_buff) =
2000 (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
2003 /* Insert a token into the token buffer at the position pointed to by
2004 DEST. Note that the buffer is not enlarged so the previous token
2005 that was at *DEST is overwritten. VIRT_LOC_DEST, if non-null,
2006 means -ftrack-macro-expansion is effect; it then points to where to
2007 insert the virtual location of TOKEN. TOKEN is the token to
2008 insert. VIRT_LOC is the virtual location of the token, i.e, the
2009 location possibly encoding its locus across macro expansion. If
2010 TOKEN is an argument of a function-like macro (inside a macro
2011 replacement list), PARM_DEF_LOC is the spelling location of the
2012 macro parameter that TOKEN is replacing, in the replacement list of
2013 the macro. If TOKEN is not an argument of a function-like macro or
2014 if it doesn't come from a macro expansion, then VIRT_LOC can just
2015 be set to the same value as PARM_DEF_LOC. If MAP is non null, it
2016 means TOKEN comes from a macro expansion and MAP is the macro map
2017 associated to the macro. MACRO_TOKEN_INDEX points to the index of
2018 the token in the macro map; it is not considered if MAP is NULL.
2020 Upon successful completion this function returns the a pointer to
2021 the position of the token coming right after the insertion
2022 point. */
2023 static inline const cpp_token **
2024 tokens_buff_put_token_to (const cpp_token **dest,
2025 source_location *virt_loc_dest,
2026 const cpp_token *token,
2027 source_location virt_loc,
2028 source_location parm_def_loc,
2029 const struct line_map *map,
2030 unsigned int macro_token_index)
2032 source_location macro_loc = virt_loc;
2033 const cpp_token **result;
2035 if (virt_loc_dest)
2037 /* -ftrack-macro-expansion is on. */
2038 if (map)
2039 macro_loc = linemap_add_macro_token (map, macro_token_index,
2040 virt_loc, parm_def_loc);
2041 *virt_loc_dest = macro_loc;
2043 *dest = token;
2044 result = &dest[1];
2046 return result;
2049 /* Adds a token at the end of the tokens contained in BUFFER. Note
2050 that this function doesn't enlarge BUFFER when the number of tokens
2051 reaches BUFFER's size; it aborts in that situation.
2053 TOKEN is the token to append. VIRT_LOC is the virtual location of
2054 the token, i.e, the location possibly encoding its locus across
2055 macro expansion. If TOKEN is an argument of a function-like macro
2056 (inside a macro replacement list), PARM_DEF_LOC is the location of
2057 the macro parameter that TOKEN is replacing. If TOKEN doesn't come
2058 from a macro expansion, then VIRT_LOC can just be set to the same
2059 value as PARM_DEF_LOC. If MAP is non null, it means TOKEN comes
2060 from a macro expansion and MAP is the macro map associated to the
2061 macro. MACRO_TOKEN_INDEX points to the index of the token in the
2062 macro map; It is not considered if MAP is NULL. If VIRT_LOCS is
2063 non-null, it means -ftrack-macro-expansion is on; in which case
2064 this function adds the virtual location DEF_LOC to the VIRT_LOCS
2065 array, at the same index as the one of TOKEN in BUFFER. Upon
2066 successful completion this function returns the a pointer to the
2067 position of the token coming right after the insertion point. */
2068 static const cpp_token **
2069 tokens_buff_add_token (_cpp_buff *buffer,
2070 source_location *virt_locs,
2071 const cpp_token *token,
2072 source_location virt_loc,
2073 source_location parm_def_loc,
2074 const struct line_map *map,
2075 unsigned int macro_token_index)
2077 const cpp_token **result;
2078 source_location *virt_loc_dest = NULL;
2079 unsigned token_index =
2080 (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2082 /* Abort if we pass the end the buffer. */
2083 if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2084 abort ();
2086 if (virt_locs != NULL)
2087 virt_loc_dest = &virt_locs[token_index];
2089 result =
2090 tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2091 virt_loc_dest, token, virt_loc, parm_def_loc,
2092 map, macro_token_index);
2094 BUFF_FRONT (buffer) = (unsigned char *) result;
2095 return result;
2098 /* Allocate space for the function-like macro argument ARG to store
2099 the tokens resulting from the macro-expansion of the tokens that
2100 make up ARG itself. That space is allocated in ARG->expanded and
2101 needs to be freed using free. */
2102 static void
2103 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2105 #ifdef ENABLE_CHECKING
2106 if (arg->expanded != NULL
2107 || arg->expanded_virt_locs != NULL)
2108 abort ();
2109 #endif
2110 arg->expanded = XNEWVEC (const cpp_token *, capacity);
2111 if (CPP_OPTION (pfile, track_macro_expansion))
2112 arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2116 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2117 tokens. */
2118 static void
2119 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2120 size_t size, size_t *expanded_capacity)
2122 if (size <= *expanded_capacity)
2123 return;
2125 size *= 2;
2127 arg->expanded =
2128 XRESIZEVEC (const cpp_token *, arg->expanded, size);
2129 *expanded_capacity = size;
2131 if (CPP_OPTION (pfile, track_macro_expansion))
2133 if (arg->expanded_virt_locs == NULL)
2134 arg->expanded_virt_locs = XNEWVEC (source_location, size);
2135 else
2136 arg->expanded_virt_locs = XRESIZEVEC (source_location,
2137 arg->expanded_virt_locs,
2138 size);
2142 /* Expand an argument ARG before replacing parameters in a
2143 function-like macro. This works by pushing a context with the
2144 argument's tokens, and then expanding that into a temporary buffer
2145 as if it were a normal part of the token stream. collect_args()
2146 has terminated the argument's tokens with a CPP_EOF so that we know
2147 when we have fully expanded the argument. */
2148 static void
2149 expand_arg (cpp_reader *pfile, macro_arg *arg)
2151 size_t capacity;
2152 bool saved_warn_trad;
2153 bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2155 if (arg->count == 0
2156 || arg->expanded != NULL)
2157 return;
2159 /* Don't warn about funlike macros when pre-expanding. */
2160 saved_warn_trad = CPP_WTRADITIONAL (pfile);
2161 CPP_WTRADITIONAL (pfile) = 0;
2163 /* Loop, reading in the tokens of the argument. */
2164 capacity = 256;
2165 alloc_expanded_arg_mem (pfile, arg, capacity);
2167 if (track_macro_exp_p)
2168 push_extended_tokens_context (pfile, NULL, NULL,
2169 arg->virt_locs,
2170 arg->first,
2171 arg->count + 1);
2172 else
2173 push_ptoken_context (pfile, NULL, NULL,
2174 arg->first, arg->count + 1);
2176 for (;;)
2178 const cpp_token *token;
2179 source_location location;
2181 ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2182 &capacity);
2184 token = cpp_get_token_1 (pfile, &location);
2186 if (token->type == CPP_EOF)
2187 break;
2189 set_arg_token (arg, token, location,
2190 arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2191 CPP_OPTION (pfile, track_macro_expansion));
2192 arg->expanded_count++;
2195 _cpp_pop_context (pfile);
2197 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2200 /* Returns the macro associated to the current context if we are in
2201 the context a macro expansion, NULL otherwise. */
2202 static cpp_hashnode*
2203 macro_of_context (cpp_context *context)
2205 if (context == NULL)
2206 return NULL;
2208 return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2209 ? context->c.mc->macro_node
2210 : context->c.macro;
2213 /* Return TRUE iff we are expanding a macro or are about to start
2214 expanding one. If we are effectively expanding a macro, the
2215 function macro_of_context returns a pointer to the macro being
2216 expanded. */
2217 static bool
2218 in_macro_expansion_p (cpp_reader *pfile)
2220 if (pfile == NULL)
2221 return false;
2223 return (pfile->about_to_expand_macro_p
2224 || macro_of_context (pfile->context));
2227 /* Pop the current context off the stack, re-enabling the macro if the
2228 context represented a macro's replacement list. Initially the
2229 context structure was not freed so that we can re-use it later, but
2230 now we do free it to reduce peak memory consumption. */
2231 void
2232 _cpp_pop_context (cpp_reader *pfile)
2234 cpp_context *context = pfile->context;
2236 /* We should not be popping the base context. */
2237 if (context == &pfile->base_context)
2238 abort ();
2240 if (context->c.macro)
2242 cpp_hashnode *macro;
2243 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2245 macro_context *mc = context->c.mc;
2246 macro = mc->macro_node;
2247 /* If context->buff is set, it means the life time of tokens
2248 is bound to the life time of this context; so we must
2249 free the tokens; that means we must free the virtual
2250 locations of these tokens too. */
2251 if (context->buff && mc->virt_locs)
2253 free (mc->virt_locs);
2254 mc->virt_locs = NULL;
2256 free (mc);
2257 context->c.mc = NULL;
2259 else
2260 macro = context->c.macro;
2262 /* Beware that MACRO can be NULL in cases like when we are
2263 called from expand_arg. In those cases, a dummy context with
2264 tokens is pushed just for the purpose of walking them using
2265 cpp_get_token_1. In that case, no 'macro' field is set into
2266 the dummy context. */
2267 if (macro != NULL
2268 /* Several contiguous macro expansion contexts can be
2269 associated to the same macro; that means it's the same
2270 macro expansion that spans across all these (sub)
2271 contexts. So we should re-enable an expansion-disabled
2272 macro only when we are sure we are really out of that
2273 macro expansion. */
2274 && macro_of_context (context->prev) != macro)
2275 macro->flags &= ~NODE_DISABLED;
2278 if (context->buff)
2280 /* Decrease memory peak consumption by freeing the memory used
2281 by the context. */
2282 _cpp_free_buff (context->buff);
2285 pfile->context = context->prev;
2286 /* decrease peak memory consumption by feeing the context. */
2287 pfile->context->next = NULL;
2288 free (context);
2291 /* Return TRUE if we reached the end of the set of tokens stored in
2292 CONTEXT, FALSE otherwise. */
2293 static inline bool
2294 reached_end_of_context (cpp_context *context)
2296 if (context->tokens_kind == TOKENS_KIND_DIRECT)
2297 return FIRST (context).token == LAST (context).token;
2298 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2299 || context->tokens_kind == TOKENS_KIND_EXTENDED)
2300 return FIRST (context).ptoken == LAST (context).ptoken;
2301 else
2302 abort ();
2305 /* Consume the next token contained in the current context of PFILE,
2306 and return it in *TOKEN. It's "full location" is returned in
2307 *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2308 means the location encoding the locus of the token across macro
2309 expansion; otherwise it's just is the "normal" location of the
2310 token which (*TOKEN)->src_loc. */
2311 static inline void
2312 consume_next_token_from_context (cpp_reader *pfile,
2313 const cpp_token ** token,
2314 source_location *location)
2316 cpp_context *c = pfile->context;
2318 if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2320 *token = FIRST (c).token;
2321 *location = (*token)->src_loc;
2322 FIRST (c).token++;
2324 else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2326 *token = *FIRST (c).ptoken;
2327 *location = (*token)->src_loc;
2328 FIRST (c).ptoken++;
2330 else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2332 macro_context *m = c->c.mc;
2333 *token = *FIRST (c).ptoken;
2334 if (m->virt_locs)
2336 *location = *m->cur_virt_loc;
2337 m->cur_virt_loc++;
2339 else
2340 *location = (*token)->src_loc;
2341 FIRST (c).ptoken++;
2343 else
2344 abort ();
2347 /* In the traditional mode of the preprocessor, if we are currently in
2348 a directive, the location of a token must be the location of the
2349 start of the directive line. This function returns the proper
2350 location if we are in the traditional mode, and just returns
2351 LOCATION otherwise. */
2353 static inline source_location
2354 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2356 if (CPP_OPTION (pfile, traditional))
2358 if (pfile->state.in_directive)
2359 return pfile->directive_line;
2361 return location;
2364 /* Routine to get a token as well as its location.
2366 Macro expansions and directives are transparently handled,
2367 including entering included files. Thus tokens are post-macro
2368 expansion, and after any intervening directives. External callers
2369 see CPP_EOF only at EOF. Internal callers also see it when meeting
2370 a directive inside a macro call, when at the end of a directive and
2371 state.in_directive is still 1, and at the end of argument
2372 pre-expansion.
2374 LOC is an out parameter; *LOC is set to the location "as expected
2375 by the user". Please read the comment of
2376 cpp_get_token_with_location to learn more about the meaning of this
2377 location. */
2378 static const cpp_token*
2379 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2381 const cpp_token *result;
2382 /* This token is a virtual token that either encodes a location
2383 related to macro expansion or a spelling location. */
2384 source_location virt_loc = 0;
2385 /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2386 to functions that push macro contexts. So let's save it so that
2387 we can restore it when we are about to leave this routine. */
2388 bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2390 for (;;)
2392 cpp_hashnode *node;
2393 cpp_context *context = pfile->context;
2395 /* Context->prev == 0 <=> base context. */
2396 if (!context->prev)
2398 result = _cpp_lex_token (pfile);
2399 virt_loc = result->src_loc;
2401 else if (!reached_end_of_context (context))
2403 consume_next_token_from_context (pfile, &result,
2404 &virt_loc);
2405 if (result->flags & PASTE_LEFT)
2407 paste_all_tokens (pfile, result);
2408 if (pfile->state.in_directive)
2409 continue;
2410 result = padding_token (pfile, result);
2411 goto out;
2414 else
2416 if (pfile->context->c.macro)
2417 ++num_expanded_macros_counter;
2418 _cpp_pop_context (pfile);
2419 if (pfile->state.in_directive)
2420 continue;
2421 result = &pfile->avoid_paste;
2422 goto out;
2425 if (pfile->state.in_directive && result->type == CPP_COMMENT)
2426 continue;
2428 if (result->type != CPP_NAME)
2429 break;
2431 node = result->val.node.node;
2433 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2434 break;
2436 if (!(node->flags & NODE_DISABLED))
2438 int ret = 0;
2439 /* If not in a macro context, and we're going to start an
2440 expansion, record the location. */
2441 if (!in_macro_expansion_p (pfile))
2442 pfile->invocation_location = result->src_loc;
2443 if (pfile->state.prevent_expansion)
2444 break;
2446 /* Conditional macros require that a predicate be evaluated
2447 first. */
2448 if ((node->flags & NODE_CONDITIONAL) != 0)
2450 if (pfile->cb.macro_to_expand)
2452 bool whitespace_after;
2453 const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2455 whitespace_after = (peek_tok->type == CPP_PADDING
2456 || (peek_tok->flags & PREV_WHITE));
2457 node = pfile->cb.macro_to_expand (pfile, result);
2458 if (node)
2459 ret = enter_macro_context (pfile, node, result,
2460 virt_loc);
2461 else if (whitespace_after)
2463 /* If macro_to_expand hook returned NULL and it
2464 ate some tokens, see if we don't need to add
2465 a padding token in between this and the
2466 next token. */
2467 peek_tok = cpp_peek_token (pfile, 0);
2468 if (peek_tok->type != CPP_PADDING
2469 && (peek_tok->flags & PREV_WHITE) == 0)
2470 _cpp_push_token_context (pfile, NULL,
2471 padding_token (pfile,
2472 peek_tok), 1);
2476 else
2477 ret = enter_macro_context (pfile, node, result,
2478 virt_loc);
2479 if (ret)
2481 if (pfile->state.in_directive || ret == 2)
2482 continue;
2483 result = padding_token (pfile, result);
2484 goto out;
2487 else
2489 /* Flag this token as always unexpandable. FIXME: move this
2490 to collect_args()?. */
2491 cpp_token *t = _cpp_temp_token (pfile);
2492 t->type = result->type;
2493 t->flags = result->flags | NO_EXPAND;
2494 t->val = result->val;
2495 result = t;
2498 break;
2501 out:
2502 if (location != NULL)
2504 if (virt_loc == 0)
2505 virt_loc = result->src_loc;
2506 *location = virt_loc;
2508 if (!CPP_OPTION (pfile, track_macro_expansion)
2509 && macro_of_context (pfile->context) != NULL)
2510 /* We are in a macro expansion context, are not tracking
2511 virtual location, but were asked to report the location
2512 of the expansion point of the macro being expanded. */
2513 *location = pfile->invocation_location;
2515 *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2518 pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
2519 return result;
2522 /* External routine to get a token. Also used nearly everywhere
2523 internally, except for places where we know we can safely call
2524 _cpp_lex_token directly, such as lexing a directive name.
2526 Macro expansions and directives are transparently handled,
2527 including entering included files. Thus tokens are post-macro
2528 expansion, and after any intervening directives. External callers
2529 see CPP_EOF only at EOF. Internal callers also see it when meeting
2530 a directive inside a macro call, when at the end of a directive and
2531 state.in_directive is still 1, and at the end of argument
2532 pre-expansion. */
2533 const cpp_token *
2534 cpp_get_token (cpp_reader *pfile)
2536 return cpp_get_token_1 (pfile, NULL);
2539 /* Like cpp_get_token, but also returns a virtual token location
2540 separate from the spelling location carried by the returned token.
2542 LOC is an out parameter; *LOC is set to the location "as expected
2543 by the user". This matters when a token results from macro
2544 expansion; in that case the token's spelling location indicates the
2545 locus of the token in the definition of the macro but *LOC
2546 virtually encodes all the other meaningful locuses associated to
2547 the token.
2549 What? virtual location? Yes, virtual location.
2551 If the token results from macro expansion and if macro expansion
2552 location tracking is enabled its virtual location encodes (at the
2553 same time):
2555 - the spelling location of the token
2557 - the locus of the macro expansion point
2559 - the locus of the point where the token got instantiated as part
2560 of the macro expansion process.
2562 You have to use the linemap API to get the locus you are interested
2563 in from a given virtual location.
2565 Note however that virtual locations are not necessarily ordered for
2566 relations '<' and '>'. One must use the function
2567 linemap_location_before_p instead of using the relational operator
2568 '<'.
2570 If macro expansion tracking is off and if the token results from
2571 macro expansion the virtual location is the expansion point of the
2572 macro that got expanded.
2574 When the token doesn't result from macro expansion, the virtual
2575 location is just the same thing as its spelling location. */
2577 const cpp_token *
2578 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2580 return cpp_get_token_1 (pfile, loc);
2583 /* Returns true if we're expanding an object-like macro that was
2584 defined in a system header. Just checks the macro at the top of
2585 the stack. Used for diagnostic suppression. */
2587 cpp_sys_macro_p (cpp_reader *pfile)
2589 cpp_hashnode *node = NULL;
2591 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2592 node = pfile->context->c.mc->macro_node;
2593 else
2594 node = pfile->context->c.macro;
2596 return node && node->value.macro && node->value.macro->syshdr;
2599 /* Read each token in, until end of the current file. Directives are
2600 transparently processed. */
2601 void
2602 cpp_scan_nooutput (cpp_reader *pfile)
2604 /* Request a CPP_EOF token at the end of this file, rather than
2605 transparently continuing with the including file. */
2606 pfile->buffer->return_at_eof = true;
2608 pfile->state.discarding_output++;
2609 pfile->state.prevent_expansion++;
2611 if (CPP_OPTION (pfile, traditional))
2612 while (_cpp_read_logical_line_trad (pfile))
2614 else
2615 while (cpp_get_token (pfile)->type != CPP_EOF)
2618 pfile->state.discarding_output--;
2619 pfile->state.prevent_expansion--;
2622 /* Step back one or more tokens obtained from the lexer. */
2623 void
2624 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2626 pfile->lookaheads += count;
2627 while (count--)
2629 pfile->cur_token--;
2630 if (pfile->cur_token == pfile->cur_run->base
2631 /* Possible with -fpreprocessed and no leading #line. */
2632 && pfile->cur_run->prev != NULL)
2634 pfile->cur_run = pfile->cur_run->prev;
2635 pfile->cur_token = pfile->cur_run->limit;
2640 /* Step back one (or more) tokens. Can only step back more than 1 if
2641 they are from the lexer, and not from macro expansion. */
2642 void
2643 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2645 if (pfile->context->prev == NULL)
2646 _cpp_backup_tokens_direct (pfile, count);
2647 else
2649 if (count != 1)
2650 abort ();
2651 if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2652 FIRST (pfile->context).token--;
2653 else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2654 FIRST (pfile->context).ptoken--;
2655 else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2657 FIRST (pfile->context).ptoken--;
2658 if (pfile->context->c.macro)
2660 macro_context *m = pfile->context->c.mc;
2661 m->cur_virt_loc--;
2662 #ifdef ENABLE_CHECKING
2663 if (m->cur_virt_loc < m->virt_locs)
2664 abort ();
2665 #endif
2667 else
2668 abort ();
2670 else
2671 abort ();
2675 /* #define directive parsing and handling. */
2677 /* Returns nonzero if a macro redefinition warning is required. */
2678 static bool
2679 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2680 const cpp_macro *macro2)
2682 const cpp_macro *macro1;
2683 unsigned int i;
2685 /* Some redefinitions need to be warned about regardless. */
2686 if (node->flags & NODE_WARN)
2687 return true;
2689 /* Suppress warnings for builtins that lack the NODE_WARN flag. */
2690 if (node->flags & NODE_BUILTIN)
2692 if (!pfile->cb.user_builtin_macro
2693 || !pfile->cb.user_builtin_macro (pfile, node))
2694 return false;
2697 /* Redefinitions of conditional (context-sensitive) macros, on
2698 the other hand, must be allowed silently. */
2699 if (node->flags & NODE_CONDITIONAL)
2700 return false;
2702 /* Redefinition of a macro is allowed if and only if the old and new
2703 definitions are the same. (6.10.3 paragraph 2). */
2704 macro1 = node->value.macro;
2706 /* Don't check count here as it can be different in valid
2707 traditional redefinitions with just whitespace differences. */
2708 if (macro1->paramc != macro2->paramc
2709 || macro1->fun_like != macro2->fun_like
2710 || macro1->variadic != macro2->variadic)
2711 return true;
2713 /* Check parameter spellings. */
2714 for (i = 0; i < macro1->paramc; i++)
2715 if (macro1->params[i] != macro2->params[i])
2716 return true;
2718 /* Check the replacement text or tokens. */
2719 if (CPP_OPTION (pfile, traditional))
2720 return _cpp_expansions_different_trad (macro1, macro2);
2722 if (macro1->count != macro2->count)
2723 return true;
2725 for (i = 0; i < macro1->count; i++)
2726 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2727 return true;
2729 return false;
2732 /* Free the definition of hashnode H. */
2733 void
2734 _cpp_free_definition (cpp_hashnode *h)
2736 /* Macros and assertions no longer have anything to free. */
2737 h->type = NT_VOID;
2738 /* Clear builtin flag in case of redefinition. */
2739 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2742 /* Save parameter NODE to the parameter list of macro MACRO. Returns
2743 zero on success, nonzero if the parameter is a duplicate. */
2744 bool
2745 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
2747 unsigned int len;
2748 /* Constraint 6.10.3.6 - duplicate parameter names. */
2749 if (node->flags & NODE_MACRO_ARG)
2751 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2752 NODE_NAME (node));
2753 return true;
2756 if (BUFF_ROOM (pfile->a_buff)
2757 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2758 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2760 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
2761 node->flags |= NODE_MACRO_ARG;
2762 len = macro->paramc * sizeof (union _cpp_hashnode_value);
2763 if (len > pfile->macro_buffer_len)
2765 pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2766 len);
2767 pfile->macro_buffer_len = len;
2769 ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
2770 = node->value;
2772 node->value.arg_index = macro->paramc;
2773 return false;
2776 /* Check the syntax of the parameters in a MACRO definition. Returns
2777 false if an error occurs. */
2778 static bool
2779 parse_params (cpp_reader *pfile, cpp_macro *macro)
2781 unsigned int prev_ident = 0;
2783 for (;;)
2785 const cpp_token *token = _cpp_lex_token (pfile);
2787 switch (token->type)
2789 default:
2790 /* Allow/ignore comments in parameter lists if we are
2791 preserving comments in macro expansions. */
2792 if (token->type == CPP_COMMENT
2793 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
2794 continue;
2796 cpp_error (pfile, CPP_DL_ERROR,
2797 "\"%s\" may not appear in macro parameter list",
2798 cpp_token_as_text (pfile, token));
2799 return false;
2801 case CPP_NAME:
2802 if (prev_ident)
2804 cpp_error (pfile, CPP_DL_ERROR,
2805 "macro parameters must be comma-separated");
2806 return false;
2808 prev_ident = 1;
2810 if (_cpp_save_parameter (pfile, macro, token->val.node.node))
2811 return false;
2812 continue;
2814 case CPP_CLOSE_PAREN:
2815 if (prev_ident || macro->paramc == 0)
2816 return true;
2818 /* Fall through to pick up the error. */
2819 case CPP_COMMA:
2820 if (!prev_ident)
2822 cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
2823 return false;
2825 prev_ident = 0;
2826 continue;
2828 case CPP_ELLIPSIS:
2829 macro->variadic = 1;
2830 if (!prev_ident)
2832 _cpp_save_parameter (pfile, macro,
2833 pfile->spec_nodes.n__VA_ARGS__);
2834 pfile->state.va_args_ok = 1;
2835 if (! CPP_OPTION (pfile, c99)
2836 && CPP_OPTION (pfile, cpp_pedantic)
2837 && CPP_OPTION (pfile, warn_variadic_macros))
2839 if (CPP_OPTION (pfile, cplusplus))
2840 cpp_pedwarning
2841 (pfile, CPP_W_VARIADIC_MACROS,
2842 "anonymous variadic macros were introduced in C++11");
2843 else
2844 cpp_pedwarning
2845 (pfile, CPP_W_VARIADIC_MACROS,
2846 "anonymous variadic macros were introduced in C99");
2849 else if (CPP_OPTION (pfile, cpp_pedantic)
2850 && CPP_OPTION (pfile, warn_variadic_macros))
2852 if (CPP_OPTION (pfile, cplusplus))
2853 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2854 "ISO C++ does not permit named variadic macros");
2855 else
2856 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2857 "ISO C does not permit named variadic macros");
2860 /* We're at the end, and just expect a closing parenthesis. */
2861 token = _cpp_lex_token (pfile);
2862 if (token->type == CPP_CLOSE_PAREN)
2863 return true;
2864 /* Fall through. */
2866 case CPP_EOF:
2867 cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
2868 return false;
2873 /* Allocate room for a token from a macro's replacement list. */
2874 static cpp_token *
2875 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2877 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
2878 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
2880 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
2883 /* Lex a token from the expansion of MACRO, but mark parameters as we
2884 find them and warn of traditional stringification. */
2885 static cpp_token *
2886 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2888 cpp_token *token, *saved_cur_token;
2890 saved_cur_token = pfile->cur_token;
2891 pfile->cur_token = alloc_expansion_token (pfile, macro);
2892 token = _cpp_lex_direct (pfile);
2893 pfile->cur_token = saved_cur_token;
2895 /* Is this a parameter? */
2896 if (token->type == CPP_NAME
2897 && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
2899 token->type = CPP_MACRO_ARG;
2900 token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
2902 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
2903 && (token->type == CPP_STRING || token->type == CPP_CHAR))
2904 check_trad_stringification (pfile, macro, &token->val.str);
2906 return token;
2909 static bool
2910 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
2912 cpp_token *token;
2913 const cpp_token *ctoken;
2914 bool following_paste_op = false;
2915 const char *paste_op_error_msg =
2916 N_("'##' cannot appear at either end of a macro expansion");
2917 unsigned int num_extra_tokens = 0;
2919 /* Get the first token of the expansion (or the '(' of a
2920 function-like macro). */
2921 ctoken = _cpp_lex_token (pfile);
2923 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
2925 bool ok = parse_params (pfile, macro);
2926 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
2927 if (!ok)
2928 return false;
2930 /* Success. Commit or allocate the parameter array. */
2931 if (pfile->hash_table->alloc_subobject)
2933 cpp_hashnode **params =
2934 (cpp_hashnode **) pfile->hash_table->alloc_subobject
2935 (sizeof (cpp_hashnode *) * macro->paramc);
2936 memcpy (params, macro->params,
2937 sizeof (cpp_hashnode *) * macro->paramc);
2938 macro->params = params;
2940 else
2941 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
2942 macro->fun_like = 1;
2944 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
2946 /* While ISO C99 requires whitespace before replacement text
2947 in a macro definition, ISO C90 with TC1 allows characters
2948 from the basic source character set there. */
2949 if (CPP_OPTION (pfile, c99))
2951 if (CPP_OPTION (pfile, cplusplus))
2952 cpp_error (pfile, CPP_DL_PEDWARN,
2953 "ISO C++11 requires whitespace after the macro name");
2954 else
2955 cpp_error (pfile, CPP_DL_PEDWARN,
2956 "ISO C99 requires whitespace after the macro name");
2958 else
2960 int warntype = CPP_DL_WARNING;
2961 switch (ctoken->type)
2963 case CPP_ATSIGN:
2964 case CPP_AT_NAME:
2965 case CPP_OBJC_STRING:
2966 /* '@' is not in basic character set. */
2967 warntype = CPP_DL_PEDWARN;
2968 break;
2969 case CPP_OTHER:
2970 /* Basic character set sans letters, digits and _. */
2971 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
2972 ctoken->val.str.text[0]) == NULL)
2973 warntype = CPP_DL_PEDWARN;
2974 break;
2975 default:
2976 /* All other tokens start with a character from basic
2977 character set. */
2978 break;
2980 cpp_error (pfile, warntype,
2981 "missing whitespace after the macro name");
2985 if (macro->fun_like)
2986 token = lex_expansion_token (pfile, macro);
2987 else
2989 token = alloc_expansion_token (pfile, macro);
2990 *token = *ctoken;
2993 for (;;)
2995 /* Check the stringifying # constraint 6.10.3.2.1 of
2996 function-like macros when lexing the subsequent token. */
2997 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
2999 if (token->type == CPP_MACRO_ARG)
3001 if (token->flags & PREV_WHITE)
3002 token->flags |= SP_PREV_WHITE;
3003 if (token[-1].flags & DIGRAPH)
3004 token->flags |= SP_DIGRAPH;
3005 token->flags &= ~PREV_WHITE;
3006 token->flags |= STRINGIFY_ARG;
3007 token->flags |= token[-1].flags & PREV_WHITE;
3008 token[-1] = token[0];
3009 macro->count--;
3011 /* Let assembler get away with murder. */
3012 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
3014 cpp_error (pfile, CPP_DL_ERROR,
3015 "'#' is not followed by a macro parameter");
3016 return false;
3020 if (token->type == CPP_EOF)
3022 /* Paste operator constraint 6.10.3.3.1:
3023 Token-paste ##, can appear in both object-like and
3024 function-like macros, but not at the end. */
3025 if (following_paste_op)
3027 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3028 return false;
3030 break;
3033 /* Paste operator constraint 6.10.3.3.1. */
3034 if (token->type == CPP_PASTE)
3036 /* Token-paste ##, can appear in both object-like and
3037 function-like macros, but not at the beginning. */
3038 if (macro->count == 1)
3040 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3041 return false;
3044 if (token[-1].flags & PASTE_LEFT)
3046 macro->extra_tokens = 1;
3047 num_extra_tokens++;
3048 token->val.token_no = macro->count - 1;
3050 else
3052 --macro->count;
3053 token[-1].flags |= PASTE_LEFT;
3054 if (token->flags & DIGRAPH)
3055 token[-1].flags |= SP_DIGRAPH;
3056 if (token->flags & PREV_WHITE)
3057 token[-1].flags |= SP_PREV_WHITE;
3061 following_paste_op = (token->type == CPP_PASTE);
3062 token = lex_expansion_token (pfile, macro);
3065 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
3066 macro->traditional = 0;
3068 /* Don't count the CPP_EOF. */
3069 macro->count--;
3071 /* Clear whitespace on first token for warn_of_redefinition(). */
3072 if (macro->count)
3073 macro->exp.tokens[0].flags &= ~PREV_WHITE;
3075 /* Commit or allocate the memory. */
3076 if (pfile->hash_table->alloc_subobject)
3078 cpp_token *tokns =
3079 (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
3080 * macro->count);
3081 if (num_extra_tokens)
3083 /* Place second and subsequent ## or %:%: tokens in
3084 sequences of consecutive such tokens at the end of the
3085 list to preserve information about where they appear, how
3086 they are spelt and whether they are preceded by
3087 whitespace without otherwise interfering with macro
3088 expansion. */
3089 cpp_token *normal_dest = tokns;
3090 cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
3091 unsigned int i;
3092 for (i = 0; i < macro->count; i++)
3094 if (macro->exp.tokens[i].type == CPP_PASTE)
3095 *extra_dest++ = macro->exp.tokens[i];
3096 else
3097 *normal_dest++ = macro->exp.tokens[i];
3100 else
3101 memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
3102 macro->exp.tokens = tokns;
3104 else
3105 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
3107 return true;
3110 /* Parse a macro and save its expansion. Returns nonzero on success. */
3111 bool
3112 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3114 cpp_macro *macro;
3115 unsigned int i;
3116 bool ok;
3118 if (pfile->hash_table->alloc_subobject)
3119 macro = (cpp_macro *) pfile->hash_table->alloc_subobject
3120 (sizeof (cpp_macro));
3121 else
3122 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
3123 macro->line = pfile->directive_line;
3124 macro->params = 0;
3125 macro->paramc = 0;
3126 macro->variadic = 0;
3127 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3128 macro->count = 0;
3129 macro->fun_like = 0;
3130 macro->extra_tokens = 0;
3131 /* To suppress some diagnostics. */
3132 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3134 if (CPP_OPTION (pfile, traditional))
3135 ok = _cpp_create_trad_definition (pfile, macro);
3136 else
3138 ok = create_iso_definition (pfile, macro);
3140 /* We set the type for SEEN_EOL() in directives.c.
3142 Longer term we should lex the whole line before coming here,
3143 and just copy the expansion. */
3145 /* Stop the lexer accepting __VA_ARGS__. */
3146 pfile->state.va_args_ok = 0;
3149 /* Clear the fast argument lookup indices. */
3150 for (i = macro->paramc; i-- > 0; )
3152 struct cpp_hashnode *node = macro->params[i];
3153 node->flags &= ~ NODE_MACRO_ARG;
3154 node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
3157 if (!ok)
3158 return ok;
3160 if (node->type == NT_MACRO)
3162 if (CPP_OPTION (pfile, warn_unused_macros))
3163 _cpp_warn_if_unused_macro (pfile, node, NULL);
3165 if (warn_of_redefinition (pfile, node, macro))
3167 const int reason = (node->flags & NODE_BUILTIN)
3168 ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3169 bool warned;
3171 warned = cpp_pedwarning_with_line (pfile, reason,
3172 pfile->directive_line, 0,
3173 "\"%s\" redefined",
3174 NODE_NAME (node));
3176 if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3177 cpp_error_with_line (pfile, CPP_DL_NOTE,
3178 node->value.macro->line, 0,
3179 "this is the location of the previous definition");
3183 if (node->type != NT_VOID)
3184 _cpp_free_definition (node);
3186 /* Enter definition in hash table. */
3187 node->type = NT_MACRO;
3188 node->value.macro = macro;
3189 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3190 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3191 /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3192 in the C standard, as something that one must use in C++.
3193 However DR#593 and C++11 indicate that they play no role in C++.
3194 We special-case them anyway. */
3195 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3196 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3197 node->flags |= NODE_WARN;
3199 /* If user defines one of the conditional macros, remove the
3200 conditional flag */
3201 node->flags &= ~NODE_CONDITIONAL;
3203 return ok;
3206 /* Warn if a token in STRING matches one of a function-like MACRO's
3207 parameters. */
3208 static void
3209 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3210 const cpp_string *string)
3212 unsigned int i, len;
3213 const uchar *p, *q, *limit;
3215 /* Loop over the string. */
3216 limit = string->text + string->len - 1;
3217 for (p = string->text + 1; p < limit; p = q)
3219 /* Find the start of an identifier. */
3220 while (p < limit && !is_idstart (*p))
3221 p++;
3223 /* Find the end of the identifier. */
3224 q = p;
3225 while (q < limit && is_idchar (*q))
3226 q++;
3228 len = q - p;
3230 /* Loop over the function macro arguments to see if the
3231 identifier inside the string matches one of them. */
3232 for (i = 0; i < macro->paramc; i++)
3234 const cpp_hashnode *node = macro->params[i];
3236 if (NODE_LEN (node) == len
3237 && !memcmp (p, NODE_NAME (node), len))
3239 cpp_error (pfile, CPP_DL_WARNING,
3240 "macro argument \"%s\" would be stringified in traditional C",
3241 NODE_NAME (node));
3242 break;
3248 /* Returns the name, arguments and expansion of a macro, in a format
3249 suitable to be read back in again, and therefore also for DWARF 2
3250 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3251 Caller is expected to generate the "#define" bit if needed. The
3252 returned text is temporary, and automatically freed later. */
3253 const unsigned char *
3254 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3256 unsigned int i, len;
3257 const cpp_macro *macro;
3258 unsigned char *buffer;
3260 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3262 if (node->type != NT_MACRO
3263 || !pfile->cb.user_builtin_macro
3264 || !pfile->cb.user_builtin_macro (pfile, node))
3266 cpp_error (pfile, CPP_DL_ICE,
3267 "invalid hash type %d in cpp_macro_definition",
3268 node->type);
3269 return 0;
3273 macro = node->value.macro;
3274 /* Calculate length. */
3275 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
3276 if (macro->fun_like)
3278 len += 4; /* "()" plus possible final ".." of named
3279 varargs (we have + 1 below). */
3280 for (i = 0; i < macro->paramc; i++)
3281 len += NODE_LEN (macro->params[i]) + 1; /* "," */
3284 /* This should match below where we fill in the buffer. */
3285 if (CPP_OPTION (pfile, traditional))
3286 len += _cpp_replacement_text_len (macro);
3287 else
3289 unsigned int count = macro_real_token_count (macro);
3290 for (i = 0; i < count; i++)
3292 cpp_token *token = &macro->exp.tokens[i];
3294 if (token->type == CPP_MACRO_ARG)
3295 len += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3296 else
3297 len += cpp_token_len (token);
3299 if (token->flags & STRINGIFY_ARG)
3300 len++; /* "#" */
3301 if (token->flags & PASTE_LEFT)
3302 len += 3; /* " ##" */
3303 if (token->flags & PREV_WHITE)
3304 len++; /* " " */
3308 if (len > pfile->macro_buffer_len)
3310 pfile->macro_buffer = XRESIZEVEC (unsigned char,
3311 pfile->macro_buffer, len);
3312 pfile->macro_buffer_len = len;
3315 /* Fill in the buffer. Start with the macro name. */
3316 buffer = pfile->macro_buffer;
3317 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
3318 buffer += NODE_LEN (node);
3320 /* Parameter names. */
3321 if (macro->fun_like)
3323 *buffer++ = '(';
3324 for (i = 0; i < macro->paramc; i++)
3326 cpp_hashnode *param = macro->params[i];
3328 if (param != pfile->spec_nodes.n__VA_ARGS__)
3330 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3331 buffer += NODE_LEN (param);
3334 if (i + 1 < macro->paramc)
3335 /* Don't emit a space after the comma here; we're trying
3336 to emit a Dwarf-friendly definition, and the Dwarf spec
3337 forbids spaces in the argument list. */
3338 *buffer++ = ',';
3339 else if (macro->variadic)
3340 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3342 *buffer++ = ')';
3345 /* The Dwarf spec requires a space after the macro name, even if the
3346 definition is the empty string. */
3347 *buffer++ = ' ';
3349 if (CPP_OPTION (pfile, traditional))
3350 buffer = _cpp_copy_replacement_text (macro, buffer);
3351 else if (macro->count)
3352 /* Expansion tokens. */
3354 unsigned int count = macro_real_token_count (macro);
3355 for (i = 0; i < count; i++)
3357 cpp_token *token = &macro->exp.tokens[i];
3359 if (token->flags & PREV_WHITE)
3360 *buffer++ = ' ';
3361 if (token->flags & STRINGIFY_ARG)
3362 *buffer++ = '#';
3364 if (token->type == CPP_MACRO_ARG)
3366 memcpy (buffer,
3367 NODE_NAME (macro->params[token->val.macro_arg.arg_no - 1]),
3368 NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]));
3369 buffer += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3371 else
3372 buffer = cpp_spell_token (pfile, token, buffer, false);
3374 if (token->flags & PASTE_LEFT)
3376 *buffer++ = ' ';
3377 *buffer++ = '#';
3378 *buffer++ = '#';
3379 /* Next has PREV_WHITE; see _cpp_create_definition. */
3384 *buffer = '\0';
3385 return pfile->macro_buffer;