Use tree_vector_builder::new_unary_operation for folding
[official-gcc.git] / libcpp / macro.c
blob791817af8db912967cb6fb4ec2cf87915ac9ebff
1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986-2017 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 #if CHECKING_P
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 /* Saved data about an identifier being used as a macro argument
84 name. */
85 struct macro_arg_saved_data {
86 /* The canonical (UTF-8) spelling of this identifier. */
87 cpp_hashnode *canonical_node;
88 /* The previous value of this identifier. */
89 union _cpp_hashnode_value value;
92 static const char *vaopt_paste_error =
93 N_("'##' cannot appear at either end of __VA_OPT__");
95 /* A class for tracking __VA_OPT__ state while iterating over a
96 sequence of tokens. This is used during both macro definition and
97 expansion. */
98 class vaopt_state {
100 public:
102 /* Initialize the state tracker. ANY_ARGS is true if variable
103 arguments were provided to the macro invocation. */
104 vaopt_state (cpp_reader *pfile, bool is_variadic, bool any_args)
105 : m_pfile (pfile),
106 m_allowed (any_args),
107 m_variadic (is_variadic),
108 m_state (0),
109 m_last_was_paste (false),
110 m_paste_location (0),
111 m_location (0)
115 enum update_type
117 ERROR,
118 DROP,
119 INCLUDE
122 /* Given a token, update the state of this tracker and return a
123 boolean indicating whether the token should be be included in the
124 expansion. */
125 update_type update (const cpp_token *token)
127 /* If the macro isn't variadic, just don't bother. */
128 if (!m_variadic)
129 return INCLUDE;
131 if (token->type == CPP_NAME
132 && token->val.node.node == m_pfile->spec_nodes.n__VA_OPT__)
134 if (m_state > 0)
136 cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
137 "__VA_OPT__ may not appear in a __VA_OPT__");
138 return ERROR;
140 ++m_state;
141 m_location = token->src_loc;
142 return DROP;
144 else if (m_state == 1)
146 if (token->type != CPP_OPEN_PAREN)
148 cpp_error_at (m_pfile, CPP_DL_ERROR, m_location,
149 "__VA_OPT__ must be followed by an "
150 "open parenthesis");
151 return ERROR;
153 ++m_state;
154 return DROP;
156 else if (m_state >= 2)
158 if (m_state == 2 && token->type == CPP_PASTE)
160 cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
161 vaopt_paste_error);
162 return ERROR;
164 /* Advance states before further considering this token, in
165 case we see a close paren immediately after the open
166 paren. */
167 if (m_state == 2)
168 ++m_state;
170 bool was_paste = m_last_was_paste;
171 m_last_was_paste = false;
172 if (token->type == CPP_PASTE)
174 m_last_was_paste = true;
175 m_paste_location = token->src_loc;
177 else if (token->type == CPP_OPEN_PAREN)
178 ++m_state;
179 else if (token->type == CPP_CLOSE_PAREN)
181 --m_state;
182 if (m_state == 2)
184 /* Saw the final paren. */
185 m_state = 0;
187 if (was_paste)
189 cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
190 vaopt_paste_error);
191 return ERROR;
194 return DROP;
197 return m_allowed ? INCLUDE : DROP;
200 /* Nothing to do with __VA_OPT__. */
201 return INCLUDE;
204 /* Ensure that any __VA_OPT__ was completed. If ok, return true.
205 Otherwise, issue an error and return false. */
206 bool completed ()
208 if (m_variadic && m_state != 0)
209 cpp_error_at (m_pfile, CPP_DL_ERROR, m_location,
210 "unterminated __VA_OPT__");
211 return m_state == 0;
214 private:
216 /* The cpp_reader. */
217 cpp_reader *m_pfile;
219 /* True if there were varargs. */
220 bool m_allowed;
221 /* True if the macro is variadic. */
222 bool m_variadic;
224 /* The state variable:
225 0 means not parsing
226 1 means __VA_OPT__ seen, looking for "("
227 2 means "(" seen (so the next token can't be "##")
228 >= 3 means looking for ")", the number encodes the paren depth. */
229 int m_state;
231 /* If true, the previous token was ##. This is used to detect when
232 a paste occurs at the end of the sequence. */
233 bool m_last_was_paste;
234 /* The location of the paste token. */
235 source_location m_paste_location;
237 /* Location of the __VA_OPT__ token. */
238 source_location m_location;
241 /* Macro expansion. */
243 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
244 const cpp_token *, source_location);
245 static int builtin_macro (cpp_reader *, cpp_hashnode *,
246 source_location, source_location);
247 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
248 const cpp_token **, unsigned int);
249 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
250 _cpp_buff *, source_location *,
251 const cpp_token **, unsigned int);
252 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
253 _cpp_buff **, unsigned *);
254 static cpp_context *next_context (cpp_reader *);
255 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
256 static void expand_arg (cpp_reader *, macro_arg *);
257 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
258 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
259 static void paste_all_tokens (cpp_reader *, const cpp_token *);
260 static bool paste_tokens (cpp_reader *, source_location,
261 const cpp_token **, const cpp_token *);
262 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
263 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
264 static void delete_macro_args (_cpp_buff*, unsigned num_args);
265 static void set_arg_token (macro_arg *, const cpp_token *,
266 source_location, size_t,
267 enum macro_arg_token_kind,
268 bool);
269 static const source_location *get_arg_token_location (const macro_arg *,
270 enum macro_arg_token_kind);
271 static const cpp_token **arg_token_ptr_at (const macro_arg *,
272 size_t,
273 enum macro_arg_token_kind,
274 source_location **virt_location);
276 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
277 enum macro_arg_token_kind,
278 const macro_arg *,
279 const cpp_token **);
280 static const cpp_token *macro_arg_token_iter_get_token
281 (const macro_arg_token_iter *it);
282 static source_location macro_arg_token_iter_get_location
283 (const macro_arg_token_iter *);
284 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
285 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
286 source_location **);
287 static size_t tokens_buff_count (_cpp_buff *);
288 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
289 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
290 source_location *,
291 const cpp_token *,
292 source_location,
293 source_location,
294 const line_map_macro *,
295 unsigned int);
297 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
298 source_location *,
299 const cpp_token *,
300 source_location,
301 source_location,
302 const line_map_macro *,
303 unsigned int);
304 static inline void tokens_buff_remove_last_token (_cpp_buff *);
305 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
306 macro_arg *, source_location);
307 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
308 _cpp_buff **, unsigned *);
309 static bool create_iso_definition (cpp_reader *, cpp_macro *);
311 /* #define directive parsing and handling. */
313 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
314 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
315 static bool warn_of_redefinition (cpp_reader *, cpp_hashnode *,
316 const cpp_macro *);
317 static bool parse_params (cpp_reader *, cpp_macro *);
318 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
319 const cpp_string *);
320 static bool reached_end_of_context (cpp_context *);
321 static void consume_next_token_from_context (cpp_reader *pfile,
322 const cpp_token **,
323 source_location *);
324 static const cpp_token* cpp_get_token_1 (cpp_reader *, source_location *);
326 static cpp_hashnode* macro_of_context (cpp_context *context);
328 static bool in_macro_expansion_p (cpp_reader *pfile);
330 /* Statistical counter tracking the number of macros that got
331 expanded. */
332 unsigned num_expanded_macros_counter = 0;
333 /* Statistical counter tracking the total number tokens resulting
334 from macro expansion. */
335 unsigned num_macro_tokens_counter = 0;
337 /* Emits a warning if NODE is a macro defined in the main file that
338 has not been used. */
340 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
341 void *v ATTRIBUTE_UNUSED)
343 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
345 cpp_macro *macro = node->value.macro;
347 if (!macro->used
348 && MAIN_FILE_P (linemap_check_ordinary
349 (linemap_lookup (pfile->line_table,
350 macro->line))))
351 cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
352 "macro \"%s\" is not used", NODE_NAME (node));
355 return 1;
358 /* Allocates and returns a CPP_STRING token, containing TEXT of length
359 LEN, after null-terminating it. TEXT must be in permanent storage. */
360 static const cpp_token *
361 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
363 cpp_token *token = _cpp_temp_token (pfile);
365 text[len] = '\0';
366 token->type = CPP_STRING;
367 token->val.str.len = len;
368 token->val.str.text = text;
369 token->flags = 0;
370 return token;
373 static const char * const monthnames[] =
375 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
376 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
379 /* Helper function for builtin_macro. Returns the text generated by
380 a builtin macro. */
381 const uchar *
382 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node,
383 source_location loc)
385 const uchar *result = NULL;
386 linenum_type number = 1;
388 switch (node->value.builtin)
390 default:
391 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
392 NODE_NAME (node));
393 break;
395 case BT_TIMESTAMP:
397 if (CPP_OPTION (pfile, warn_date_time))
398 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
399 "reproducible builds", NODE_NAME (node));
401 cpp_buffer *pbuffer = cpp_get_buffer (pfile);
402 if (pbuffer->timestamp == NULL)
404 /* Initialize timestamp value of the assotiated file. */
405 struct _cpp_file *file = cpp_get_file (pbuffer);
406 if (file)
408 /* Generate __TIMESTAMP__ string, that represents
409 the date and time of the last modification
410 of the current source file. The string constant
411 looks like "Sun Sep 16 01:03:52 1973". */
412 struct tm *tb = NULL;
413 struct stat *st = _cpp_get_file_stat (file);
414 if (st)
415 tb = localtime (&st->st_mtime);
416 if (tb)
418 char *str = asctime (tb);
419 size_t len = strlen (str);
420 unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
421 buf[0] = '"';
422 strcpy ((char *) buf + 1, str);
423 buf[len] = '"';
424 pbuffer->timestamp = buf;
426 else
428 cpp_errno (pfile, CPP_DL_WARNING,
429 "could not determine file timestamp");
430 pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
434 result = pbuffer->timestamp;
436 break;
437 case BT_FILE:
438 case BT_BASE_FILE:
440 unsigned int len;
441 const char *name;
442 uchar *buf;
444 if (node->value.builtin == BT_FILE)
445 name = linemap_get_expansion_filename (pfile->line_table,
446 pfile->line_table->highest_line);
447 else
449 name = _cpp_get_file_name (pfile->main_file);
450 if (!name)
451 abort ();
453 len = strlen (name);
454 buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
455 result = buf;
456 *buf = '"';
457 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
458 *buf++ = '"';
459 *buf = '\0';
461 break;
463 case BT_INCLUDE_LEVEL:
464 /* The line map depth counts the primary source as level 1, but
465 historically __INCLUDE_DEPTH__ has called the primary source
466 level 0. */
467 number = pfile->line_table->depth - 1;
468 break;
470 case BT_SPECLINE:
471 /* If __LINE__ is embedded in a macro, it must expand to the
472 line of the macro's invocation, not its definition.
473 Otherwise things like assert() will not work properly.
474 See WG14 N1911, WG21 N4220 sec 6.5, and PR 61861. */
475 if (CPP_OPTION (pfile, traditional))
476 loc = pfile->line_table->highest_line;
477 else
478 loc = linemap_resolve_location (pfile->line_table, loc,
479 LRK_MACRO_EXPANSION_POINT, NULL);
480 number = linemap_get_expansion_line (pfile->line_table, loc);
481 break;
483 /* __STDC__ has the value 1 under normal circumstances.
484 However, if (a) we are in a system header, (b) the option
485 stdc_0_in_system_headers is true (set by target config), and
486 (c) we are not in strictly conforming mode, then it has the
487 value 0. (b) and (c) are already checked in cpp_init_builtins. */
488 case BT_STDC:
489 if (cpp_in_system_header (pfile))
490 number = 0;
491 else
492 number = 1;
493 break;
495 case BT_DATE:
496 case BT_TIME:
497 if (CPP_OPTION (pfile, warn_date_time))
498 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
499 "reproducible builds", NODE_NAME (node));
500 if (pfile->date == NULL)
502 /* Allocate __DATE__ and __TIME__ strings from permanent
503 storage. We only do this once, and don't generate them
504 at init time, because time() and localtime() are very
505 slow on some systems. */
506 time_t tt;
507 struct tm *tb = NULL;
509 /* Set a reproducible timestamp for __DATE__ and __TIME__ macro
510 if SOURCE_DATE_EPOCH is defined. */
511 if (pfile->source_date_epoch == (time_t) -2
512 && pfile->cb.get_source_date_epoch != NULL)
513 pfile->source_date_epoch = pfile->cb.get_source_date_epoch (pfile);
515 if (pfile->source_date_epoch >= (time_t) 0)
516 tb = gmtime (&pfile->source_date_epoch);
517 else
519 /* (time_t) -1 is a legitimate value for "number of seconds
520 since the Epoch", so we have to do a little dance to
521 distinguish that from a genuine error. */
522 errno = 0;
523 tt = time (NULL);
524 if (tt != (time_t)-1 || errno == 0)
525 tb = localtime (&tt);
528 if (tb)
530 pfile->date = _cpp_unaligned_alloc (pfile,
531 sizeof ("\"Oct 11 1347\""));
532 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
533 monthnames[tb->tm_mon], tb->tm_mday,
534 tb->tm_year + 1900);
536 pfile->time = _cpp_unaligned_alloc (pfile,
537 sizeof ("\"12:34:56\""));
538 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
539 tb->tm_hour, tb->tm_min, tb->tm_sec);
541 else
543 cpp_errno (pfile, CPP_DL_WARNING,
544 "could not determine date and time");
546 pfile->date = UC"\"??? ?? ????\"";
547 pfile->time = UC"\"??:??:??\"";
551 if (node->value.builtin == BT_DATE)
552 result = pfile->date;
553 else
554 result = pfile->time;
555 break;
557 case BT_COUNTER:
558 if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
559 cpp_error (pfile, CPP_DL_ERROR,
560 "__COUNTER__ expanded inside directive with -fdirectives-only");
561 number = pfile->counter++;
562 break;
564 case BT_HAS_ATTRIBUTE:
565 number = pfile->cb.has_attribute (pfile);
566 break;
569 if (result == NULL)
571 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
572 result = _cpp_unaligned_alloc (pfile, 21);
573 sprintf ((char *) result, "%u", number);
576 return result;
579 /* Convert builtin macros like __FILE__ to a token and push it on the
580 context stack. Also handles _Pragma, for which a new token may not
581 be created. Returns 1 if it generates a new token context, 0 to
582 return the token to the caller. LOC is the location of the expansion
583 point of the macro. */
584 static int
585 builtin_macro (cpp_reader *pfile, cpp_hashnode *node,
586 source_location loc, source_location expand_loc)
588 const uchar *buf;
589 size_t len;
590 char *nbuf;
592 if (node->value.builtin == BT_PRAGMA)
594 /* Don't interpret _Pragma within directives. The standard is
595 not clear on this, but to me this makes most sense. */
596 if (pfile->state.in_directive)
597 return 0;
599 return _cpp_do__Pragma (pfile, loc);
602 buf = _cpp_builtin_macro_text (pfile, node, expand_loc);
603 len = ustrlen (buf);
604 nbuf = (char *) alloca (len + 1);
605 memcpy (nbuf, buf, len);
606 nbuf[len]='\n';
608 cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
609 _cpp_clean_line (pfile);
611 /* Set pfile->cur_token as required by _cpp_lex_direct. */
612 pfile->cur_token = _cpp_temp_token (pfile);
613 cpp_token *token = _cpp_lex_direct (pfile);
614 /* We should point to the expansion point of the builtin macro. */
615 token->src_loc = loc;
616 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
618 /* We are tracking tokens resulting from macro expansion.
619 Create a macro line map and generate a virtual location for
620 the token resulting from the expansion of the built-in
621 macro. */
622 source_location *virt_locs = NULL;
623 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
624 const line_map_macro * map =
625 linemap_enter_macro (pfile->line_table, node, loc, 1);
626 tokens_buff_add_token (token_buf, virt_locs, token,
627 pfile->line_table->builtin_location,
628 pfile->line_table->builtin_location,
629 map, /*macro_token_index=*/0);
630 push_extended_tokens_context (pfile, node, token_buf, virt_locs,
631 (const cpp_token **)token_buf->base,
634 else
635 _cpp_push_token_context (pfile, NULL, token, 1);
636 if (pfile->buffer->cur != pfile->buffer->rlimit)
637 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
638 NODE_NAME (node));
639 _cpp_pop_buffer (pfile);
641 return 1;
644 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
645 backslashes and double quotes. DEST must be of sufficient size.
646 Returns a pointer to the end of the string. */
647 uchar *
648 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
650 while (len--)
652 uchar c = *src++;
654 switch (c)
656 case '\n':
657 /* Naked LF can appear in raw string literals */
658 c = 'n';
659 /* FALLTHROUGH */
661 case '\\':
662 case '"':
663 *dest++ = '\\';
664 /* FALLTHROUGH */
666 default:
667 *dest++ = c;
671 return dest;
674 /* Convert a token sequence ARG to a single string token according to
675 the rules of the ISO C #-operator. */
676 static const cpp_token *
677 stringify_arg (cpp_reader *pfile, macro_arg *arg)
679 unsigned char *dest;
680 unsigned int i, escape_it, backslash_count = 0;
681 const cpp_token *source = NULL;
682 size_t len;
684 if (BUFF_ROOM (pfile->u_buff) < 3)
685 _cpp_extend_buff (pfile, &pfile->u_buff, 3);
686 dest = BUFF_FRONT (pfile->u_buff);
687 *dest++ = '"';
689 /* Loop, reading in the argument's tokens. */
690 for (i = 0; i < arg->count; i++)
692 const cpp_token *token = arg->first[i];
694 if (token->type == CPP_PADDING)
696 if (source == NULL
697 || (!(source->flags & PREV_WHITE)
698 && token->val.source == NULL))
699 source = token->val.source;
700 continue;
703 escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
704 || token->type == CPP_WSTRING || token->type == CPP_WCHAR
705 || token->type == CPP_STRING32 || token->type == CPP_CHAR32
706 || token->type == CPP_STRING16 || token->type == CPP_CHAR16
707 || token->type == CPP_UTF8STRING || token->type == CPP_UTF8CHAR
708 || cpp_userdef_string_p (token->type)
709 || cpp_userdef_char_p (token->type));
711 /* Room for each char being written in octal, initial space and
712 final quote and NUL. */
713 len = cpp_token_len (token);
714 if (escape_it)
715 len *= 4;
716 len += 3;
718 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
720 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
721 _cpp_extend_buff (pfile, &pfile->u_buff, len);
722 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
725 /* Leading white space? */
726 if (dest - 1 != BUFF_FRONT (pfile->u_buff))
728 if (source == NULL)
729 source = token;
730 if (source->flags & PREV_WHITE)
731 *dest++ = ' ';
733 source = NULL;
735 if (escape_it)
737 _cpp_buff *buff = _cpp_get_buff (pfile, len);
738 unsigned char *buf = BUFF_FRONT (buff);
739 len = cpp_spell_token (pfile, token, buf, true) - buf;
740 dest = cpp_quote_string (dest, buf, len);
741 _cpp_release_buff (pfile, buff);
743 else
744 dest = cpp_spell_token (pfile, token, dest, true);
746 if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
747 backslash_count++;
748 else
749 backslash_count = 0;
752 /* Ignore the final \ of invalid string literals. */
753 if (backslash_count & 1)
755 cpp_error (pfile, CPP_DL_WARNING,
756 "invalid string literal, ignoring final '\\'");
757 dest--;
760 /* Commit the memory, including NUL, and return the token. */
761 *dest++ = '"';
762 len = dest - BUFF_FRONT (pfile->u_buff);
763 BUFF_FRONT (pfile->u_buff) = dest + 1;
764 return new_string_token (pfile, dest - len, len);
767 /* Try to paste two tokens. On success, return nonzero. In any
768 case, PLHS is updated to point to the pasted token, which is
769 guaranteed to not have the PASTE_LEFT flag set. LOCATION is
770 the virtual location used for error reporting. */
771 static bool
772 paste_tokens (cpp_reader *pfile, source_location location,
773 const cpp_token **plhs, const cpp_token *rhs)
775 unsigned char *buf, *end, *lhsend;
776 cpp_token *lhs;
777 unsigned int len;
779 len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
780 buf = (unsigned char *) alloca (len);
781 end = lhsend = cpp_spell_token (pfile, *plhs, buf, true);
783 /* Avoid comment headers, since they are still processed in stage 3.
784 It is simpler to insert a space here, rather than modifying the
785 lexer to ignore comments in some circumstances. Simply returning
786 false doesn't work, since we want to clear the PASTE_LEFT flag. */
787 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
788 *end++ = ' ';
789 /* In one obscure case we might see padding here. */
790 if (rhs->type != CPP_PADDING)
791 end = cpp_spell_token (pfile, rhs, end, true);
792 *end = '\n';
794 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
795 _cpp_clean_line (pfile);
797 /* Set pfile->cur_token as required by _cpp_lex_direct. */
798 pfile->cur_token = _cpp_temp_token (pfile);
799 lhs = _cpp_lex_direct (pfile);
800 if (pfile->buffer->cur != pfile->buffer->rlimit)
802 source_location saved_loc = lhs->src_loc;
804 _cpp_pop_buffer (pfile);
805 _cpp_backup_tokens (pfile, 1);
806 *lhsend = '\0';
808 /* We have to remove the PASTE_LEFT flag from the old lhs, but
809 we want to keep the new location. */
810 *lhs = **plhs;
811 *plhs = lhs;
812 lhs->src_loc = saved_loc;
813 lhs->flags &= ~PASTE_LEFT;
815 /* Mandatory error for all apart from assembler. */
816 if (CPP_OPTION (pfile, lang) != CLK_ASM)
817 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
818 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
819 buf, cpp_token_as_text (pfile, rhs));
820 return false;
823 *plhs = lhs;
824 _cpp_pop_buffer (pfile);
825 return true;
828 /* Handles an arbitrarily long sequence of ## operators, with initial
829 operand LHS. This implementation is left-associative,
830 non-recursive, and finishes a paste before handling succeeding
831 ones. If a paste fails, we back up to the RHS of the failing ##
832 operator before pushing the context containing the result of prior
833 successful pastes, with the effect that the RHS appears in the
834 output stream after the pasted LHS normally. */
835 static void
836 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
838 const cpp_token *rhs = NULL;
839 cpp_context *context = pfile->context;
840 source_location virt_loc = 0;
842 /* We are expanding a macro and we must have been called on a token
843 that appears at the left hand side of a ## operator. */
844 if (macro_of_context (pfile->context) == NULL
845 || (!(lhs->flags & PASTE_LEFT)))
846 abort ();
848 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
849 /* The caller must have called consume_next_token_from_context
850 right before calling us. That has incremented the pointer to
851 the current virtual location. So it now points to the location
852 of the token that comes right after *LHS. We want the
853 resulting pasted token to have the location of the current
854 *LHS, though. */
855 virt_loc = context->c.mc->cur_virt_loc[-1];
856 else
857 /* We are not tracking macro expansion. So the best virtual
858 location we can get here is the expansion point of the macro we
859 are currently expanding. */
860 virt_loc = pfile->invocation_location;
864 /* Take the token directly from the current context. We can do
865 this, because we are in the replacement list of either an
866 object-like macro, or a function-like macro with arguments
867 inserted. In either case, the constraints to #define
868 guarantee we have at least one more token. */
869 if (context->tokens_kind == TOKENS_KIND_DIRECT)
870 rhs = FIRST (context).token++;
871 else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
872 rhs = *FIRST (context).ptoken++;
873 else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
875 /* So we are in presence of an extended token context, which
876 means that each token in this context has a virtual
877 location attached to it. So let's not forget to update
878 the pointer to the current virtual location of the
879 current token when we update the pointer to the current
880 token */
882 rhs = *FIRST (context).ptoken++;
883 /* context->c.mc must be non-null, as if we were not in a
884 macro context, context->tokens_kind could not be equal to
885 TOKENS_KIND_EXTENDED. */
886 context->c.mc->cur_virt_loc++;
889 if (rhs->type == CPP_PADDING)
891 if (rhs->flags & PASTE_LEFT)
892 abort ();
894 if (!paste_tokens (pfile, virt_loc, &lhs, rhs))
895 break;
897 while (rhs->flags & PASTE_LEFT);
899 /* Put the resulting token in its own context. */
900 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
902 source_location *virt_locs = NULL;
903 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
904 tokens_buff_add_token (token_buf, virt_locs, lhs,
905 virt_loc, 0, NULL, 0);
906 push_extended_tokens_context (pfile, context->c.mc->macro_node,
907 token_buf, virt_locs,
908 (const cpp_token **)token_buf->base, 1);
910 else
911 _cpp_push_token_context (pfile, NULL, lhs, 1);
914 /* Returns TRUE if the number of arguments ARGC supplied in an
915 invocation of the MACRO referenced by NODE is valid. An empty
916 invocation to a macro with no parameters should pass ARGC as zero.
918 Note that MACRO cannot necessarily be deduced from NODE, in case
919 NODE was redefined whilst collecting arguments. */
920 bool
921 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
923 if (argc == macro->paramc)
924 return true;
926 if (argc < macro->paramc)
928 /* In C++2a (here the va_opt flag is used), and also as a GNU
929 extension, variadic arguments are allowed to not appear in
930 the invocation at all.
931 e.g. #define debug(format, args...) something
932 debug("string");
934 This is exactly the same as if an empty variadic list had been
935 supplied - debug("string", ). */
937 if (argc + 1 == macro->paramc && macro->variadic)
939 if (CPP_PEDANTIC (pfile) && ! macro->syshdr
940 && ! CPP_OPTION (pfile, va_opt))
942 if (CPP_OPTION (pfile, cplusplus))
943 cpp_error (pfile, CPP_DL_PEDWARN,
944 "ISO C++11 requires at least one argument "
945 "for the \"...\" in a variadic macro");
946 else
947 cpp_error (pfile, CPP_DL_PEDWARN,
948 "ISO C99 requires at least one argument "
949 "for the \"...\" in a variadic macro");
951 return true;
954 cpp_error (pfile, CPP_DL_ERROR,
955 "macro \"%s\" requires %u arguments, but only %u given",
956 NODE_NAME (node), macro->paramc, argc);
958 else
959 cpp_error (pfile, CPP_DL_ERROR,
960 "macro \"%s\" passed %u arguments, but takes just %u",
961 NODE_NAME (node), argc, macro->paramc);
963 return false;
966 /* Reads and returns the arguments to a function-like macro
967 invocation. Assumes the opening parenthesis has been processed.
968 If there is an error, emits an appropriate diagnostic and returns
969 NULL. Each argument is terminated by a CPP_EOF token, for the
970 future benefit of expand_arg(). If there are any deferred
971 #pragma directives among macro arguments, store pointers to the
972 CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
974 What is returned is the buffer that contains the memory allocated
975 to hold the macro arguments. NODE is the name of the macro this
976 function is dealing with. If NUM_ARGS is non-NULL, *NUM_ARGS is
977 set to the actual number of macro arguments allocated in the
978 returned buffer. */
979 static _cpp_buff *
980 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
981 _cpp_buff **pragma_buff, unsigned *num_args)
983 _cpp_buff *buff, *base_buff;
984 cpp_macro *macro;
985 macro_arg *args, *arg;
986 const cpp_token *token;
987 unsigned int argc;
988 source_location virt_loc;
989 bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
990 unsigned num_args_alloced = 0;
992 macro = node->value.macro;
993 if (macro->paramc)
994 argc = macro->paramc;
995 else
996 argc = 1;
998 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
999 #define ARG_TOKENS_EXTENT 1000
1001 buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
1002 * sizeof (cpp_token *)
1003 + sizeof (macro_arg)));
1004 base_buff = buff;
1005 args = (macro_arg *) buff->base;
1006 memset (args, 0, argc * sizeof (macro_arg));
1007 buff->cur = (unsigned char *) &args[argc];
1008 arg = args, argc = 0;
1010 /* Collect the tokens making up each argument. We don't yet know
1011 how many arguments have been supplied, whether too many or too
1012 few. Hence the slightly bizarre usage of "argc" and "arg". */
1015 unsigned int paren_depth = 0;
1016 unsigned int ntokens = 0;
1017 unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
1018 num_args_alloced++;
1020 argc++;
1021 arg->first = (const cpp_token **) buff->cur;
1022 if (track_macro_expansion_p)
1024 virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
1025 arg->virt_locs = XNEWVEC (source_location,
1026 virt_locs_capacity);
1029 for (;;)
1031 /* Require space for 2 new tokens (including a CPP_EOF). */
1032 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
1034 buff = _cpp_append_extend_buff (pfile, buff,
1035 ARG_TOKENS_EXTENT
1036 * sizeof (cpp_token *));
1037 arg->first = (const cpp_token **) buff->cur;
1039 if (track_macro_expansion_p
1040 && (ntokens + 2 > virt_locs_capacity))
1042 virt_locs_capacity += ARG_TOKENS_EXTENT;
1043 arg->virt_locs = XRESIZEVEC (source_location,
1044 arg->virt_locs,
1045 virt_locs_capacity);
1048 token = cpp_get_token_1 (pfile, &virt_loc);
1050 if (token->type == CPP_PADDING)
1052 /* Drop leading padding. */
1053 if (ntokens == 0)
1054 continue;
1056 else if (token->type == CPP_OPEN_PAREN)
1057 paren_depth++;
1058 else if (token->type == CPP_CLOSE_PAREN)
1060 if (paren_depth-- == 0)
1061 break;
1063 else if (token->type == CPP_COMMA)
1065 /* A comma does not terminate an argument within
1066 parentheses or as part of a variable argument. */
1067 if (paren_depth == 0
1068 && ! (macro->variadic && argc == macro->paramc))
1069 break;
1071 else if (token->type == CPP_EOF
1072 || (token->type == CPP_HASH && token->flags & BOL))
1073 break;
1074 else if (token->type == CPP_PRAGMA)
1076 cpp_token *newtok = _cpp_temp_token (pfile);
1078 /* CPP_PRAGMA token lives in directive_result, which will
1079 be overwritten on the next directive. */
1080 *newtok = *token;
1081 token = newtok;
1084 if (*pragma_buff == NULL
1085 || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
1087 _cpp_buff *next;
1088 if (*pragma_buff == NULL)
1089 *pragma_buff
1090 = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
1091 else
1093 next = *pragma_buff;
1094 *pragma_buff
1095 = _cpp_get_buff (pfile,
1096 (BUFF_FRONT (*pragma_buff)
1097 - (*pragma_buff)->base) * 2);
1098 (*pragma_buff)->next = next;
1101 *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
1102 BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
1103 if (token->type == CPP_PRAGMA_EOL)
1104 break;
1105 token = cpp_get_token_1 (pfile, &virt_loc);
1107 while (token->type != CPP_EOF);
1109 /* In deferred pragmas parsing_args and prevent_expansion
1110 had been changed, reset it. */
1111 pfile->state.parsing_args = 2;
1112 pfile->state.prevent_expansion = 1;
1114 if (token->type == CPP_EOF)
1115 break;
1116 else
1117 continue;
1119 set_arg_token (arg, token, virt_loc,
1120 ntokens, MACRO_ARG_TOKEN_NORMAL,
1121 CPP_OPTION (pfile, track_macro_expansion));
1122 ntokens++;
1125 /* Drop trailing padding. */
1126 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
1127 ntokens--;
1129 arg->count = ntokens;
1130 set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
1131 ntokens, MACRO_ARG_TOKEN_NORMAL,
1132 CPP_OPTION (pfile, track_macro_expansion));
1134 /* Terminate the argument. Excess arguments loop back and
1135 overwrite the final legitimate argument, before failing. */
1136 if (argc <= macro->paramc)
1138 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
1139 if (argc != macro->paramc)
1140 arg++;
1143 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
1145 if (token->type == CPP_EOF)
1147 /* We still need the CPP_EOF to end directives, and to end
1148 pre-expansion of a macro argument. Step back is not
1149 unconditional, since we don't want to return a CPP_EOF to our
1150 callers at the end of an -include-d file. */
1151 if (pfile->context->prev || pfile->state.in_directive)
1152 _cpp_backup_tokens (pfile, 1);
1153 cpp_error (pfile, CPP_DL_ERROR,
1154 "unterminated argument list invoking macro \"%s\"",
1155 NODE_NAME (node));
1157 else
1159 /* A single empty argument is counted as no argument. */
1160 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
1161 argc = 0;
1162 if (_cpp_arguments_ok (pfile, macro, node, argc))
1164 /* GCC has special semantics for , ## b where b is a varargs
1165 parameter: we remove the comma if b was omitted entirely.
1166 If b was merely an empty argument, the comma is retained.
1167 If the macro takes just one (varargs) parameter, then we
1168 retain the comma only if we are standards conforming.
1170 If FIRST is NULL replace_args () swallows the comma. */
1171 if (macro->variadic && (argc < macro->paramc
1172 || (argc == 1 && args[0].count == 0
1173 && !CPP_OPTION (pfile, std))))
1174 args[macro->paramc - 1].first = NULL;
1175 if (num_args)
1176 *num_args = num_args_alloced;
1177 return base_buff;
1181 /* An error occurred. */
1182 _cpp_release_buff (pfile, base_buff);
1183 return NULL;
1186 /* Search for an opening parenthesis to the macro of NODE, in such a
1187 way that, if none is found, we don't lose the information in any
1188 intervening padding tokens. If we find the parenthesis, collect
1189 the arguments and return the buffer containing them. PRAGMA_BUFF
1190 argument is the same as in collect_args. If NUM_ARGS is non-NULL,
1191 *NUM_ARGS is set to the number of arguments contained in the
1192 returned buffer. */
1193 static _cpp_buff *
1194 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
1195 _cpp_buff **pragma_buff, unsigned *num_args)
1197 const cpp_token *token, *padding = NULL;
1199 for (;;)
1201 token = cpp_get_token (pfile);
1202 if (token->type != CPP_PADDING)
1203 break;
1204 if (padding == NULL
1205 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
1206 padding = token;
1209 if (token->type == CPP_OPEN_PAREN)
1211 pfile->state.parsing_args = 2;
1212 return collect_args (pfile, node, pragma_buff, num_args);
1215 /* CPP_EOF can be the end of macro arguments, or the end of the
1216 file. We mustn't back up over the latter. Ugh. */
1217 if (token->type != CPP_EOF || token == &pfile->eof)
1219 /* Back up. We may have skipped padding, in which case backing
1220 up more than one token when expanding macros is in general
1221 too difficult. We re-insert it in its own context. */
1222 _cpp_backup_tokens (pfile, 1);
1223 if (padding)
1224 _cpp_push_token_context (pfile, NULL, padding, 1);
1227 return NULL;
1230 /* Return the real number of tokens in the expansion of MACRO. */
1231 static inline unsigned int
1232 macro_real_token_count (const cpp_macro *macro)
1234 unsigned int i;
1235 if (__builtin_expect (!macro->extra_tokens, true))
1236 return macro->count;
1237 for (i = 0; i < macro->count; i++)
1238 if (macro->exp.tokens[i].type == CPP_PASTE)
1239 return i;
1240 abort ();
1243 /* Push the context of a macro with hash entry NODE onto the context
1244 stack. If we can successfully expand the macro, we push a context
1245 containing its yet-to-be-rescanned replacement list and return one.
1246 If there were additionally any unexpanded deferred #pragma
1247 directives among macro arguments, push another context containing
1248 the pragma tokens before the yet-to-be-rescanned replacement list
1249 and return two. Otherwise, we don't push a context and return
1250 zero. LOCATION is the location of the expansion point of the
1251 macro. */
1252 static int
1253 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1254 const cpp_token *result, source_location location)
1256 /* The presence of a macro invalidates a file's controlling macro. */
1257 pfile->mi_valid = false;
1259 pfile->state.angled_headers = false;
1261 /* From here to when we push the context for the macro later down
1262 this function, we need to flag the fact that we are about to
1263 expand a macro. This is useful when -ftrack-macro-expansion is
1264 turned off. In that case, we need to record the location of the
1265 expansion point of the top-most macro we are about to to expand,
1266 into pfile->invocation_location. But we must not record any such
1267 location once the process of expanding the macro starts; that is,
1268 we must not do that recording between now and later down this
1269 function where set this flag to FALSE. */
1270 pfile->about_to_expand_macro_p = true;
1272 if ((node->flags & NODE_BUILTIN) && !(node->flags & NODE_USED))
1274 node->flags |= NODE_USED;
1275 if ((!pfile->cb.user_builtin_macro
1276 || !pfile->cb.user_builtin_macro (pfile, node))
1277 && pfile->cb.used_define)
1278 pfile->cb.used_define (pfile, pfile->directive_line, node);
1281 /* Handle standard macros. */
1282 if (! (node->flags & NODE_BUILTIN))
1284 cpp_macro *macro = node->value.macro;
1285 _cpp_buff *pragma_buff = NULL;
1287 if (macro->fun_like)
1289 _cpp_buff *buff;
1290 unsigned num_args = 0;
1292 pfile->state.prevent_expansion++;
1293 pfile->keep_tokens++;
1294 pfile->state.parsing_args = 1;
1295 buff = funlike_invocation_p (pfile, node, &pragma_buff,
1296 &num_args);
1297 pfile->state.parsing_args = 0;
1298 pfile->keep_tokens--;
1299 pfile->state.prevent_expansion--;
1301 if (buff == NULL)
1303 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1304 cpp_warning (pfile, CPP_W_TRADITIONAL,
1305 "function-like macro \"%s\" must be used with arguments in traditional C",
1306 NODE_NAME (node));
1308 if (pragma_buff)
1309 _cpp_release_buff (pfile, pragma_buff);
1311 pfile->about_to_expand_macro_p = false;
1312 return 0;
1315 if (macro->paramc > 0)
1316 replace_args (pfile, node, macro,
1317 (macro_arg *) buff->base,
1318 location);
1319 /* Free the memory used by the arguments of this
1320 function-like macro. This memory has been allocated by
1321 funlike_invocation_p and by replace_args. */
1322 delete_macro_args (buff, num_args);
1325 /* Disable the macro within its expansion. */
1326 node->flags |= NODE_DISABLED;
1328 if (!(node->flags & NODE_USED))
1330 node->flags |= NODE_USED;
1331 if (pfile->cb.used_define)
1332 pfile->cb.used_define (pfile, pfile->directive_line, node);
1335 if (pfile->cb.used)
1336 pfile->cb.used (pfile, location, node);
1338 macro->used = 1;
1340 if (macro->paramc == 0)
1342 unsigned tokens_count = macro_real_token_count (macro);
1343 if (CPP_OPTION (pfile, track_macro_expansion))
1345 unsigned int i;
1346 const cpp_token *src = macro->exp.tokens;
1347 const line_map_macro *map;
1348 source_location *virt_locs = NULL;
1349 _cpp_buff *macro_tokens
1350 = tokens_buff_new (pfile, tokens_count, &virt_locs);
1352 /* Create a macro map to record the locations of the
1353 tokens that are involved in the expansion. LOCATION
1354 is the location of the macro expansion point. */
1355 map = linemap_enter_macro (pfile->line_table,
1356 node, location, tokens_count);
1357 for (i = 0; i < tokens_count; ++i)
1359 tokens_buff_add_token (macro_tokens, virt_locs,
1360 src, src->src_loc,
1361 src->src_loc, map, i);
1362 ++src;
1364 push_extended_tokens_context (pfile, node,
1365 macro_tokens,
1366 virt_locs,
1367 (const cpp_token **)
1368 macro_tokens->base,
1369 tokens_count);
1371 else
1372 _cpp_push_token_context (pfile, node, macro->exp.tokens,
1373 tokens_count);
1374 num_macro_tokens_counter += tokens_count;
1377 if (pragma_buff)
1379 if (!pfile->state.in_directive)
1380 _cpp_push_token_context (pfile, NULL,
1381 padding_token (pfile, result), 1);
1384 unsigned tokens_count;
1385 _cpp_buff *tail = pragma_buff->next;
1386 pragma_buff->next = NULL;
1387 tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1388 - (const cpp_token **) pragma_buff->base);
1389 push_ptoken_context (pfile, NULL, pragma_buff,
1390 (const cpp_token **) pragma_buff->base,
1391 tokens_count);
1392 pragma_buff = tail;
1393 if (!CPP_OPTION (pfile, track_macro_expansion))
1394 num_macro_tokens_counter += tokens_count;
1397 while (pragma_buff != NULL);
1398 pfile->about_to_expand_macro_p = false;
1399 return 2;
1402 pfile->about_to_expand_macro_p = false;
1403 return 1;
1406 pfile->about_to_expand_macro_p = false;
1407 /* Handle built-in macros and the _Pragma operator. */
1409 source_location loc, expand_loc;
1411 if (/* The top-level macro invocation that triggered the expansion
1412 we are looking at is with a standard macro ...*/
1413 !(pfile->top_most_macro_node->flags & NODE_BUILTIN)
1414 /* ... and it's a function-like macro invocation. */
1415 && pfile->top_most_macro_node->value.macro->fun_like)
1417 /* Then the location of the end of the macro invocation is the
1418 location of the closing parenthesis. */
1419 loc = pfile->cur_token[-1].src_loc;
1420 expand_loc = loc;
1422 else
1424 /* Otherwise, the location of the end of the macro invocation is
1425 the location of the expansion point of that top-level macro
1426 invocation. */
1427 loc = location;
1428 expand_loc = pfile->invocation_location;
1431 return builtin_macro (pfile, node, loc, expand_loc);
1435 /* De-allocate the memory used by BUFF which is an array of instances
1436 of macro_arg. NUM_ARGS is the number of instances of macro_arg
1437 present in BUFF. */
1438 static void
1439 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1441 macro_arg *macro_args;
1442 unsigned i;
1444 if (buff == NULL)
1445 return;
1447 macro_args = (macro_arg *) buff->base;
1449 /* Walk instances of macro_arg to free their expanded tokens as well
1450 as their macro_arg::virt_locs members. */
1451 for (i = 0; i < num_args; ++i)
1453 if (macro_args[i].expanded)
1455 free (macro_args[i].expanded);
1456 macro_args[i].expanded = NULL;
1458 if (macro_args[i].virt_locs)
1460 free (macro_args[i].virt_locs);
1461 macro_args[i].virt_locs = NULL;
1463 if (macro_args[i].expanded_virt_locs)
1465 free (macro_args[i].expanded_virt_locs);
1466 macro_args[i].expanded_virt_locs = NULL;
1469 _cpp_free_buff (buff);
1472 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1473 to set, LOCATION is its virtual location. "Virtual" location means
1474 the location that encodes loci across macro expansion. Otherwise
1475 it has to be TOKEN->SRC_LOC. KIND is the kind of tokens the
1476 argument ARG is supposed to contain. Note that ARG must be
1477 tailored so that it has enough room to contain INDEX + 1 numbers of
1478 tokens, at least. */
1479 static void
1480 set_arg_token (macro_arg *arg, const cpp_token *token,
1481 source_location location, size_t index,
1482 enum macro_arg_token_kind kind,
1483 bool track_macro_exp_p)
1485 const cpp_token **token_ptr;
1486 source_location *loc = NULL;
1488 token_ptr =
1489 arg_token_ptr_at (arg, index, kind,
1490 track_macro_exp_p ? &loc : NULL);
1491 *token_ptr = token;
1493 if (loc != NULL)
1495 /* We can't set the location of a stringified argument
1496 token and we can't set any location if we aren't tracking
1497 macro expansion locations. */
1498 gcc_checking_assert (kind != MACRO_ARG_TOKEN_STRINGIFIED
1499 && track_macro_exp_p);
1500 *loc = location;
1504 /* Get the pointer to the location of the argument token of the
1505 function-like macro argument ARG. This function must be called
1506 only when we -ftrack-macro-expansion is on. */
1507 static const source_location *
1508 get_arg_token_location (const macro_arg *arg,
1509 enum macro_arg_token_kind kind)
1511 const source_location *loc = NULL;
1512 const cpp_token **token_ptr =
1513 arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1515 if (token_ptr == NULL)
1516 return NULL;
1518 return loc;
1521 /* Return the pointer to the INDEXth token of the macro argument ARG.
1522 KIND specifies the kind of token the macro argument ARG contains.
1523 If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1524 of the virtual location of the returned token if the
1525 -ftrack-macro-expansion flag is on; otherwise, it's set to the
1526 spelling location of the returned token. */
1527 static const cpp_token **
1528 arg_token_ptr_at (const macro_arg *arg, size_t index,
1529 enum macro_arg_token_kind kind,
1530 source_location **virt_location)
1532 const cpp_token **tokens_ptr = NULL;
1534 switch (kind)
1536 case MACRO_ARG_TOKEN_NORMAL:
1537 tokens_ptr = arg->first;
1538 break;
1539 case MACRO_ARG_TOKEN_STRINGIFIED:
1540 tokens_ptr = (const cpp_token **) &arg->stringified;
1541 break;
1542 case MACRO_ARG_TOKEN_EXPANDED:
1543 tokens_ptr = arg->expanded;
1544 break;
1547 if (tokens_ptr == NULL)
1548 /* This can happen for e.g, an empty token argument to a
1549 funtion-like macro. */
1550 return tokens_ptr;
1552 if (virt_location)
1554 if (kind == MACRO_ARG_TOKEN_NORMAL)
1555 *virt_location = &arg->virt_locs[index];
1556 else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1557 *virt_location = &arg->expanded_virt_locs[index];
1558 else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1559 *virt_location =
1560 (source_location *) &tokens_ptr[index]->src_loc;
1562 return &tokens_ptr[index];
1565 /* Initialize an iterator so that it iterates over the tokens of a
1566 function-like macro argument. KIND is the kind of tokens we want
1567 ITER to iterate over. TOKEN_PTR points the first token ITER will
1568 iterate over. */
1569 static void
1570 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1571 bool track_macro_exp_p,
1572 enum macro_arg_token_kind kind,
1573 const macro_arg *arg,
1574 const cpp_token **token_ptr)
1576 iter->track_macro_exp_p = track_macro_exp_p;
1577 iter->kind = kind;
1578 iter->token_ptr = token_ptr;
1579 /* Unconditionally initialize this so that the compiler doesn't warn
1580 about iter->location_ptr being possibly uninitialized later after
1581 this code has been inlined somewhere. */
1582 iter->location_ptr = NULL;
1583 if (track_macro_exp_p)
1584 iter->location_ptr = get_arg_token_location (arg, kind);
1585 #if CHECKING_P
1586 iter->num_forwards = 0;
1587 if (track_macro_exp_p
1588 && token_ptr != NULL
1589 && iter->location_ptr == NULL)
1590 abort ();
1591 #endif
1594 /* Move the iterator one token forward. Note that if IT was
1595 initialized on an argument that has a stringified token, moving it
1596 forward doesn't make sense as a stringified token is essentially one
1597 string. */
1598 static void
1599 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1601 switch (it->kind)
1603 case MACRO_ARG_TOKEN_NORMAL:
1604 case MACRO_ARG_TOKEN_EXPANDED:
1605 it->token_ptr++;
1606 if (it->track_macro_exp_p)
1607 it->location_ptr++;
1608 break;
1609 case MACRO_ARG_TOKEN_STRINGIFIED:
1610 #if CHECKING_P
1611 if (it->num_forwards > 0)
1612 abort ();
1613 #endif
1614 break;
1617 #if CHECKING_P
1618 it->num_forwards++;
1619 #endif
1622 /* Return the token pointed to by the iterator. */
1623 static const cpp_token *
1624 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1626 #if CHECKING_P
1627 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1628 && it->num_forwards > 0)
1629 abort ();
1630 #endif
1631 if (it->token_ptr == NULL)
1632 return NULL;
1633 return *it->token_ptr;
1636 /* Return the location of the token pointed to by the iterator.*/
1637 static source_location
1638 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1640 #if CHECKING_P
1641 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1642 && it->num_forwards > 0)
1643 abort ();
1644 #endif
1645 if (it->track_macro_exp_p)
1646 return *it->location_ptr;
1647 else
1648 return (*it->token_ptr)->src_loc;
1651 /* Return the index of a token [resulting from macro expansion] inside
1652 the total list of tokens resulting from a given macro
1653 expansion. The index can be different depending on whether if we
1654 want each tokens resulting from function-like macro arguments
1655 expansion to have a different location or not.
1657 E.g, consider this function-like macro:
1659 #define M(x) x - 3
1661 Then consider us "calling" it (and thus expanding it) like:
1663 M(1+4)
1665 It will be expanded into:
1667 1+4-3
1669 Let's consider the case of the token '4'.
1671 Its index can be 2 (it's the third token of the set of tokens
1672 resulting from the expansion) or it can be 0 if we consider that
1673 all tokens resulting from the expansion of the argument "1+2" have
1674 the same index, which is 0. In this later case, the index of token
1675 '-' would then be 1 and the index of token '3' would be 2.
1677 The later case is useful to use less memory e.g, for the case of
1678 the user using the option -ftrack-macro-expansion=1.
1680 ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1681 are interested in. CUR_REPLACEMENT_TOKEN is the token of the macro
1682 parameter (inside the macro replacement list) that corresponds to
1683 the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1686 If we refer to the example above, for the '4' argument token,
1687 ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1688 would be set to the token 'x', in the replacement list "x - 3" of
1689 macro M.
1691 This is a subroutine of replace_args. */
1692 inline static unsigned
1693 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1694 const cpp_token *cur_replacement_token,
1695 unsigned absolute_token_index)
1697 if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1698 return absolute_token_index;
1699 return cur_replacement_token - macro->exp.tokens;
1702 /* Replace the parameters in a function-like macro of NODE with the
1703 actual ARGS, and place the result in a newly pushed token context.
1704 Expand each argument before replacing, unless it is operated upon
1705 by the # or ## operators. EXPANSION_POINT_LOC is the location of
1706 the expansion point of the macro. E.g, the location of the
1707 function-like macro invocation. */
1708 static void
1709 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1710 macro_arg *args, source_location expansion_point_loc)
1712 unsigned int i, total;
1713 const cpp_token *src, *limit;
1714 const cpp_token **first = NULL;
1715 macro_arg *arg;
1716 _cpp_buff *buff = NULL;
1717 source_location *virt_locs = NULL;
1718 unsigned int exp_count;
1719 const line_map_macro *map = NULL;
1720 int track_macro_exp;
1722 /* First, fully macro-expand arguments, calculating the number of
1723 tokens in the final expansion as we go. The ordering of the if
1724 statements below is subtle; we must handle stringification before
1725 pasting. */
1727 /* EXP_COUNT is the number of tokens in the macro replacement
1728 list. TOTAL is the number of tokens /after/ macro parameters
1729 have been replaced by their arguments. */
1730 exp_count = macro_real_token_count (macro);
1731 total = exp_count;
1732 limit = macro->exp.tokens + exp_count;
1734 for (src = macro->exp.tokens; src < limit; src++)
1735 if (src->type == CPP_MACRO_ARG)
1737 /* Leading and trailing padding tokens. */
1738 total += 2;
1739 /* Account for leading and padding tokens in exp_count too.
1740 This is going to be important later down this function,
1741 when we want to handle the case of (track_macro_exp <
1742 2). */
1743 exp_count += 2;
1745 /* We have an argument. If it is not being stringified or
1746 pasted it is macro-replaced before insertion. */
1747 arg = &args[src->val.macro_arg.arg_no - 1];
1749 if (src->flags & STRINGIFY_ARG)
1751 if (!arg->stringified)
1752 arg->stringified = stringify_arg (pfile, arg);
1754 else if ((src->flags & PASTE_LEFT)
1755 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1756 total += arg->count - 1;
1757 else
1759 if (!arg->expanded)
1760 expand_arg (pfile, arg);
1761 total += arg->expanded_count - 1;
1765 /* When the compiler is called with the -ftrack-macro-expansion
1766 flag, we need to keep track of the location of each token that
1767 results from macro expansion.
1769 A token resulting from macro expansion is not a new token. It is
1770 simply the same token as the token coming from the macro
1771 definition. The new things that are allocated are the buffer
1772 that holds the tokens resulting from macro expansion and a new
1773 location that records many things like the locus of the expansion
1774 point as well as the original locus inside the definition of the
1775 macro. This location is called a virtual location.
1777 So the buffer BUFF holds a set of cpp_token*, and the buffer
1778 VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1780 Both of these two buffers are going to be hung off of the macro
1781 context, when the latter is pushed. The memory allocated to
1782 store the tokens and their locations is going to be freed once
1783 the context of macro expansion is popped.
1785 As far as tokens are concerned, the memory overhead of
1786 -ftrack-macro-expansion is proportional to the number of
1787 macros that get expanded multiplied by sizeof (source_location).
1788 The good news is that extra memory gets freed when the macro
1789 context is freed, i.e shortly after the macro got expanded. */
1791 /* Is the -ftrack-macro-expansion flag in effect? */
1792 track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1794 /* Now allocate memory space for tokens and locations resulting from
1795 the macro expansion, copy the tokens and replace the arguments.
1796 This memory must be freed when the context of the macro MACRO is
1797 popped. */
1798 buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1800 first = (const cpp_token **) buff->base;
1802 /* Create a macro map to record the locations of the tokens that are
1803 involved in the expansion. Note that the expansion point is set
1804 to the location of the closing parenthesis. Otherwise, the
1805 subsequent map created for the first token that comes after the
1806 macro map might have a wrong line number. That would lead to
1807 tokens with wrong line numbers after the macro expansion. This
1808 adds up to the memory overhead of the -ftrack-macro-expansion
1809 flag; for every macro that is expanded, a "macro map" is
1810 created. */
1811 if (track_macro_exp)
1813 int num_macro_tokens = total;
1814 if (track_macro_exp < 2)
1815 /* Then the number of macro tokens won't take in account the
1816 fact that function-like macro arguments can expand to
1817 multiple tokens. This is to save memory at the expense of
1818 accuracy.
1820 Suppose we have #define SQARE(A) A * A
1822 And then we do SQARE(2+3)
1824 Then the tokens 2, +, 3, will have the same location,
1825 saying they come from the expansion of the argument A. */
1826 num_macro_tokens = exp_count;
1827 map = linemap_enter_macro (pfile->line_table, node,
1828 expansion_point_loc,
1829 num_macro_tokens);
1831 i = 0;
1832 vaopt_state vaopt_tracker (pfile, macro->variadic,
1833 args[macro->paramc - 1].count > 0);
1834 for (src = macro->exp.tokens; src < limit; src++)
1836 unsigned int arg_tokens_count;
1837 macro_arg_token_iter from;
1838 const cpp_token **paste_flag = NULL;
1839 const cpp_token **tmp_token_ptr;
1841 /* __VA_OPT__ handling. */
1842 if (vaopt_tracker.update (src) != vaopt_state::INCLUDE)
1843 continue;
1845 if (src->type != CPP_MACRO_ARG)
1847 /* Allocate a virtual location for token SRC, and add that
1848 token and its virtual location into the buffers BUFF and
1849 VIRT_LOCS. */
1850 unsigned index = expanded_token_index (pfile, macro, src, i);
1851 tokens_buff_add_token (buff, virt_locs, src,
1852 src->src_loc, src->src_loc,
1853 map, index);
1854 i += 1;
1855 continue;
1858 paste_flag = 0;
1859 arg = &args[src->val.macro_arg.arg_no - 1];
1860 /* SRC is a macro parameter that we need to replace with its
1861 corresponding argument. So at some point we'll need to
1862 iterate over the tokens of the macro argument and copy them
1863 into the "place" now holding the correspondig macro
1864 parameter. We are going to use the iterator type
1865 macro_argo_token_iter to handle that iterating. The 'if'
1866 below is to initialize the iterator depending on the type of
1867 tokens the macro argument has. It also does some adjustment
1868 related to padding tokens and some pasting corner cases. */
1869 if (src->flags & STRINGIFY_ARG)
1871 arg_tokens_count = 1;
1872 macro_arg_token_iter_init (&from,
1873 CPP_OPTION (pfile,
1874 track_macro_expansion),
1875 MACRO_ARG_TOKEN_STRINGIFIED,
1876 arg, &arg->stringified);
1878 else if (src->flags & PASTE_LEFT)
1880 arg_tokens_count = arg->count;
1881 macro_arg_token_iter_init (&from,
1882 CPP_OPTION (pfile,
1883 track_macro_expansion),
1884 MACRO_ARG_TOKEN_NORMAL,
1885 arg, arg->first);
1887 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1889 int num_toks;
1890 arg_tokens_count = arg->count;
1891 macro_arg_token_iter_init (&from,
1892 CPP_OPTION (pfile,
1893 track_macro_expansion),
1894 MACRO_ARG_TOKEN_NORMAL,
1895 arg, arg->first);
1897 num_toks = tokens_buff_count (buff);
1899 if (num_toks != 0)
1901 /* So the current parameter token is pasted to the previous
1902 token in the replacement list. Let's look at what
1903 we have as previous and current arguments. */
1905 /* This is the previous argument's token ... */
1906 tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1908 if ((*tmp_token_ptr)->type == CPP_COMMA
1909 && macro->variadic
1910 && src->val.macro_arg.arg_no == macro->paramc)
1912 /* ... which is a comma; and the current parameter
1913 is the last parameter of a variadic function-like
1914 macro. If the argument to the current last
1915 parameter is NULL, then swallow the comma,
1916 otherwise drop the paste flag. */
1917 if (macro_arg_token_iter_get_token (&from) == NULL)
1918 tokens_buff_remove_last_token (buff);
1919 else
1920 paste_flag = tmp_token_ptr;
1922 /* Remove the paste flag if the RHS is a placemarker. */
1923 else if (arg_tokens_count == 0)
1924 paste_flag = tmp_token_ptr;
1927 else
1929 arg_tokens_count = arg->expanded_count;
1930 macro_arg_token_iter_init (&from,
1931 CPP_OPTION (pfile,
1932 track_macro_expansion),
1933 MACRO_ARG_TOKEN_EXPANDED,
1934 arg, arg->expanded);
1937 /* Padding on the left of an argument (unless RHS of ##). */
1938 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1939 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1941 const cpp_token *t = padding_token (pfile, src);
1942 unsigned index = expanded_token_index (pfile, macro, src, i);
1943 /* Allocate a virtual location for the padding token and
1944 append the token and its location to BUFF and
1945 VIRT_LOCS. */
1946 tokens_buff_add_token (buff, virt_locs, t,
1947 t->src_loc, t->src_loc,
1948 map, index);
1951 if (arg_tokens_count)
1953 /* So now we've got the number of tokens that make up the
1954 argument that is going to replace the current parameter
1955 in the macro's replacement list. */
1956 unsigned int j;
1957 for (j = 0; j < arg_tokens_count; ++j)
1959 /* So if track_macro_exp is < 2, the user wants to
1960 save extra memory while tracking macro expansion
1961 locations. So in that case here is what we do:
1963 Suppose we have #define SQARE(A) A * A
1965 And then we do SQARE(2+3)
1967 Then the tokens 2, +, 3, will have the same location,
1968 saying they come from the expansion of the argument
1971 So that means we are going to ignore the COUNT tokens
1972 resulting from the expansion of the current macro
1973 arugment. In other words all the ARG_TOKENS_COUNT tokens
1974 resulting from the expansion of the macro argument will
1975 have the index I. Normally, each of those token should
1976 have index I+J. */
1977 unsigned token_index = i;
1978 unsigned index;
1979 if (track_macro_exp > 1)
1980 token_index += j;
1982 index = expanded_token_index (pfile, macro, src, token_index);
1983 tokens_buff_add_token (buff, virt_locs,
1984 macro_arg_token_iter_get_token (&from),
1985 macro_arg_token_iter_get_location (&from),
1986 src->src_loc, map, index);
1987 macro_arg_token_iter_forward (&from);
1990 /* With a non-empty argument on the LHS of ##, the last
1991 token should be flagged PASTE_LEFT. */
1992 if (src->flags & PASTE_LEFT)
1993 paste_flag =
1994 (const cpp_token **) tokens_buff_last_token_ptr (buff);
1996 else if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99)
1997 && ! macro->syshdr && ! cpp_in_system_header (pfile))
1999 if (CPP_OPTION (pfile, cplusplus))
2000 cpp_pedwarning (pfile, CPP_W_PEDANTIC,
2001 "invoking macro %s argument %d: "
2002 "empty macro arguments are undefined"
2003 " in ISO C++98",
2004 NODE_NAME (node), src->val.macro_arg.arg_no);
2005 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat))
2006 cpp_pedwarning (pfile,
2007 CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2008 ? CPP_W_C90_C99_COMPAT : CPP_W_PEDANTIC,
2009 "invoking macro %s argument %d: "
2010 "empty macro arguments are undefined"
2011 " in ISO C90",
2012 NODE_NAME (node), src->val.macro_arg.arg_no);
2014 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2015 && ! CPP_OPTION (pfile, cplusplus)
2016 && ! macro->syshdr && ! cpp_in_system_header (pfile))
2017 cpp_warning (pfile, CPP_W_C90_C99_COMPAT,
2018 "invoking macro %s argument %d: "
2019 "empty macro arguments are undefined"
2020 " in ISO C90",
2021 NODE_NAME (node), src->val.macro_arg.arg_no);
2023 /* Avoid paste on RHS (even case count == 0). */
2024 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
2026 const cpp_token *t = &pfile->avoid_paste;
2027 tokens_buff_add_token (buff, virt_locs,
2028 t, t->src_loc, t->src_loc,
2029 NULL, 0);
2032 /* Add a new paste flag, or remove an unwanted one. */
2033 if (paste_flag)
2035 cpp_token *token = _cpp_temp_token (pfile);
2036 token->type = (*paste_flag)->type;
2037 token->val = (*paste_flag)->val;
2038 if (src->flags & PASTE_LEFT)
2039 token->flags = (*paste_flag)->flags | PASTE_LEFT;
2040 else
2041 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
2042 *paste_flag = token;
2045 i += arg_tokens_count;
2048 if (track_macro_exp)
2049 push_extended_tokens_context (pfile, node, buff, virt_locs, first,
2050 tokens_buff_count (buff));
2051 else
2052 push_ptoken_context (pfile, node, buff, first,
2053 tokens_buff_count (buff));
2055 num_macro_tokens_counter += tokens_buff_count (buff);
2058 /* Return a special padding token, with padding inherited from SOURCE. */
2059 static const cpp_token *
2060 padding_token (cpp_reader *pfile, const cpp_token *source)
2062 cpp_token *result = _cpp_temp_token (pfile);
2064 result->type = CPP_PADDING;
2066 /* Data in GCed data structures cannot be made const so far, so we
2067 need a cast here. */
2068 result->val.source = (cpp_token *) source;
2069 result->flags = 0;
2070 return result;
2073 /* Get a new uninitialized context. Create a new one if we cannot
2074 re-use an old one. */
2075 static cpp_context *
2076 next_context (cpp_reader *pfile)
2078 cpp_context *result = pfile->context->next;
2080 if (result == 0)
2082 result = XNEW (cpp_context);
2083 memset (result, 0, sizeof (cpp_context));
2084 result->prev = pfile->context;
2085 result->next = 0;
2086 pfile->context->next = result;
2089 pfile->context = result;
2090 return result;
2093 /* Push a list of pointers to tokens. */
2094 static void
2095 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
2096 const cpp_token **first, unsigned int count)
2098 cpp_context *context = next_context (pfile);
2100 context->tokens_kind = TOKENS_KIND_INDIRECT;
2101 context->c.macro = macro;
2102 context->buff = buff;
2103 FIRST (context).ptoken = first;
2104 LAST (context).ptoken = first + count;
2107 /* Push a list of tokens.
2109 A NULL macro means that we should continue the current macro
2110 expansion, in essence. That means that if we are currently in a
2111 macro expansion context, we'll make the new pfile->context refer to
2112 the current macro. */
2113 void
2114 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
2115 const cpp_token *first, unsigned int count)
2117 cpp_context *context;
2119 if (macro == NULL)
2120 macro = macro_of_context (pfile->context);
2122 context = next_context (pfile);
2123 context->tokens_kind = TOKENS_KIND_DIRECT;
2124 context->c.macro = macro;
2125 context->buff = NULL;
2126 FIRST (context).token = first;
2127 LAST (context).token = first + count;
2130 /* Build a context containing a list of tokens as well as their
2131 virtual locations and push it. TOKENS_BUFF is the buffer that
2132 contains the tokens pointed to by FIRST. If TOKENS_BUFF is
2133 non-NULL, it means that the context owns it, meaning that
2134 _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
2135 contains the virtual locations.
2137 A NULL macro means that we should continue the current macro
2138 expansion, in essence. That means that if we are currently in a
2139 macro expansion context, we'll make the new pfile->context refer to
2140 the current macro. */
2141 static void
2142 push_extended_tokens_context (cpp_reader *pfile,
2143 cpp_hashnode *macro,
2144 _cpp_buff *token_buff,
2145 source_location *virt_locs,
2146 const cpp_token **first,
2147 unsigned int count)
2149 cpp_context *context;
2150 macro_context *m;
2152 if (macro == NULL)
2153 macro = macro_of_context (pfile->context);
2155 context = next_context (pfile);
2156 context->tokens_kind = TOKENS_KIND_EXTENDED;
2157 context->buff = token_buff;
2159 m = XNEW (macro_context);
2160 m->macro_node = macro;
2161 m->virt_locs = virt_locs;
2162 m->cur_virt_loc = virt_locs;
2163 context->c.mc = m;
2164 FIRST (context).ptoken = first;
2165 LAST (context).ptoken = first + count;
2168 /* Push a traditional macro's replacement text. */
2169 void
2170 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
2171 const uchar *start, size_t len)
2173 cpp_context *context = next_context (pfile);
2175 context->tokens_kind = TOKENS_KIND_DIRECT;
2176 context->c.macro = macro;
2177 context->buff = NULL;
2178 CUR (context) = start;
2179 RLIMIT (context) = start + len;
2180 macro->flags |= NODE_DISABLED;
2183 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
2184 for the purpose of storing them on a cpp_context. If VIRT_LOCS is
2185 non-null (which means that -ftrack-macro-expansion is on),
2186 *VIRT_LOCS is set to a newly allocated buffer that is supposed to
2187 hold the virtual locations of the tokens resulting from macro
2188 expansion. */
2189 static _cpp_buff*
2190 tokens_buff_new (cpp_reader *pfile, size_t len,
2191 source_location **virt_locs)
2193 size_t tokens_size = len * sizeof (cpp_token *);
2194 size_t locs_size = len * sizeof (source_location);
2196 if (virt_locs != NULL)
2197 *virt_locs = XNEWVEC (source_location, locs_size);
2198 return _cpp_get_buff (pfile, tokens_size);
2201 /* Returns the number of tokens contained in a token buffer. The
2202 buffer holds a set of cpp_token*. */
2203 static size_t
2204 tokens_buff_count (_cpp_buff *buff)
2206 return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
2209 /* Return a pointer to the last token contained in the token buffer
2210 BUFF. */
2211 static const cpp_token **
2212 tokens_buff_last_token_ptr (_cpp_buff *buff)
2214 return &((const cpp_token **) BUFF_FRONT (buff))[-1];
2217 /* Remove the last token contained in the token buffer TOKENS_BUFF.
2218 If VIRT_LOCS_BUFF is non-NULL, it should point at the buffer
2219 containing the virtual locations of the tokens in TOKENS_BUFF; in
2220 which case the function updates that buffer as well. */
2221 static inline void
2222 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
2225 if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
2226 BUFF_FRONT (tokens_buff) =
2227 (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
2230 /* Insert a token into the token buffer at the position pointed to by
2231 DEST. Note that the buffer is not enlarged so the previous token
2232 that was at *DEST is overwritten. VIRT_LOC_DEST, if non-null,
2233 means -ftrack-macro-expansion is effect; it then points to where to
2234 insert the virtual location of TOKEN. TOKEN is the token to
2235 insert. VIRT_LOC is the virtual location of the token, i.e, the
2236 location possibly encoding its locus across macro expansion. If
2237 TOKEN is an argument of a function-like macro (inside a macro
2238 replacement list), PARM_DEF_LOC is the spelling location of the
2239 macro parameter that TOKEN is replacing, in the replacement list of
2240 the macro. If TOKEN is not an argument of a function-like macro or
2241 if it doesn't come from a macro expansion, then VIRT_LOC can just
2242 be set to the same value as PARM_DEF_LOC. If MAP is non null, it
2243 means TOKEN comes from a macro expansion and MAP is the macro map
2244 associated to the macro. MACRO_TOKEN_INDEX points to the index of
2245 the token in the macro map; it is not considered if MAP is NULL.
2247 Upon successful completion this function returns the a pointer to
2248 the position of the token coming right after the insertion
2249 point. */
2250 static inline const cpp_token **
2251 tokens_buff_put_token_to (const cpp_token **dest,
2252 source_location *virt_loc_dest,
2253 const cpp_token *token,
2254 source_location virt_loc,
2255 source_location parm_def_loc,
2256 const line_map_macro *map,
2257 unsigned int macro_token_index)
2259 source_location macro_loc = virt_loc;
2260 const cpp_token **result;
2262 if (virt_loc_dest)
2264 /* -ftrack-macro-expansion is on. */
2265 if (map)
2266 macro_loc = linemap_add_macro_token (map, macro_token_index,
2267 virt_loc, parm_def_loc);
2268 *virt_loc_dest = macro_loc;
2270 *dest = token;
2271 result = &dest[1];
2273 return result;
2276 /* Adds a token at the end of the tokens contained in BUFFER. Note
2277 that this function doesn't enlarge BUFFER when the number of tokens
2278 reaches BUFFER's size; it aborts in that situation.
2280 TOKEN is the token to append. VIRT_LOC is the virtual location of
2281 the token, i.e, the location possibly encoding its locus across
2282 macro expansion. If TOKEN is an argument of a function-like macro
2283 (inside a macro replacement list), PARM_DEF_LOC is the location of
2284 the macro parameter that TOKEN is replacing. If TOKEN doesn't come
2285 from a macro expansion, then VIRT_LOC can just be set to the same
2286 value as PARM_DEF_LOC. If MAP is non null, it means TOKEN comes
2287 from a macro expansion and MAP is the macro map associated to the
2288 macro. MACRO_TOKEN_INDEX points to the index of the token in the
2289 macro map; It is not considered if MAP is NULL. If VIRT_LOCS is
2290 non-null, it means -ftrack-macro-expansion is on; in which case
2291 this function adds the virtual location DEF_LOC to the VIRT_LOCS
2292 array, at the same index as the one of TOKEN in BUFFER. Upon
2293 successful completion this function returns the a pointer to the
2294 position of the token coming right after the insertion point. */
2295 static const cpp_token **
2296 tokens_buff_add_token (_cpp_buff *buffer,
2297 source_location *virt_locs,
2298 const cpp_token *token,
2299 source_location virt_loc,
2300 source_location parm_def_loc,
2301 const line_map_macro *map,
2302 unsigned int macro_token_index)
2304 const cpp_token **result;
2305 source_location *virt_loc_dest = NULL;
2306 unsigned token_index =
2307 (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2309 /* Abort if we pass the end the buffer. */
2310 if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2311 abort ();
2313 if (virt_locs != NULL)
2314 virt_loc_dest = &virt_locs[token_index];
2316 result =
2317 tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2318 virt_loc_dest, token, virt_loc, parm_def_loc,
2319 map, macro_token_index);
2321 BUFF_FRONT (buffer) = (unsigned char *) result;
2322 return result;
2325 /* Allocate space for the function-like macro argument ARG to store
2326 the tokens resulting from the macro-expansion of the tokens that
2327 make up ARG itself. That space is allocated in ARG->expanded and
2328 needs to be freed using free. */
2329 static void
2330 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2332 gcc_checking_assert (arg->expanded == NULL
2333 && arg->expanded_virt_locs == NULL);
2335 arg->expanded = XNEWVEC (const cpp_token *, capacity);
2336 if (CPP_OPTION (pfile, track_macro_expansion))
2337 arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2341 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2342 tokens. */
2343 static void
2344 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2345 size_t size, size_t *expanded_capacity)
2347 if (size <= *expanded_capacity)
2348 return;
2350 size *= 2;
2352 arg->expanded =
2353 XRESIZEVEC (const cpp_token *, arg->expanded, size);
2354 *expanded_capacity = size;
2356 if (CPP_OPTION (pfile, track_macro_expansion))
2358 if (arg->expanded_virt_locs == NULL)
2359 arg->expanded_virt_locs = XNEWVEC (source_location, size);
2360 else
2361 arg->expanded_virt_locs = XRESIZEVEC (source_location,
2362 arg->expanded_virt_locs,
2363 size);
2367 /* Expand an argument ARG before replacing parameters in a
2368 function-like macro. This works by pushing a context with the
2369 argument's tokens, and then expanding that into a temporary buffer
2370 as if it were a normal part of the token stream. collect_args()
2371 has terminated the argument's tokens with a CPP_EOF so that we know
2372 when we have fully expanded the argument. */
2373 static void
2374 expand_arg (cpp_reader *pfile, macro_arg *arg)
2376 size_t capacity;
2377 bool saved_warn_trad;
2378 bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2380 if (arg->count == 0
2381 || arg->expanded != NULL)
2382 return;
2384 /* Don't warn about funlike macros when pre-expanding. */
2385 saved_warn_trad = CPP_WTRADITIONAL (pfile);
2386 CPP_WTRADITIONAL (pfile) = 0;
2388 /* Loop, reading in the tokens of the argument. */
2389 capacity = 256;
2390 alloc_expanded_arg_mem (pfile, arg, capacity);
2392 if (track_macro_exp_p)
2393 push_extended_tokens_context (pfile, NULL, NULL,
2394 arg->virt_locs,
2395 arg->first,
2396 arg->count + 1);
2397 else
2398 push_ptoken_context (pfile, NULL, NULL,
2399 arg->first, arg->count + 1);
2401 for (;;)
2403 const cpp_token *token;
2404 source_location location;
2406 ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2407 &capacity);
2409 token = cpp_get_token_1 (pfile, &location);
2411 if (token->type == CPP_EOF)
2412 break;
2414 set_arg_token (arg, token, location,
2415 arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2416 CPP_OPTION (pfile, track_macro_expansion));
2417 arg->expanded_count++;
2420 _cpp_pop_context (pfile);
2422 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2425 /* Returns the macro associated to the current context if we are in
2426 the context a macro expansion, NULL otherwise. */
2427 static cpp_hashnode*
2428 macro_of_context (cpp_context *context)
2430 if (context == NULL)
2431 return NULL;
2433 return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2434 ? context->c.mc->macro_node
2435 : context->c.macro;
2438 /* Return TRUE iff we are expanding a macro or are about to start
2439 expanding one. If we are effectively expanding a macro, the
2440 function macro_of_context returns a pointer to the macro being
2441 expanded. */
2442 static bool
2443 in_macro_expansion_p (cpp_reader *pfile)
2445 if (pfile == NULL)
2446 return false;
2448 return (pfile->about_to_expand_macro_p
2449 || macro_of_context (pfile->context));
2452 /* Pop the current context off the stack, re-enabling the macro if the
2453 context represented a macro's replacement list. Initially the
2454 context structure was not freed so that we can re-use it later, but
2455 now we do free it to reduce peak memory consumption. */
2456 void
2457 _cpp_pop_context (cpp_reader *pfile)
2459 cpp_context *context = pfile->context;
2461 /* We should not be popping the base context. */
2462 if (context == &pfile->base_context)
2463 abort ();
2465 if (context->c.macro)
2467 cpp_hashnode *macro;
2468 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2470 macro_context *mc = context->c.mc;
2471 macro = mc->macro_node;
2472 /* If context->buff is set, it means the life time of tokens
2473 is bound to the life time of this context; so we must
2474 free the tokens; that means we must free the virtual
2475 locations of these tokens too. */
2476 if (context->buff && mc->virt_locs)
2478 free (mc->virt_locs);
2479 mc->virt_locs = NULL;
2481 free (mc);
2482 context->c.mc = NULL;
2484 else
2485 macro = context->c.macro;
2487 /* Beware that MACRO can be NULL in cases like when we are
2488 called from expand_arg. In those cases, a dummy context with
2489 tokens is pushed just for the purpose of walking them using
2490 cpp_get_token_1. In that case, no 'macro' field is set into
2491 the dummy context. */
2492 if (macro != NULL
2493 /* Several contiguous macro expansion contexts can be
2494 associated to the same macro; that means it's the same
2495 macro expansion that spans across all these (sub)
2496 contexts. So we should re-enable an expansion-disabled
2497 macro only when we are sure we are really out of that
2498 macro expansion. */
2499 && macro_of_context (context->prev) != macro)
2500 macro->flags &= ~NODE_DISABLED;
2502 if (macro == pfile->top_most_macro_node && context->prev == NULL)
2503 /* We are popping the context of the top-most macro node. */
2504 pfile->top_most_macro_node = NULL;
2507 if (context->buff)
2509 /* Decrease memory peak consumption by freeing the memory used
2510 by the context. */
2511 _cpp_free_buff (context->buff);
2514 pfile->context = context->prev;
2515 /* decrease peak memory consumption by feeing the context. */
2516 pfile->context->next = NULL;
2517 free (context);
2520 /* Return TRUE if we reached the end of the set of tokens stored in
2521 CONTEXT, FALSE otherwise. */
2522 static inline bool
2523 reached_end_of_context (cpp_context *context)
2525 if (context->tokens_kind == TOKENS_KIND_DIRECT)
2526 return FIRST (context).token == LAST (context).token;
2527 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2528 || context->tokens_kind == TOKENS_KIND_EXTENDED)
2529 return FIRST (context).ptoken == LAST (context).ptoken;
2530 else
2531 abort ();
2534 /* Consume the next token contained in the current context of PFILE,
2535 and return it in *TOKEN. It's "full location" is returned in
2536 *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2537 means the location encoding the locus of the token across macro
2538 expansion; otherwise it's just is the "normal" location of the
2539 token which (*TOKEN)->src_loc. */
2540 static inline void
2541 consume_next_token_from_context (cpp_reader *pfile,
2542 const cpp_token ** token,
2543 source_location *location)
2545 cpp_context *c = pfile->context;
2547 if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2549 *token = FIRST (c).token;
2550 *location = (*token)->src_loc;
2551 FIRST (c).token++;
2553 else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2555 *token = *FIRST (c).ptoken;
2556 *location = (*token)->src_loc;
2557 FIRST (c).ptoken++;
2559 else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2561 macro_context *m = c->c.mc;
2562 *token = *FIRST (c).ptoken;
2563 if (m->virt_locs)
2565 *location = *m->cur_virt_loc;
2566 m->cur_virt_loc++;
2568 else
2569 *location = (*token)->src_loc;
2570 FIRST (c).ptoken++;
2572 else
2573 abort ();
2576 /* In the traditional mode of the preprocessor, if we are currently in
2577 a directive, the location of a token must be the location of the
2578 start of the directive line. This function returns the proper
2579 location if we are in the traditional mode, and just returns
2580 LOCATION otherwise. */
2582 static inline source_location
2583 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2585 if (CPP_OPTION (pfile, traditional))
2587 if (pfile->state.in_directive)
2588 return pfile->directive_line;
2590 return location;
2593 /* Routine to get a token as well as its location.
2595 Macro expansions and directives are transparently handled,
2596 including entering included files. Thus tokens are post-macro
2597 expansion, and after any intervening directives. External callers
2598 see CPP_EOF only at EOF. Internal callers also see it when meeting
2599 a directive inside a macro call, when at the end of a directive and
2600 state.in_directive is still 1, and at the end of argument
2601 pre-expansion.
2603 LOC is an out parameter; *LOC is set to the location "as expected
2604 by the user". Please read the comment of
2605 cpp_get_token_with_location to learn more about the meaning of this
2606 location. */
2607 static const cpp_token*
2608 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2610 const cpp_token *result;
2611 /* This token is a virtual token that either encodes a location
2612 related to macro expansion or a spelling location. */
2613 source_location virt_loc = 0;
2614 /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2615 to functions that push macro contexts. So let's save it so that
2616 we can restore it when we are about to leave this routine. */
2617 bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2619 for (;;)
2621 cpp_hashnode *node;
2622 cpp_context *context = pfile->context;
2624 /* Context->prev == 0 <=> base context. */
2625 if (!context->prev)
2627 result = _cpp_lex_token (pfile);
2628 virt_loc = result->src_loc;
2630 else if (!reached_end_of_context (context))
2632 consume_next_token_from_context (pfile, &result,
2633 &virt_loc);
2634 if (result->flags & PASTE_LEFT)
2636 paste_all_tokens (pfile, result);
2637 if (pfile->state.in_directive)
2638 continue;
2639 result = padding_token (pfile, result);
2640 goto out;
2643 else
2645 if (pfile->context->c.macro)
2646 ++num_expanded_macros_counter;
2647 _cpp_pop_context (pfile);
2648 if (pfile->state.in_directive)
2649 continue;
2650 result = &pfile->avoid_paste;
2651 goto out;
2654 if (pfile->state.in_directive && result->type == CPP_COMMENT)
2655 continue;
2657 if (result->type != CPP_NAME)
2658 break;
2660 node = result->val.node.node;
2662 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2663 break;
2665 if (!(node->flags & NODE_DISABLED))
2667 int ret = 0;
2668 /* If not in a macro context, and we're going to start an
2669 expansion, record the location and the top level macro
2670 about to be expanded. */
2671 if (!in_macro_expansion_p (pfile))
2673 pfile->invocation_location = result->src_loc;
2674 pfile->top_most_macro_node = node;
2676 if (pfile->state.prevent_expansion)
2677 break;
2679 /* Conditional macros require that a predicate be evaluated
2680 first. */
2681 if ((node->flags & NODE_CONDITIONAL) != 0)
2683 if (pfile->cb.macro_to_expand)
2685 bool whitespace_after;
2686 const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2688 whitespace_after = (peek_tok->type == CPP_PADDING
2689 || (peek_tok->flags & PREV_WHITE));
2690 node = pfile->cb.macro_to_expand (pfile, result);
2691 if (node)
2692 ret = enter_macro_context (pfile, node, result,
2693 virt_loc);
2694 else if (whitespace_after)
2696 /* If macro_to_expand hook returned NULL and it
2697 ate some tokens, see if we don't need to add
2698 a padding token in between this and the
2699 next token. */
2700 peek_tok = cpp_peek_token (pfile, 0);
2701 if (peek_tok->type != CPP_PADDING
2702 && (peek_tok->flags & PREV_WHITE) == 0)
2703 _cpp_push_token_context (pfile, NULL,
2704 padding_token (pfile,
2705 peek_tok), 1);
2709 else
2710 ret = enter_macro_context (pfile, node, result,
2711 virt_loc);
2712 if (ret)
2714 if (pfile->state.in_directive || ret == 2)
2715 continue;
2716 result = padding_token (pfile, result);
2717 goto out;
2720 else
2722 /* Flag this token as always unexpandable. FIXME: move this
2723 to collect_args()?. */
2724 cpp_token *t = _cpp_temp_token (pfile);
2725 t->type = result->type;
2726 t->flags = result->flags | NO_EXPAND;
2727 t->val = result->val;
2728 result = t;
2731 break;
2734 out:
2735 if (location != NULL)
2737 if (virt_loc == 0)
2738 virt_loc = result->src_loc;
2739 *location = virt_loc;
2741 if (!CPP_OPTION (pfile, track_macro_expansion)
2742 && macro_of_context (pfile->context) != NULL)
2743 /* We are in a macro expansion context, are not tracking
2744 virtual location, but were asked to report the location
2745 of the expansion point of the macro being expanded. */
2746 *location = pfile->invocation_location;
2748 *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2751 pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
2752 return result;
2755 /* External routine to get a token. Also used nearly everywhere
2756 internally, except for places where we know we can safely call
2757 _cpp_lex_token directly, such as lexing a directive name.
2759 Macro expansions and directives are transparently handled,
2760 including entering included files. Thus tokens are post-macro
2761 expansion, and after any intervening directives. External callers
2762 see CPP_EOF only at EOF. Internal callers also see it when meeting
2763 a directive inside a macro call, when at the end of a directive and
2764 state.in_directive is still 1, and at the end of argument
2765 pre-expansion. */
2766 const cpp_token *
2767 cpp_get_token (cpp_reader *pfile)
2769 return cpp_get_token_1 (pfile, NULL);
2772 /* Like cpp_get_token, but also returns a virtual token location
2773 separate from the spelling location carried by the returned token.
2775 LOC is an out parameter; *LOC is set to the location "as expected
2776 by the user". This matters when a token results from macro
2777 expansion; in that case the token's spelling location indicates the
2778 locus of the token in the definition of the macro but *LOC
2779 virtually encodes all the other meaningful locuses associated to
2780 the token.
2782 What? virtual location? Yes, virtual location.
2784 If the token results from macro expansion and if macro expansion
2785 location tracking is enabled its virtual location encodes (at the
2786 same time):
2788 - the spelling location of the token
2790 - the locus of the macro expansion point
2792 - the locus of the point where the token got instantiated as part
2793 of the macro expansion process.
2795 You have to use the linemap API to get the locus you are interested
2796 in from a given virtual location.
2798 Note however that virtual locations are not necessarily ordered for
2799 relations '<' and '>'. One must use the function
2800 linemap_location_before_p instead of using the relational operator
2801 '<'.
2803 If macro expansion tracking is off and if the token results from
2804 macro expansion the virtual location is the expansion point of the
2805 macro that got expanded.
2807 When the token doesn't result from macro expansion, the virtual
2808 location is just the same thing as its spelling location. */
2810 const cpp_token *
2811 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2813 return cpp_get_token_1 (pfile, loc);
2816 /* Returns true if we're expanding an object-like macro that was
2817 defined in a system header. Just checks the macro at the top of
2818 the stack. Used for diagnostic suppression. */
2820 cpp_sys_macro_p (cpp_reader *pfile)
2822 cpp_hashnode *node = NULL;
2824 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2825 node = pfile->context->c.mc->macro_node;
2826 else
2827 node = pfile->context->c.macro;
2829 return node && node->value.macro && node->value.macro->syshdr;
2832 /* Read each token in, until end of the current file. Directives are
2833 transparently processed. */
2834 void
2835 cpp_scan_nooutput (cpp_reader *pfile)
2837 /* Request a CPP_EOF token at the end of this file, rather than
2838 transparently continuing with the including file. */
2839 pfile->buffer->return_at_eof = true;
2841 pfile->state.discarding_output++;
2842 pfile->state.prevent_expansion++;
2844 if (CPP_OPTION (pfile, traditional))
2845 while (_cpp_read_logical_line_trad (pfile))
2847 else
2848 while (cpp_get_token (pfile)->type != CPP_EOF)
2851 pfile->state.discarding_output--;
2852 pfile->state.prevent_expansion--;
2855 /* Step back one or more tokens obtained from the lexer. */
2856 void
2857 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2859 pfile->lookaheads += count;
2860 while (count--)
2862 pfile->cur_token--;
2863 if (pfile->cur_token == pfile->cur_run->base
2864 /* Possible with -fpreprocessed and no leading #line. */
2865 && pfile->cur_run->prev != NULL)
2867 pfile->cur_run = pfile->cur_run->prev;
2868 pfile->cur_token = pfile->cur_run->limit;
2873 /* Step back one (or more) tokens. Can only step back more than 1 if
2874 they are from the lexer, and not from macro expansion. */
2875 void
2876 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2878 if (pfile->context->prev == NULL)
2879 _cpp_backup_tokens_direct (pfile, count);
2880 else
2882 if (count != 1)
2883 abort ();
2884 if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2885 FIRST (pfile->context).token--;
2886 else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2887 FIRST (pfile->context).ptoken--;
2888 else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2890 FIRST (pfile->context).ptoken--;
2891 if (pfile->context->c.macro)
2893 macro_context *m = pfile->context->c.mc;
2894 m->cur_virt_loc--;
2895 gcc_checking_assert (m->cur_virt_loc >= m->virt_locs);
2897 else
2898 abort ();
2900 else
2901 abort ();
2905 /* #define directive parsing and handling. */
2907 /* Returns nonzero if a macro redefinition warning is required. */
2908 static bool
2909 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2910 const cpp_macro *macro2)
2912 const cpp_macro *macro1;
2913 unsigned int i;
2915 /* Some redefinitions need to be warned about regardless. */
2916 if (node->flags & NODE_WARN)
2917 return true;
2919 /* Suppress warnings for builtins that lack the NODE_WARN flag,
2920 unless Wbuiltin-macro-redefined. */
2921 if (node->flags & NODE_BUILTIN
2922 && (!pfile->cb.user_builtin_macro
2923 || !pfile->cb.user_builtin_macro (pfile, node)))
2924 return CPP_OPTION (pfile, warn_builtin_macro_redefined);
2926 /* Redefinitions of conditional (context-sensitive) macros, on
2927 the other hand, must be allowed silently. */
2928 if (node->flags & NODE_CONDITIONAL)
2929 return false;
2931 /* Redefinition of a macro is allowed if and only if the old and new
2932 definitions are the same. (6.10.3 paragraph 2). */
2933 macro1 = node->value.macro;
2935 /* Don't check count here as it can be different in valid
2936 traditional redefinitions with just whitespace differences. */
2937 if (macro1->paramc != macro2->paramc
2938 || macro1->fun_like != macro2->fun_like
2939 || macro1->variadic != macro2->variadic)
2940 return true;
2942 /* Check parameter spellings. */
2943 for (i = 0; i < macro1->paramc; i++)
2944 if (macro1->params[i] != macro2->params[i])
2945 return true;
2947 /* Check the replacement text or tokens. */
2948 if (CPP_OPTION (pfile, traditional))
2949 return _cpp_expansions_different_trad (macro1, macro2);
2951 if (macro1->count != macro2->count)
2952 return true;
2954 for (i = 0; i < macro1->count; i++)
2955 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2956 return true;
2958 return false;
2961 /* Free the definition of hashnode H. */
2962 void
2963 _cpp_free_definition (cpp_hashnode *h)
2965 /* Macros and assertions no longer have anything to free. */
2966 h->type = NT_VOID;
2967 /* Clear builtin flag in case of redefinition. */
2968 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2971 /* Save parameter NODE (spelling SPELLING) to the parameter list of
2972 macro MACRO. Returns zero on success, nonzero if the parameter is
2973 a duplicate. */
2974 bool
2975 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node,
2976 cpp_hashnode *spelling)
2978 unsigned int len;
2979 /* Constraint 6.10.3.6 - duplicate parameter names. */
2980 if (node->flags & NODE_MACRO_ARG)
2982 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2983 NODE_NAME (node));
2984 return true;
2987 if (BUFF_ROOM (pfile->a_buff)
2988 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2989 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2991 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = spelling;
2992 node->flags |= NODE_MACRO_ARG;
2993 len = macro->paramc * sizeof (struct macro_arg_saved_data);
2994 if (len > pfile->macro_buffer_len)
2996 pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2997 len);
2998 pfile->macro_buffer_len = len;
3000 struct macro_arg_saved_data save;
3001 save.value = node->value;
3002 save.canonical_node = node;
3003 ((struct macro_arg_saved_data *) pfile->macro_buffer)[macro->paramc - 1]
3004 = save;
3006 node->value.arg_index = macro->paramc;
3007 return false;
3010 /* Check the syntax of the parameters in a MACRO definition. Returns
3011 false if an error occurs. */
3012 static bool
3013 parse_params (cpp_reader *pfile, cpp_macro *macro)
3015 unsigned int prev_ident = 0;
3017 for (;;)
3019 const cpp_token *token = _cpp_lex_token (pfile);
3021 switch (token->type)
3023 default:
3024 /* Allow/ignore comments in parameter lists if we are
3025 preserving comments in macro expansions. */
3026 if (token->type == CPP_COMMENT
3027 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
3028 continue;
3030 cpp_error (pfile, CPP_DL_ERROR,
3031 "\"%s\" may not appear in macro parameter list",
3032 cpp_token_as_text (pfile, token));
3033 return false;
3035 case CPP_NAME:
3036 if (prev_ident)
3038 cpp_error (pfile, CPP_DL_ERROR,
3039 "macro parameters must be comma-separated");
3040 return false;
3042 prev_ident = 1;
3044 if (_cpp_save_parameter (pfile, macro, token->val.node.node,
3045 token->val.node.spelling))
3046 return false;
3047 continue;
3049 case CPP_CLOSE_PAREN:
3050 if (prev_ident || macro->paramc == 0)
3051 return true;
3053 /* Fall through to pick up the error. */
3054 /* FALLTHRU */
3055 case CPP_COMMA:
3056 if (!prev_ident)
3058 cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
3059 return false;
3061 prev_ident = 0;
3062 continue;
3064 case CPP_ELLIPSIS:
3065 macro->variadic = 1;
3066 if (!prev_ident)
3068 _cpp_save_parameter (pfile, macro,
3069 pfile->spec_nodes.n__VA_ARGS__,
3070 pfile->spec_nodes.n__VA_ARGS__);
3071 pfile->state.va_args_ok = 1;
3072 if (! CPP_OPTION (pfile, c99)
3073 && CPP_OPTION (pfile, cpp_pedantic)
3074 && CPP_OPTION (pfile, warn_variadic_macros))
3076 if (CPP_OPTION (pfile, cplusplus))
3077 cpp_pedwarning
3078 (pfile, CPP_W_VARIADIC_MACROS,
3079 "anonymous variadic macros were introduced in C++11");
3080 else
3081 cpp_pedwarning
3082 (pfile, CPP_W_VARIADIC_MACROS,
3083 "anonymous variadic macros were introduced in C99");
3085 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
3086 && ! CPP_OPTION (pfile, cplusplus))
3087 cpp_error (pfile, CPP_DL_WARNING,
3088 "anonymous variadic macros were introduced in C99");
3090 else if (CPP_OPTION (pfile, cpp_pedantic)
3091 && CPP_OPTION (pfile, warn_variadic_macros))
3093 if (CPP_OPTION (pfile, cplusplus))
3094 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
3095 "ISO C++ does not permit named variadic macros");
3096 else
3097 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
3098 "ISO C does not permit named variadic macros");
3101 /* We're at the end, and just expect a closing parenthesis. */
3102 token = _cpp_lex_token (pfile);
3103 if (token->type == CPP_CLOSE_PAREN)
3104 return true;
3105 /* Fall through. */
3107 case CPP_EOF:
3108 cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
3109 return false;
3114 /* Allocate room for a token from a macro's replacement list. */
3115 static cpp_token *
3116 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
3118 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
3119 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
3121 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
3124 /* Lex a token from the expansion of MACRO, but mark parameters as we
3125 find them and warn of traditional stringification. */
3126 static cpp_token *
3127 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
3129 cpp_token *token, *saved_cur_token;
3131 saved_cur_token = pfile->cur_token;
3132 pfile->cur_token = alloc_expansion_token (pfile, macro);
3133 token = _cpp_lex_direct (pfile);
3134 pfile->cur_token = saved_cur_token;
3136 /* Is this a parameter? */
3137 if (token->type == CPP_NAME
3138 && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
3140 cpp_hashnode *spelling = token->val.node.spelling;
3141 token->type = CPP_MACRO_ARG;
3142 token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
3143 token->val.macro_arg.spelling = spelling;
3145 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
3146 && (token->type == CPP_STRING || token->type == CPP_CHAR))
3147 check_trad_stringification (pfile, macro, &token->val.str);
3149 return token;
3152 static bool
3153 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
3155 cpp_token *token;
3156 const cpp_token *ctoken;
3157 bool following_paste_op = false;
3158 const char *paste_op_error_msg =
3159 N_("'##' cannot appear at either end of a macro expansion");
3160 unsigned int num_extra_tokens = 0;
3162 /* Get the first token of the expansion (or the '(' of a
3163 function-like macro). */
3164 ctoken = _cpp_lex_token (pfile);
3166 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
3168 bool ok = parse_params (pfile, macro);
3169 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
3170 if (!ok)
3171 return false;
3173 /* Success. Commit or allocate the parameter array. */
3174 if (pfile->hash_table->alloc_subobject)
3176 cpp_hashnode **params =
3177 (cpp_hashnode **) pfile->hash_table->alloc_subobject
3178 (sizeof (cpp_hashnode *) * macro->paramc);
3179 memcpy (params, macro->params,
3180 sizeof (cpp_hashnode *) * macro->paramc);
3181 macro->params = params;
3183 else
3184 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
3185 macro->fun_like = 1;
3187 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
3189 /* While ISO C99 requires whitespace before replacement text
3190 in a macro definition, ISO C90 with TC1 allows characters
3191 from the basic source character set there. */
3192 if (CPP_OPTION (pfile, c99))
3194 if (CPP_OPTION (pfile, cplusplus))
3195 cpp_error (pfile, CPP_DL_PEDWARN,
3196 "ISO C++11 requires whitespace after the macro name");
3197 else
3198 cpp_error (pfile, CPP_DL_PEDWARN,
3199 "ISO C99 requires whitespace after the macro name");
3201 else
3203 int warntype = CPP_DL_WARNING;
3204 switch (ctoken->type)
3206 case CPP_ATSIGN:
3207 case CPP_AT_NAME:
3208 case CPP_OBJC_STRING:
3209 /* '@' is not in basic character set. */
3210 warntype = CPP_DL_PEDWARN;
3211 break;
3212 case CPP_OTHER:
3213 /* Basic character set sans letters, digits and _. */
3214 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
3215 ctoken->val.str.text[0]) == NULL)
3216 warntype = CPP_DL_PEDWARN;
3217 break;
3218 default:
3219 /* All other tokens start with a character from basic
3220 character set. */
3221 break;
3223 cpp_error (pfile, warntype,
3224 "missing whitespace after the macro name");
3228 if (macro->fun_like)
3229 token = lex_expansion_token (pfile, macro);
3230 else
3232 token = alloc_expansion_token (pfile, macro);
3233 *token = *ctoken;
3236 /* The argument doesn't matter here. */
3237 vaopt_state vaopt_tracker (pfile, macro->variadic, true);
3239 for (;;)
3241 /* Check the stringifying # constraint 6.10.3.2.1 of
3242 function-like macros when lexing the subsequent token. */
3243 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
3245 if (token->type == CPP_MACRO_ARG)
3247 if (token->flags & PREV_WHITE)
3248 token->flags |= SP_PREV_WHITE;
3249 if (token[-1].flags & DIGRAPH)
3250 token->flags |= SP_DIGRAPH;
3251 token->flags &= ~PREV_WHITE;
3252 token->flags |= STRINGIFY_ARG;
3253 token->flags |= token[-1].flags & PREV_WHITE;
3254 token[-1] = token[0];
3255 macro->count--;
3257 /* Let assembler get away with murder. */
3258 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
3260 cpp_error (pfile, CPP_DL_ERROR,
3261 "'#' is not followed by a macro parameter");
3262 return false;
3266 if (token->type == CPP_EOF)
3268 /* Paste operator constraint 6.10.3.3.1:
3269 Token-paste ##, can appear in both object-like and
3270 function-like macros, but not at the end. */
3271 if (following_paste_op)
3273 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3274 return false;
3276 break;
3279 /* Paste operator constraint 6.10.3.3.1. */
3280 if (token->type == CPP_PASTE)
3282 /* Token-paste ##, can appear in both object-like and
3283 function-like macros, but not at the beginning. */
3284 if (macro->count == 1)
3286 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3287 return false;
3290 if (token[-1].flags & PASTE_LEFT)
3292 macro->extra_tokens = 1;
3293 num_extra_tokens++;
3294 token->val.token_no = macro->count - 1;
3296 else
3298 --macro->count;
3299 token[-1].flags |= PASTE_LEFT;
3300 if (token->flags & DIGRAPH)
3301 token[-1].flags |= SP_DIGRAPH;
3302 if (token->flags & PREV_WHITE)
3303 token[-1].flags |= SP_PREV_WHITE;
3307 if (vaopt_tracker.update (token) == vaopt_state::ERROR)
3308 return false;
3310 following_paste_op = (token->type == CPP_PASTE);
3311 token = lex_expansion_token (pfile, macro);
3314 if (!vaopt_tracker.completed ())
3315 return false;
3317 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
3318 macro->traditional = 0;
3320 /* Don't count the CPP_EOF. */
3321 macro->count--;
3323 /* Clear whitespace on first token for warn_of_redefinition(). */
3324 if (macro->count)
3325 macro->exp.tokens[0].flags &= ~PREV_WHITE;
3327 /* Commit or allocate the memory. */
3328 if (pfile->hash_table->alloc_subobject)
3330 cpp_token *tokns =
3331 (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
3332 * macro->count);
3333 if (num_extra_tokens)
3335 /* Place second and subsequent ## or %:%: tokens in
3336 sequences of consecutive such tokens at the end of the
3337 list to preserve information about where they appear, how
3338 they are spelt and whether they are preceded by
3339 whitespace without otherwise interfering with macro
3340 expansion. */
3341 cpp_token *normal_dest = tokns;
3342 cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
3343 unsigned int i;
3344 for (i = 0; i < macro->count; i++)
3346 if (macro->exp.tokens[i].type == CPP_PASTE)
3347 *extra_dest++ = macro->exp.tokens[i];
3348 else
3349 *normal_dest++ = macro->exp.tokens[i];
3352 else
3353 memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
3354 macro->exp.tokens = tokns;
3356 else
3357 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
3359 return true;
3362 /* Parse a macro and save its expansion. Returns nonzero on success. */
3363 bool
3364 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3366 cpp_macro *macro;
3367 unsigned int i;
3368 bool ok;
3370 if (pfile->hash_table->alloc_subobject)
3371 macro = (cpp_macro *) pfile->hash_table->alloc_subobject
3372 (sizeof (cpp_macro));
3373 else
3374 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
3375 macro->line = pfile->directive_line;
3376 macro->params = 0;
3377 macro->paramc = 0;
3378 macro->variadic = 0;
3379 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3380 macro->count = 0;
3381 macro->fun_like = 0;
3382 macro->extra_tokens = 0;
3383 /* To suppress some diagnostics. */
3384 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3386 if (CPP_OPTION (pfile, traditional))
3387 ok = _cpp_create_trad_definition (pfile, macro);
3388 else
3390 ok = create_iso_definition (pfile, macro);
3392 /* We set the type for SEEN_EOL() in directives.c.
3394 Longer term we should lex the whole line before coming here,
3395 and just copy the expansion. */
3397 /* Stop the lexer accepting __VA_ARGS__. */
3398 pfile->state.va_args_ok = 0;
3401 /* Clear the fast argument lookup indices. */
3402 for (i = macro->paramc; i-- > 0; )
3404 struct macro_arg_saved_data *save =
3405 &((struct macro_arg_saved_data *) pfile->macro_buffer)[i];
3406 struct cpp_hashnode *node = save->canonical_node;
3407 node->flags &= ~ NODE_MACRO_ARG;
3408 node->value = save->value;
3411 if (!ok)
3412 return ok;
3414 if (node->type == NT_MACRO)
3416 if (CPP_OPTION (pfile, warn_unused_macros))
3417 _cpp_warn_if_unused_macro (pfile, node, NULL);
3419 if (warn_of_redefinition (pfile, node, macro))
3421 const int reason = ((node->flags & NODE_BUILTIN)
3422 && !(node->flags & NODE_WARN))
3423 ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3425 bool warned =
3426 cpp_pedwarning_with_line (pfile, reason,
3427 pfile->directive_line, 0,
3428 "\"%s\" redefined", NODE_NAME (node));
3430 if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3431 cpp_error_with_line (pfile, CPP_DL_NOTE,
3432 node->value.macro->line, 0,
3433 "this is the location of the previous definition");
3437 if (node->type != NT_VOID)
3438 _cpp_free_definition (node);
3440 /* Enter definition in hash table. */
3441 node->type = NT_MACRO;
3442 node->value.macro = macro;
3443 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3444 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3445 /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3446 in the C standard, as something that one must use in C++.
3447 However DR#593 and C++11 indicate that they play no role in C++.
3448 We special-case them anyway. */
3449 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3450 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3451 node->flags |= NODE_WARN;
3453 /* If user defines one of the conditional macros, remove the
3454 conditional flag */
3455 node->flags &= ~NODE_CONDITIONAL;
3457 return ok;
3460 /* Warn if a token in STRING matches one of a function-like MACRO's
3461 parameters. */
3462 static void
3463 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3464 const cpp_string *string)
3466 unsigned int i, len;
3467 const uchar *p, *q, *limit;
3469 /* Loop over the string. */
3470 limit = string->text + string->len - 1;
3471 for (p = string->text + 1; p < limit; p = q)
3473 /* Find the start of an identifier. */
3474 while (p < limit && !is_idstart (*p))
3475 p++;
3477 /* Find the end of the identifier. */
3478 q = p;
3479 while (q < limit && is_idchar (*q))
3480 q++;
3482 len = q - p;
3484 /* Loop over the function macro arguments to see if the
3485 identifier inside the string matches one of them. */
3486 for (i = 0; i < macro->paramc; i++)
3488 const cpp_hashnode *node = macro->params[i];
3490 if (NODE_LEN (node) == len
3491 && !memcmp (p, NODE_NAME (node), len))
3493 cpp_warning (pfile, CPP_W_TRADITIONAL,
3494 "macro argument \"%s\" would be stringified in traditional C",
3495 NODE_NAME (node));
3496 break;
3502 /* Returns true of NODE is a function-like macro. */
3503 bool
3504 cpp_fun_like_macro_p (cpp_hashnode *node)
3506 return (node->type == NT_MACRO
3507 && (node->flags & (NODE_BUILTIN | NODE_MACRO_ARG)) == 0
3508 && node->value.macro->fun_like);
3511 /* Returns the name, arguments and expansion of a macro, in a format
3512 suitable to be read back in again, and therefore also for DWARF 2
3513 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3514 Caller is expected to generate the "#define" bit if needed. The
3515 returned text is temporary, and automatically freed later. */
3516 const unsigned char *
3517 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3519 unsigned int i, len;
3520 const cpp_macro *macro;
3521 unsigned char *buffer;
3523 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3525 if (node->type != NT_MACRO
3526 || !pfile->cb.user_builtin_macro
3527 || !pfile->cb.user_builtin_macro (pfile, node))
3529 cpp_error (pfile, CPP_DL_ICE,
3530 "invalid hash type %d in cpp_macro_definition",
3531 node->type);
3532 return 0;
3536 macro = node->value.macro;
3537 /* Calculate length. */
3538 len = NODE_LEN (node) * 10 + 2; /* ' ' and NUL. */
3539 if (macro->fun_like)
3541 len += 4; /* "()" plus possible final ".." of named
3542 varargs (we have + 1 below). */
3543 for (i = 0; i < macro->paramc; i++)
3544 len += NODE_LEN (macro->params[i]) + 1; /* "," */
3547 /* This should match below where we fill in the buffer. */
3548 if (CPP_OPTION (pfile, traditional))
3549 len += _cpp_replacement_text_len (macro);
3550 else
3552 unsigned int count = macro_real_token_count (macro);
3553 for (i = 0; i < count; i++)
3555 cpp_token *token = &macro->exp.tokens[i];
3557 if (token->type == CPP_MACRO_ARG)
3558 len += NODE_LEN (token->val.macro_arg.spelling);
3559 else
3560 len += cpp_token_len (token);
3562 if (token->flags & STRINGIFY_ARG)
3563 len++; /* "#" */
3564 if (token->flags & PASTE_LEFT)
3565 len += 3; /* " ##" */
3566 if (token->flags & PREV_WHITE)
3567 len++; /* " " */
3571 if (len > pfile->macro_buffer_len)
3573 pfile->macro_buffer = XRESIZEVEC (unsigned char,
3574 pfile->macro_buffer, len);
3575 pfile->macro_buffer_len = len;
3578 /* Fill in the buffer. Start with the macro name. */
3579 buffer = pfile->macro_buffer;
3580 buffer = _cpp_spell_ident_ucns (buffer, node);
3582 /* Parameter names. */
3583 if (macro->fun_like)
3585 *buffer++ = '(';
3586 for (i = 0; i < macro->paramc; i++)
3588 cpp_hashnode *param = macro->params[i];
3590 if (param != pfile->spec_nodes.n__VA_ARGS__)
3592 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3593 buffer += NODE_LEN (param);
3596 if (i + 1 < macro->paramc)
3597 /* Don't emit a space after the comma here; we're trying
3598 to emit a Dwarf-friendly definition, and the Dwarf spec
3599 forbids spaces in the argument list. */
3600 *buffer++ = ',';
3601 else if (macro->variadic)
3602 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3604 *buffer++ = ')';
3607 /* The Dwarf spec requires a space after the macro name, even if the
3608 definition is the empty string. */
3609 *buffer++ = ' ';
3611 if (CPP_OPTION (pfile, traditional))
3612 buffer = _cpp_copy_replacement_text (macro, buffer);
3613 else if (macro->count)
3614 /* Expansion tokens. */
3616 unsigned int count = macro_real_token_count (macro);
3617 for (i = 0; i < count; i++)
3619 cpp_token *token = &macro->exp.tokens[i];
3621 if (token->flags & PREV_WHITE)
3622 *buffer++ = ' ';
3623 if (token->flags & STRINGIFY_ARG)
3624 *buffer++ = '#';
3626 if (token->type == CPP_MACRO_ARG)
3628 memcpy (buffer,
3629 NODE_NAME (token->val.macro_arg.spelling),
3630 NODE_LEN (token->val.macro_arg.spelling));
3631 buffer += NODE_LEN (token->val.macro_arg.spelling);
3633 else
3634 buffer = cpp_spell_token (pfile, token, buffer, true);
3636 if (token->flags & PASTE_LEFT)
3638 *buffer++ = ' ';
3639 *buffer++ = '#';
3640 *buffer++ = '#';
3641 /* Next has PREV_WHITE; see _cpp_create_definition. */
3646 *buffer = '\0';
3647 return pfile->macro_buffer;
3650 /* Get the line at which the macro was defined. */
3652 source_location
3653 cpp_macro_definition_location (cpp_hashnode *node)
3655 return node->value.macro->line;