Change dg-options for hpux to define _HPUX_SOURCE in gcc.dg/pthread-init-2.c
[official-gcc.git] / libcpp / macro.cc
bloba3d2c159f8cb962d3e354087cdbfbbe2c3b34c7a
1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986-2024 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 location_t *virt_locs; /* Where virtual locations for
43 unexpanded tokens are stored. */
44 location_t *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 literal, 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 location_t *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 & type of this identifier. */
89 union _cpp_hashnode_value value;
90 node_type type;
93 static const char *vaopt_paste_error =
94 N_("'##' cannot appear at either end of __VA_OPT__");
96 static void expand_arg (cpp_reader *, macro_arg *);
98 /* A class for tracking __VA_OPT__ state while iterating over a
99 sequence of tokens. This is used during both macro definition and
100 expansion. */
101 class vaopt_state {
103 public:
105 enum update_type
107 ERROR,
108 DROP,
109 INCLUDE,
110 BEGIN,
114 /* Initialize the state tracker. ANY_ARGS is true if variable
115 arguments were provided to the macro invocation. */
116 vaopt_state (cpp_reader *pfile, bool is_variadic, macro_arg *arg)
117 : m_pfile (pfile),
118 m_arg (arg),
119 m_variadic (is_variadic),
120 m_last_was_paste (false),
121 m_stringify (false),
122 m_state (0),
123 m_paste_location (0),
124 m_location (0),
125 m_update (ERROR)
129 /* Given a token, update the state of this tracker and return a
130 boolean indicating whether the token should be be included in the
131 expansion. */
132 update_type update (const cpp_token *token)
134 /* If the macro isn't variadic, just don't bother. */
135 if (!m_variadic)
136 return INCLUDE;
138 if (token->type == CPP_NAME
139 && token->val.node.node == m_pfile->spec_nodes.n__VA_OPT__)
141 if (m_state > 0)
143 cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
144 "__VA_OPT__ may not appear in a __VA_OPT__");
145 return ERROR;
147 ++m_state;
148 m_location = token->src_loc;
149 m_stringify = (token->flags & STRINGIFY_ARG) != 0;
150 return BEGIN;
152 else if (m_state == 1)
154 if (token->type != CPP_OPEN_PAREN)
156 cpp_error_at (m_pfile, CPP_DL_ERROR, m_location,
157 "__VA_OPT__ must be followed by an "
158 "open parenthesis");
159 return ERROR;
161 ++m_state;
162 if (m_update == ERROR)
164 if (m_arg == NULL)
165 m_update = INCLUDE;
166 else
168 m_update = DROP;
169 if (!m_arg->expanded)
170 expand_arg (m_pfile, m_arg);
171 for (unsigned idx = 0; idx < m_arg->expanded_count; ++idx)
172 if (m_arg->expanded[idx]->type != CPP_PADDING)
174 m_update = INCLUDE;
175 break;
179 return DROP;
181 else if (m_state >= 2)
183 if (m_state == 2 && token->type == CPP_PASTE)
185 cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
186 vaopt_paste_error);
187 return ERROR;
189 /* Advance states before further considering this token, in
190 case we see a close paren immediately after the open
191 paren. */
192 if (m_state == 2)
193 ++m_state;
195 bool was_paste = m_last_was_paste;
196 m_last_was_paste = false;
197 if (token->type == CPP_PASTE)
199 m_last_was_paste = true;
200 m_paste_location = token->src_loc;
202 else if (token->type == CPP_OPEN_PAREN)
203 ++m_state;
204 else if (token->type == CPP_CLOSE_PAREN)
206 --m_state;
207 if (m_state == 2)
209 /* Saw the final paren. */
210 m_state = 0;
212 if (was_paste)
214 cpp_error_at (m_pfile, CPP_DL_ERROR, token->src_loc,
215 vaopt_paste_error);
216 return ERROR;
219 return END;
222 return m_update;
225 /* Nothing to do with __VA_OPT__. */
226 return INCLUDE;
229 /* Ensure that any __VA_OPT__ was completed. If ok, return true.
230 Otherwise, issue an error and return false. */
231 bool completed ()
233 if (m_variadic && m_state != 0)
234 cpp_error_at (m_pfile, CPP_DL_ERROR, m_location,
235 "unterminated __VA_OPT__");
236 return m_state == 0;
239 /* Return true for # __VA_OPT__. */
240 bool stringify () const
242 return m_stringify;
245 private:
247 /* The cpp_reader. */
248 cpp_reader *m_pfile;
250 /* The __VA_ARGS__ argument. */
251 macro_arg *m_arg;
253 /* True if the macro is variadic. */
254 bool m_variadic;
255 /* If true, the previous token was ##. This is used to detect when
256 a paste occurs at the end of the sequence. */
257 bool m_last_was_paste;
258 /* True for #__VA_OPT__. */
259 bool m_stringify;
261 /* The state variable:
262 0 means not parsing
263 1 means __VA_OPT__ seen, looking for "("
264 2 means "(" seen (so the next token can't be "##")
265 >= 3 means looking for ")", the number encodes the paren depth. */
266 int m_state;
268 /* The location of the paste token. */
269 location_t m_paste_location;
271 /* Location of the __VA_OPT__ token. */
272 location_t m_location;
274 /* If __VA_ARGS__ substitutes to no preprocessing tokens,
275 INCLUDE, otherwise DROP. ERROR when unknown yet. */
276 update_type m_update;
279 /* Macro expansion. */
281 static cpp_macro *get_deferred_or_lazy_macro (cpp_reader *, cpp_hashnode *,
282 location_t);
283 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
284 const cpp_token *, location_t);
285 static int builtin_macro (cpp_reader *, cpp_hashnode *,
286 location_t, location_t);
287 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
288 const cpp_token **, unsigned int);
289 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
290 _cpp_buff *, location_t *,
291 const cpp_token **, unsigned int);
292 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
293 _cpp_buff **, unsigned *);
294 static cpp_context *next_context (cpp_reader *);
295 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
296 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
297 static const cpp_token *stringify_arg (cpp_reader *, const cpp_token **,
298 unsigned int);
299 static void paste_all_tokens (cpp_reader *, const cpp_token *);
300 static bool paste_tokens (cpp_reader *, location_t,
301 const cpp_token **, const cpp_token *);
302 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
303 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
304 static void delete_macro_args (_cpp_buff*, unsigned num_args);
305 static void set_arg_token (macro_arg *, const cpp_token *,
306 location_t, size_t,
307 enum macro_arg_token_kind,
308 bool);
309 static const location_t *get_arg_token_location (const macro_arg *,
310 enum macro_arg_token_kind);
311 static const cpp_token **arg_token_ptr_at (const macro_arg *,
312 size_t,
313 enum macro_arg_token_kind,
314 location_t **virt_location);
316 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
317 enum macro_arg_token_kind,
318 const macro_arg *,
319 const cpp_token **);
320 static const cpp_token *macro_arg_token_iter_get_token
321 (const macro_arg_token_iter *it);
322 static location_t macro_arg_token_iter_get_location
323 (const macro_arg_token_iter *);
324 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
325 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
326 location_t **);
327 static size_t tokens_buff_count (_cpp_buff *);
328 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
329 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
330 location_t *,
331 const cpp_token *,
332 location_t,
333 location_t,
334 const line_map_macro *,
335 unsigned int);
337 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
338 location_t *,
339 const cpp_token *,
340 location_t,
341 location_t,
342 const line_map_macro *,
343 unsigned int);
344 static inline void tokens_buff_remove_last_token (_cpp_buff *);
345 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
346 macro_arg *, location_t);
347 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
348 _cpp_buff **, unsigned *);
349 static cpp_macro *create_iso_definition (cpp_reader *);
351 /* #define directive parsing and handling. */
353 static cpp_macro *lex_expansion_token (cpp_reader *, cpp_macro *);
354 static bool parse_params (cpp_reader *, unsigned *, bool *);
355 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
356 const cpp_string *);
357 static bool reached_end_of_context (cpp_context *);
358 static void consume_next_token_from_context (cpp_reader *pfile,
359 const cpp_token **,
360 location_t *);
361 static const cpp_token* cpp_get_token_1 (cpp_reader *, location_t *);
363 static cpp_hashnode* macro_of_context (cpp_context *context);
365 /* Statistical counter tracking the number of macros that got
366 expanded. */
367 unsigned num_expanded_macros_counter = 0;
368 /* Statistical counter tracking the total number tokens resulting
369 from macro expansion. */
370 unsigned num_macro_tokens_counter = 0;
372 /* Wrapper around cpp_get_token to skip CPP_PADDING tokens
373 and not consume CPP_EOF. */
374 static const cpp_token *
375 cpp_get_token_no_padding (cpp_reader *pfile)
377 for (;;)
379 const cpp_token *ret = cpp_peek_token (pfile, 0);
380 if (ret->type == CPP_EOF)
381 return ret;
382 ret = cpp_get_token (pfile);
383 if (ret->type != CPP_PADDING)
384 return ret;
388 /* Handle meeting "__has_include" builtin macro. */
390 static int
391 builtin_has_include (cpp_reader *pfile, cpp_hashnode *op, bool has_next)
393 int result = 0;
395 if (!pfile->state.in_directive)
396 cpp_error (pfile, CPP_DL_ERROR,
397 "\"%s\" used outside of preprocessing directive",
398 NODE_NAME (op));
400 pfile->state.angled_headers = true;
401 const cpp_token *token = cpp_get_token_no_padding (pfile);
402 bool paren = token->type == CPP_OPEN_PAREN;
403 if (paren)
404 token = cpp_get_token_no_padding (pfile);
405 else
406 cpp_error (pfile, CPP_DL_ERROR,
407 "missing '(' before \"%s\" operand", NODE_NAME (op));
408 pfile->state.angled_headers = false;
410 bool bracket = token->type != CPP_STRING;
411 char *fname = NULL;
412 if (token->type == CPP_STRING || token->type == CPP_HEADER_NAME)
414 fname = XNEWVEC (char, token->val.str.len - 1);
415 memcpy (fname, token->val.str.text + 1, token->val.str.len - 2);
416 fname[token->val.str.len - 2] = '\0';
418 else if (token->type == CPP_LESS)
419 fname = _cpp_bracket_include (pfile);
420 else
421 cpp_error (pfile, CPP_DL_ERROR,
422 "operator \"%s\" requires a header-name", NODE_NAME (op));
424 if (fname)
426 /* Do not do the lookup if we're skipping, that's unnecessary
427 IO. */
428 if (!pfile->state.skip_eval
429 && _cpp_has_header (pfile, fname, bracket,
430 has_next ? IT_INCLUDE_NEXT : IT_INCLUDE))
431 result = 1;
433 XDELETEVEC (fname);
436 if (paren
437 && cpp_get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
438 cpp_error (pfile, CPP_DL_ERROR,
439 "missing ')' after \"%s\" operand", NODE_NAME (op));
441 return result;
444 /* Emits a warning if NODE is a macro defined in the main file that
445 has not been used. */
447 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
448 void *v ATTRIBUTE_UNUSED)
450 if (cpp_user_macro_p (node))
452 cpp_macro *macro = node->value.macro;
454 if (!macro->used
455 && MAIN_FILE_P (linemap_check_ordinary
456 (linemap_lookup (pfile->line_table,
457 macro->line))))
458 cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
459 "macro \"%s\" is not used", NODE_NAME (node));
462 return 1;
465 /* Allocates and returns a CPP_STRING token, containing TEXT of length
466 LEN, after null-terminating it. TEXT must be in permanent storage. */
467 static const cpp_token *
468 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
470 cpp_token *token = _cpp_temp_token (pfile);
472 text[len] = '\0';
473 token->type = CPP_STRING;
474 token->val.str.len = len;
475 token->val.str.text = text;
476 token->flags = 0;
477 return token;
480 static const char * const monthnames[] =
482 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
483 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
486 /* Helper function for builtin_macro. Returns the text generated by
487 a builtin macro. */
488 const uchar *
489 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node,
490 location_t loc)
492 const uchar *result = NULL;
493 linenum_type number = 1;
495 switch (node->value.builtin)
497 default:
498 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
499 NODE_NAME (node));
500 break;
502 case BT_TIMESTAMP:
504 if (CPP_OPTION (pfile, warn_date_time))
505 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
506 "reproducible builds", NODE_NAME (node));
508 cpp_buffer *pbuffer = cpp_get_buffer (pfile);
509 if (pbuffer->timestamp == NULL)
511 /* Initialize timestamp value of the assotiated file. */
512 struct _cpp_file *file = cpp_get_file (pbuffer);
513 if (file)
515 /* Generate __TIMESTAMP__ string, that represents
516 the date and time of the last modification
517 of the current source file. The string constant
518 looks like "Sun Sep 16 01:03:52 1973". */
519 struct tm *tb = NULL;
520 struct stat *st = _cpp_get_file_stat (file);
521 if (st)
522 tb = localtime (&st->st_mtime);
523 if (tb)
525 char *str = asctime (tb);
526 size_t len = strlen (str);
527 unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
528 buf[0] = '"';
529 strcpy ((char *) buf + 1, str);
530 buf[len] = '"';
531 pbuffer->timestamp = buf;
533 else
535 cpp_errno (pfile, CPP_DL_WARNING,
536 "could not determine file timestamp");
537 pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
541 result = pbuffer->timestamp;
543 break;
544 case BT_FILE:
545 case BT_FILE_NAME:
546 case BT_BASE_FILE:
548 unsigned int len;
549 const char *name;
550 uchar *buf;
552 if (node->value.builtin == BT_FILE
553 || node->value.builtin == BT_FILE_NAME)
555 name = linemap_get_expansion_filename (pfile->line_table,
556 pfile->line_table->highest_line);
557 if ((node->value.builtin == BT_FILE_NAME) && name)
558 name = lbasename (name);
560 else
562 name = _cpp_get_file_name (pfile->main_file);
563 if (!name)
564 abort ();
566 if (pfile->cb.remap_filename && !pfile->state.in_directive)
567 name = pfile->cb.remap_filename (name);
568 len = strlen (name);
569 buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
570 result = buf;
571 *buf = '"';
572 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
573 *buf++ = '"';
574 *buf = '\0';
576 break;
578 case BT_INCLUDE_LEVEL:
579 /* The line map depth counts the primary source as level 1, but
580 historically __INCLUDE_DEPTH__ has called the primary source
581 level 0. */
582 number = pfile->line_table->depth - 1;
583 break;
585 case BT_SPECLINE:
586 /* If __LINE__ is embedded in a macro, it must expand to the
587 line of the macro's invocation, not its definition.
588 Otherwise things like assert() will not work properly.
589 See WG14 N1911, WG21 N4220 sec 6.5, and PR 61861. */
590 if (CPP_OPTION (pfile, traditional))
591 loc = pfile->line_table->highest_line;
592 else
593 loc = linemap_resolve_location (pfile->line_table, loc,
594 LRK_MACRO_EXPANSION_POINT, NULL);
595 number = linemap_get_expansion_line (pfile->line_table, loc);
596 break;
598 /* __STDC__ has the value 1 under normal circumstances.
599 However, if (a) we are in a system header, (b) the option
600 stdc_0_in_system_headers is true (set by target config), and
601 (c) we are not in strictly conforming mode, then it has the
602 value 0. (b) and (c) are already checked in cpp_init_builtins. */
603 case BT_STDC:
604 if (_cpp_in_system_header (pfile))
605 number = 0;
606 else
607 number = 1;
608 break;
610 case BT_DATE:
611 case BT_TIME:
612 if (CPP_OPTION (pfile, warn_date_time))
613 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
614 "reproducible builds", NODE_NAME (node));
615 if (pfile->date == NULL)
617 /* Allocate __DATE__ and __TIME__ strings from permanent
618 storage. We only do this once, and don't generate them
619 at init time, because time() and localtime() are very
620 slow on some systems. */
621 time_t tt;
622 auto kind = cpp_get_date (pfile, &tt);
624 if (kind == CPP_time_kind::UNKNOWN)
626 cpp_errno (pfile, CPP_DL_WARNING,
627 "could not determine date and time");
629 pfile->date = UC"\"??? ?? ????\"";
630 pfile->time = UC"\"??:??:??\"";
632 else
634 struct tm *tb = (kind == CPP_time_kind::FIXED
635 ? gmtime : localtime) (&tt);
637 pfile->date = _cpp_unaligned_alloc (pfile,
638 sizeof ("\"Oct 11 1347\""));
639 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
640 monthnames[tb->tm_mon], tb->tm_mday,
641 tb->tm_year + 1900);
643 pfile->time = _cpp_unaligned_alloc (pfile,
644 sizeof ("\"12:34:56\""));
645 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
646 tb->tm_hour, tb->tm_min, tb->tm_sec);
650 if (node->value.builtin == BT_DATE)
651 result = pfile->date;
652 else
653 result = pfile->time;
654 break;
656 case BT_COUNTER:
657 if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
658 cpp_error (pfile, CPP_DL_ERROR,
659 "__COUNTER__ expanded inside directive with -fdirectives-only");
660 number = pfile->counter++;
661 break;
663 case BT_HAS_ATTRIBUTE:
664 number = pfile->cb.has_attribute (pfile, false);
665 break;
667 case BT_HAS_STD_ATTRIBUTE:
668 number = pfile->cb.has_attribute (pfile, true);
669 break;
671 case BT_HAS_BUILTIN:
672 number = pfile->cb.has_builtin (pfile);
673 break;
675 case BT_HAS_INCLUDE:
676 case BT_HAS_INCLUDE_NEXT:
677 number = builtin_has_include (pfile, node,
678 node->value.builtin == BT_HAS_INCLUDE_NEXT);
679 break;
681 case BT_HAS_FEATURE:
682 case BT_HAS_EXTENSION:
683 number = pfile->cb.has_feature (pfile,
684 node->value.builtin == BT_HAS_FEATURE);
685 break;
688 if (result == NULL)
690 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
691 result = _cpp_unaligned_alloc (pfile, 21);
692 sprintf ((char *) result, "%u", number);
695 return result;
698 /* Get an idempotent date. Either the cached value, the value from
699 source epoch, or failing that, the value from time(2). Use this
700 during compilation so that every time stamp is the same. */
701 CPP_time_kind
702 cpp_get_date (cpp_reader *pfile, time_t *result)
704 if (!pfile->time_stamp_kind)
706 int kind = 0;
707 if (pfile->cb.get_source_date_epoch)
709 /* Try reading the fixed epoch. */
710 pfile->time_stamp = pfile->cb.get_source_date_epoch (pfile);
711 if (pfile->time_stamp != time_t (-1))
712 kind = int (CPP_time_kind::FIXED);
715 if (!kind)
717 /* Pedantically time_t (-1) is a legitimate value for
718 "number of seconds since the Epoch". It is a silly
719 time. */
720 errno = 0;
721 pfile->time_stamp = time (nullptr);
722 /* Annoyingly a library could legally set errno and return a
723 valid time! Bad library! */
724 if (pfile->time_stamp == time_t (-1) && errno)
725 kind = errno;
726 else
727 kind = int (CPP_time_kind::DYNAMIC);
730 pfile->time_stamp_kind = kind;
733 *result = pfile->time_stamp;
734 if (pfile->time_stamp_kind >= 0)
736 errno = pfile->time_stamp_kind;
737 return CPP_time_kind::UNKNOWN;
740 return CPP_time_kind (pfile->time_stamp_kind);
743 /* Convert builtin macros like __FILE__ to a token and push it on the
744 context stack. Also handles _Pragma, for which a new token may not
745 be created. Returns 1 if it generates a new token context, 0 to
746 return the token to the caller. LOC is the location of the expansion
747 point of the macro. */
748 static int
749 builtin_macro (cpp_reader *pfile, cpp_hashnode *node,
750 location_t loc, location_t expand_loc)
752 const uchar *buf;
753 size_t len;
754 char *nbuf;
756 if (node->value.builtin == BT_PRAGMA)
758 /* Don't interpret _Pragma within directives. The standard is
759 not clear on this, but to me this makes most sense.
760 Similarly, don't interpret _Pragma inside expand_args, we might
761 need to stringize it later on. */
762 if (pfile->state.in_directive || pfile->state.ignore__Pragma)
763 return 0;
765 return _cpp_do__Pragma (pfile, loc);
768 buf = _cpp_builtin_macro_text (pfile, node, expand_loc);
769 len = ustrlen (buf);
770 nbuf = (char *) alloca (len + 1);
771 memcpy (nbuf, buf, len);
772 nbuf[len]='\n';
774 cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
775 _cpp_clean_line (pfile);
777 /* Set pfile->cur_token as required by _cpp_lex_direct. */
778 pfile->cur_token = _cpp_temp_token (pfile);
779 cpp_token *token = _cpp_lex_direct (pfile);
780 /* We should point to the expansion point of the builtin macro. */
781 token->src_loc = loc;
782 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
784 /* We are tracking tokens resulting from macro expansion.
785 Create a macro line map and generate a virtual location for
786 the token resulting from the expansion of the built-in
787 macro. */
788 location_t *virt_locs = NULL;
789 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
790 const line_map_macro * map =
791 linemap_enter_macro (pfile->line_table, node, loc, 1);
792 tokens_buff_add_token (token_buf, virt_locs, token,
793 pfile->line_table->builtin_location,
794 pfile->line_table->builtin_location,
795 map, /*macro_token_index=*/0);
796 push_extended_tokens_context (pfile, node, token_buf, virt_locs,
797 (const cpp_token **)token_buf->base,
800 else
801 _cpp_push_token_context (pfile, NULL, token, 1);
802 if (pfile->buffer->cur != pfile->buffer->rlimit)
803 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
804 NODE_NAME (node));
805 _cpp_pop_buffer (pfile);
807 return 1;
810 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
811 backslashes and double quotes. DEST must be of sufficient size.
812 Returns a pointer to the end of the string. */
813 uchar *
814 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
816 while (len--)
818 uchar c = *src++;
820 switch (c)
822 case '\n':
823 /* Naked LF can appear in raw string literals */
824 c = 'n';
825 /* FALLTHROUGH */
827 case '\\':
828 case '"':
829 *dest++ = '\\';
830 /* FALLTHROUGH */
832 default:
833 *dest++ = c;
837 return dest;
840 /* Convert a token sequence FIRST to FIRST+COUNT-1 to a single string token
841 according to the rules of the ISO C #-operator. */
842 static const cpp_token *
843 stringify_arg (cpp_reader *pfile, const cpp_token **first, unsigned int count)
845 unsigned char *dest;
846 unsigned int i, escape_it, backslash_count = 0;
847 const cpp_token *source = NULL;
848 size_t len;
850 if (BUFF_ROOM (pfile->u_buff) < 3)
851 _cpp_extend_buff (pfile, &pfile->u_buff, 3);
852 dest = BUFF_FRONT (pfile->u_buff);
853 *dest++ = '"';
855 /* Loop, reading in the argument's tokens. */
856 for (i = 0; i < count; i++)
858 const cpp_token *token = first[i];
860 if (token->type == CPP_PADDING)
862 if (source == NULL
863 || (!(source->flags & PREV_WHITE)
864 && token->val.source == NULL))
865 source = token->val.source;
866 continue;
869 escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
870 || token->type == CPP_WSTRING || token->type == CPP_WCHAR
871 || token->type == CPP_STRING32 || token->type == CPP_CHAR32
872 || token->type == CPP_STRING16 || token->type == CPP_CHAR16
873 || token->type == CPP_UTF8STRING || token->type == CPP_UTF8CHAR
874 || cpp_userdef_string_p (token->type)
875 || cpp_userdef_char_p (token->type));
877 /* Room for each char being written in octal, initial space and
878 final quote and NUL. */
879 len = cpp_token_len (token);
880 if (escape_it)
881 len *= 4;
882 len += 3;
884 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
886 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
887 _cpp_extend_buff (pfile, &pfile->u_buff, len);
888 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
891 /* Leading white space? */
892 if (dest - 1 != BUFF_FRONT (pfile->u_buff))
894 if (source == NULL)
895 source = token;
896 if (source->flags & PREV_WHITE)
897 *dest++ = ' ';
899 source = NULL;
901 if (escape_it)
903 _cpp_buff *buff = _cpp_get_buff (pfile, len);
904 unsigned char *buf = BUFF_FRONT (buff);
905 len = cpp_spell_token (pfile, token, buf, true) - buf;
906 dest = cpp_quote_string (dest, buf, len);
907 _cpp_release_buff (pfile, buff);
909 else
910 dest = cpp_spell_token (pfile, token, dest, true);
912 if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
913 backslash_count++;
914 else
915 backslash_count = 0;
918 /* Ignore the final \ of invalid string literals. */
919 if (backslash_count & 1)
921 cpp_error (pfile, CPP_DL_WARNING,
922 "invalid string literal, ignoring final '\\'");
923 dest--;
926 /* Commit the memory, including NUL, and return the token. */
927 *dest++ = '"';
928 len = dest - BUFF_FRONT (pfile->u_buff);
929 BUFF_FRONT (pfile->u_buff) = dest + 1;
930 return new_string_token (pfile, dest - len, len);
933 /* Try to paste two tokens. On success, return nonzero. In any
934 case, PLHS is updated to point to the pasted token, which is
935 guaranteed to not have the PASTE_LEFT flag set. LOCATION is
936 the virtual location used for error reporting. */
937 static bool
938 paste_tokens (cpp_reader *pfile, location_t location,
939 const cpp_token **plhs, const cpp_token *rhs)
941 unsigned char *buf, *end, *lhsend;
942 cpp_token *lhs;
943 unsigned int len;
945 len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 2;
946 buf = (unsigned char *) alloca (len);
947 end = lhsend = cpp_spell_token (pfile, *plhs, buf, true);
949 /* Avoid comment headers, since they are still processed in stage 3.
950 It is simpler to insert a space here, rather than modifying the
951 lexer to ignore comments in some circumstances. Simply returning
952 false doesn't work, since we want to clear the PASTE_LEFT flag. */
953 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
954 *end++ = ' ';
955 /* In one obscure case we might see padding here. */
956 if (rhs->type != CPP_PADDING)
957 end = cpp_spell_token (pfile, rhs, end, true);
958 *end = '\n';
960 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
961 _cpp_clean_line (pfile);
963 /* Set pfile->cur_token as required by _cpp_lex_direct. */
964 pfile->cur_token = _cpp_temp_token (pfile);
965 lhs = _cpp_lex_direct (pfile);
966 if (pfile->buffer->cur != pfile->buffer->rlimit)
968 location_t saved_loc = lhs->src_loc;
970 _cpp_pop_buffer (pfile);
972 unsigned char *rhsstart = lhsend;
973 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
974 rhsstart++;
976 /* We have to remove the PASTE_LEFT flag from the old lhs, but
977 we want to keep the new location. */
978 *lhs = **plhs;
979 *plhs = lhs;
980 lhs->src_loc = saved_loc;
981 lhs->flags &= ~PASTE_LEFT;
983 /* Mandatory error for all apart from assembler. */
984 if (CPP_OPTION (pfile, lang) != CLK_ASM)
985 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
986 "pasting \"%.*s\" and \"%.*s\" does not give "
987 "a valid preprocessing token",
988 (int) (lhsend - buf), buf,
989 (int) (end - rhsstart), rhsstart);
990 return false;
993 lhs->flags |= (*plhs)->flags & (PREV_WHITE | PREV_FALLTHROUGH);
994 *plhs = lhs;
995 _cpp_pop_buffer (pfile);
996 return true;
999 /* Handles an arbitrarily long sequence of ## operators, with initial
1000 operand LHS. This implementation is left-associative,
1001 non-recursive, and finishes a paste before handling succeeding
1002 ones. If a paste fails, we back up to the RHS of the failing ##
1003 operator before pushing the context containing the result of prior
1004 successful pastes, with the effect that the RHS appears in the
1005 output stream after the pasted LHS normally. */
1006 static void
1007 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
1009 const cpp_token *rhs = NULL;
1010 cpp_context *context = pfile->context;
1011 location_t virt_loc = 0;
1013 /* We are expanding a macro and we must have been called on a token
1014 that appears at the left hand side of a ## operator. */
1015 if (macro_of_context (pfile->context) == NULL
1016 || (!(lhs->flags & PASTE_LEFT)))
1017 abort ();
1019 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
1020 /* The caller must have called consume_next_token_from_context
1021 right before calling us. That has incremented the pointer to
1022 the current virtual location. So it now points to the location
1023 of the token that comes right after *LHS. We want the
1024 resulting pasted token to have the location of the current
1025 *LHS, though. */
1026 virt_loc = context->c.mc->cur_virt_loc[-1];
1027 else
1028 /* We are not tracking macro expansion. So the best virtual
1029 location we can get here is the expansion point of the macro we
1030 are currently expanding. */
1031 virt_loc = pfile->invocation_location;
1035 /* Take the token directly from the current context. We can do
1036 this, because we are in the replacement list of either an
1037 object-like macro, or a function-like macro with arguments
1038 inserted. In either case, the constraints to #define
1039 guarantee we have at least one more token. */
1040 if (context->tokens_kind == TOKENS_KIND_DIRECT)
1041 rhs = FIRST (context).token++;
1042 else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
1043 rhs = *FIRST (context).ptoken++;
1044 else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
1046 /* So we are in presence of an extended token context, which
1047 means that each token in this context has a virtual
1048 location attached to it. So let's not forget to update
1049 the pointer to the current virtual location of the
1050 current token when we update the pointer to the current
1051 token */
1053 rhs = *FIRST (context).ptoken++;
1054 /* context->c.mc must be non-null, as if we were not in a
1055 macro context, context->tokens_kind could not be equal to
1056 TOKENS_KIND_EXTENDED. */
1057 context->c.mc->cur_virt_loc++;
1060 if (rhs->type == CPP_PADDING)
1062 if (rhs->flags & PASTE_LEFT)
1063 abort ();
1065 if (!paste_tokens (pfile, virt_loc, &lhs, rhs))
1067 _cpp_backup_tokens (pfile, 1);
1068 break;
1071 while (rhs->flags & PASTE_LEFT);
1073 /* Put the resulting token in its own context. */
1074 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
1076 location_t *virt_locs = NULL;
1077 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
1078 tokens_buff_add_token (token_buf, virt_locs, lhs,
1079 virt_loc, 0, NULL, 0);
1080 push_extended_tokens_context (pfile, context->c.mc->macro_node,
1081 token_buf, virt_locs,
1082 (const cpp_token **)token_buf->base, 1);
1084 else
1085 _cpp_push_token_context (pfile, NULL, lhs, 1);
1088 /* Returns TRUE if the number of arguments ARGC supplied in an
1089 invocation of the MACRO referenced by NODE is valid. An empty
1090 invocation to a macro with no parameters should pass ARGC as zero.
1092 Note that MACRO cannot necessarily be deduced from NODE, in case
1093 NODE was redefined whilst collecting arguments. */
1094 bool
1095 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
1097 if (argc == macro->paramc)
1098 return true;
1100 if (argc < macro->paramc)
1102 /* In C++20 and C23 (here the va_opt flag is used), and also as a GNU
1103 extension, variadic arguments are allowed to not appear in
1104 the invocation at all.
1105 e.g. #define debug(format, args...) something
1106 debug("string");
1108 This is exactly the same as if an empty variadic list had been
1109 supplied - debug("string", ). */
1111 if (argc + 1 == macro->paramc && macro->variadic)
1113 if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1114 && ! CPP_OPTION (pfile, va_opt))
1116 if (CPP_OPTION (pfile, cplusplus))
1117 cpp_error (pfile, CPP_DL_PEDWARN,
1118 "ISO C++11 requires at least one argument "
1119 "for the \"...\" in a variadic macro");
1120 else
1121 cpp_error (pfile, CPP_DL_PEDWARN,
1122 "ISO C99 requires at least one argument "
1123 "for the \"...\" in a variadic macro");
1125 return true;
1128 cpp_error (pfile, CPP_DL_ERROR,
1129 "macro \"%s\" requires %u arguments, but only %u given",
1130 NODE_NAME (node), macro->paramc, argc);
1132 else
1133 cpp_error (pfile, CPP_DL_ERROR,
1134 "macro \"%s\" passed %u arguments, but takes just %u",
1135 NODE_NAME (node), argc, macro->paramc);
1137 if (macro->line > RESERVED_LOCATION_COUNT)
1138 cpp_error_at (pfile, CPP_DL_NOTE, macro->line, "macro \"%s\" defined here",
1139 NODE_NAME (node));
1141 return false;
1144 /* Reads and returns the arguments to a function-like macro
1145 invocation. Assumes the opening parenthesis has been processed.
1146 If there is an error, emits an appropriate diagnostic and returns
1147 NULL. Each argument is terminated by a CPP_EOF token, for the
1148 future benefit of expand_arg(). If there are any deferred
1149 #pragma directives among macro arguments, store pointers to the
1150 CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
1152 What is returned is the buffer that contains the memory allocated
1153 to hold the macro arguments. NODE is the name of the macro this
1154 function is dealing with. If NUM_ARGS is non-NULL, *NUM_ARGS is
1155 set to the actual number of macro arguments allocated in the
1156 returned buffer. */
1157 static _cpp_buff *
1158 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
1159 _cpp_buff **pragma_buff, unsigned *num_args)
1161 _cpp_buff *buff, *base_buff;
1162 cpp_macro *macro;
1163 macro_arg *args, *arg;
1164 const cpp_token *token;
1165 unsigned int argc;
1166 location_t virt_loc;
1167 bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
1168 unsigned num_args_alloced = 0;
1170 macro = node->value.macro;
1171 if (macro->paramc)
1172 argc = macro->paramc;
1173 else
1174 argc = 1;
1176 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
1177 #define ARG_TOKENS_EXTENT 1000
1179 buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
1180 * sizeof (cpp_token *)
1181 + sizeof (macro_arg)));
1182 base_buff = buff;
1183 args = (macro_arg *) buff->base;
1184 memset (args, 0, argc * sizeof (macro_arg));
1185 buff->cur = (unsigned char *) &args[argc];
1186 arg = args, argc = 0;
1188 /* Collect the tokens making up each argument. We don't yet know
1189 how many arguments have been supplied, whether too many or too
1190 few. Hence the slightly bizarre usage of "argc" and "arg". */
1193 unsigned int paren_depth = 0;
1194 unsigned int ntokens = 0;
1195 unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
1196 num_args_alloced++;
1198 argc++;
1199 arg->first = (const cpp_token **) buff->cur;
1200 if (track_macro_expansion_p)
1202 virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
1203 arg->virt_locs = XNEWVEC (location_t,
1204 virt_locs_capacity);
1207 for (;;)
1209 /* Require space for 2 new tokens (including a CPP_EOF). */
1210 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
1212 buff = _cpp_append_extend_buff (pfile, buff,
1213 ARG_TOKENS_EXTENT
1214 * sizeof (cpp_token *));
1215 arg->first = (const cpp_token **) buff->cur;
1217 if (track_macro_expansion_p
1218 && (ntokens + 2 > virt_locs_capacity))
1220 virt_locs_capacity += ARG_TOKENS_EXTENT;
1221 arg->virt_locs = XRESIZEVEC (location_t,
1222 arg->virt_locs,
1223 virt_locs_capacity);
1226 token = cpp_get_token_1 (pfile, &virt_loc);
1228 if (token->type == CPP_PADDING)
1230 /* Drop leading padding. */
1231 if (ntokens == 0)
1232 continue;
1234 else if (token->type == CPP_OPEN_PAREN)
1235 paren_depth++;
1236 else if (token->type == CPP_CLOSE_PAREN)
1238 if (paren_depth-- == 0)
1239 break;
1241 else if (token->type == CPP_COMMA)
1243 /* A comma does not terminate an argument within
1244 parentheses or as part of a variable argument. */
1245 if (paren_depth == 0
1246 && ! (macro->variadic && argc == macro->paramc))
1247 break;
1249 else if (token->type == CPP_EOF
1250 || (token->type == CPP_HASH && token->flags & BOL))
1251 break;
1252 else if (token->type == CPP_PRAGMA && !(token->flags & PRAGMA_OP))
1254 cpp_token *newtok = _cpp_temp_token (pfile);
1256 /* CPP_PRAGMA token lives in directive_result, which will
1257 be overwritten on the next directive. */
1258 *newtok = *token;
1259 token = newtok;
1262 if (*pragma_buff == NULL
1263 || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
1265 _cpp_buff *next;
1266 if (*pragma_buff == NULL)
1267 *pragma_buff
1268 = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
1269 else
1271 next = *pragma_buff;
1272 *pragma_buff
1273 = _cpp_get_buff (pfile,
1274 (BUFF_FRONT (*pragma_buff)
1275 - (*pragma_buff)->base) * 2);
1276 (*pragma_buff)->next = next;
1279 *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
1280 BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
1281 if (token->type == CPP_PRAGMA_EOL)
1282 break;
1283 token = cpp_get_token_1 (pfile, &virt_loc);
1285 while (token->type != CPP_EOF);
1287 /* In deferred pragmas parsing_args and prevent_expansion
1288 had been changed, reset it. */
1289 pfile->state.parsing_args = 2;
1290 pfile->state.prevent_expansion = 1;
1292 if (token->type == CPP_EOF)
1293 break;
1294 else
1295 continue;
1297 set_arg_token (arg, token, virt_loc,
1298 ntokens, MACRO_ARG_TOKEN_NORMAL,
1299 CPP_OPTION (pfile, track_macro_expansion));
1300 ntokens++;
1303 /* Drop trailing padding. */
1304 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
1305 ntokens--;
1307 arg->count = ntokens;
1308 /* Append an EOF to mark end-of-argument. */
1309 set_arg_token (arg, &pfile->endarg, token->src_loc,
1310 ntokens, MACRO_ARG_TOKEN_NORMAL,
1311 CPP_OPTION (pfile, track_macro_expansion));
1313 /* Terminate the argument. Excess arguments loop back and
1314 overwrite the final legitimate argument, before failing. */
1315 if (argc <= macro->paramc)
1317 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
1318 if (argc != macro->paramc)
1319 arg++;
1322 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
1324 if (token->type == CPP_EOF)
1326 /* Unless the EOF is marking the end of an argument, it's a fake
1327 one from the end of a file that _cpp_clean_line will not have
1328 advanced past. */
1329 if (token == &pfile->endarg)
1330 _cpp_backup_tokens (pfile, 1);
1331 cpp_error (pfile, CPP_DL_ERROR,
1332 "unterminated argument list invoking macro \"%s\"",
1333 NODE_NAME (node));
1335 else
1337 /* A single empty argument is counted as no argument. */
1338 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
1339 argc = 0;
1340 if (_cpp_arguments_ok (pfile, macro, node, argc))
1342 /* GCC has special semantics for , ## b where b is a varargs
1343 parameter: we remove the comma if b was omitted entirely.
1344 If b was merely an empty argument, the comma is retained.
1345 If the macro takes just one (varargs) parameter, then we
1346 retain the comma only if we are standards conforming.
1348 If FIRST is NULL replace_args () swallows the comma. */
1349 if (macro->variadic && (argc < macro->paramc
1350 || (argc == 1 && args[0].count == 0
1351 && !CPP_OPTION (pfile, std))))
1352 args[macro->paramc - 1].first = NULL;
1353 if (num_args)
1354 *num_args = num_args_alloced;
1355 return base_buff;
1359 /* An error occurred. */
1360 _cpp_release_buff (pfile, base_buff);
1361 return NULL;
1364 /* Search for an opening parenthesis to the macro of NODE, in such a
1365 way that, if none is found, we don't lose the information in any
1366 intervening padding tokens. If we find the parenthesis, collect
1367 the arguments and return the buffer containing them. PRAGMA_BUFF
1368 argument is the same as in collect_args. If NUM_ARGS is non-NULL,
1369 *NUM_ARGS is set to the number of arguments contained in the
1370 returned buffer. */
1371 static _cpp_buff *
1372 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
1373 _cpp_buff **pragma_buff, unsigned *num_args)
1375 const cpp_token *token, *padding = NULL;
1377 for (;;)
1379 token = cpp_get_token (pfile);
1380 if (token->type != CPP_PADDING)
1381 break;
1382 gcc_assert ((token->flags & PREV_WHITE) == 0);
1383 if (padding == NULL
1384 || padding->val.source == NULL
1385 || (!(padding->val.source->flags & PREV_WHITE)
1386 && token->val.source == NULL))
1387 padding = token;
1390 if (token->type == CPP_OPEN_PAREN)
1392 pfile->state.parsing_args = 2;
1393 return collect_args (pfile, node, pragma_buff, num_args);
1396 /* Back up. A CPP_EOF is either an EOF from an argument we're
1397 expanding, or a fake one from lex_direct. We want to backup the
1398 former, but not the latter. We may have skipped padding, in
1399 which case backing up more than one token when expanding macros
1400 is in general too difficult. We re-insert it in its own
1401 context. */
1402 if (token->type != CPP_EOF || token == &pfile->endarg)
1404 _cpp_backup_tokens (pfile, 1);
1405 if (padding)
1406 _cpp_push_token_context (pfile, NULL, padding, 1);
1409 return NULL;
1412 /* Return the real number of tokens in the expansion of MACRO. */
1413 static inline unsigned int
1414 macro_real_token_count (const cpp_macro *macro)
1416 if (__builtin_expect (!macro->extra_tokens, true))
1417 return macro->count;
1419 for (unsigned i = macro->count; i--;)
1420 if (macro->exp.tokens[i].type != CPP_PASTE)
1421 return i + 1;
1423 return 0;
1426 /* Push the context of a macro with hash entry NODE onto the context
1427 stack. If we can successfully expand the macro, we push a context
1428 containing its yet-to-be-rescanned replacement list and return one.
1429 If there were additionally any unexpanded deferred #pragma
1430 directives among macro arguments, push another context containing
1431 the pragma tokens before the yet-to-be-rescanned replacement list
1432 and return two. Otherwise, we don't push a context and return
1433 zero. LOCATION is the location of the expansion point of the
1434 macro. */
1435 static int
1436 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1437 const cpp_token *result, location_t location)
1439 /* The presence of a macro invalidates a file's controlling macro. */
1440 pfile->mi_valid = false;
1442 pfile->state.angled_headers = false;
1444 /* From here to when we push the context for the macro later down
1445 this function, we need to flag the fact that we are about to
1446 expand a macro. This is useful when -ftrack-macro-expansion is
1447 turned off. In that case, we need to record the location of the
1448 expansion point of the top-most macro we are about to to expand,
1449 into pfile->invocation_location. But we must not record any such
1450 location once the process of expanding the macro starts; that is,
1451 we must not do that recording between now and later down this
1452 function where set this flag to FALSE. */
1453 pfile->about_to_expand_macro_p = true;
1455 if (cpp_user_macro_p (node))
1457 cpp_macro *macro = node->value.macro;
1458 _cpp_buff *pragma_buff = NULL;
1460 if (macro->fun_like)
1462 _cpp_buff *buff;
1463 unsigned num_args = 0;
1465 pfile->state.prevent_expansion++;
1466 pfile->keep_tokens++;
1467 pfile->state.parsing_args = 1;
1468 buff = funlike_invocation_p (pfile, node, &pragma_buff,
1469 &num_args);
1470 pfile->state.parsing_args = 0;
1471 pfile->keep_tokens--;
1472 pfile->state.prevent_expansion--;
1474 if (buff == NULL)
1476 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1477 cpp_warning (pfile, CPP_W_TRADITIONAL,
1478 "function-like macro \"%s\" must be used with arguments in traditional C",
1479 NODE_NAME (node));
1481 if (pragma_buff)
1482 _cpp_release_buff (pfile, pragma_buff);
1484 pfile->about_to_expand_macro_p = false;
1485 return 0;
1488 if (macro->paramc > 0)
1489 replace_args (pfile, node, macro,
1490 (macro_arg *) buff->base,
1491 location);
1492 /* Free the memory used by the arguments of this
1493 function-like macro. This memory has been allocated by
1494 funlike_invocation_p and by replace_args. */
1495 delete_macro_args (buff, num_args);
1498 /* Disable the macro within its expansion. */
1499 node->flags |= NODE_DISABLED;
1501 /* Laziness can only affect the expansion tokens of the macro,
1502 not its fun-likeness or parameters. */
1503 _cpp_maybe_notify_macro_use (pfile, node, location);
1504 if (pfile->cb.used)
1505 pfile->cb.used (pfile, location, node);
1507 macro->used = 1;
1509 if (macro->paramc == 0)
1511 unsigned tokens_count = macro_real_token_count (macro);
1512 if (CPP_OPTION (pfile, track_macro_expansion))
1514 unsigned int i;
1515 const cpp_token *src = macro->exp.tokens;
1516 const line_map_macro *map;
1517 location_t *virt_locs = NULL;
1518 _cpp_buff *macro_tokens
1519 = tokens_buff_new (pfile, tokens_count, &virt_locs);
1521 /* Create a macro map to record the locations of the
1522 tokens that are involved in the expansion. LOCATION
1523 is the location of the macro expansion point. */
1524 map = linemap_enter_macro (pfile->line_table,
1525 node, location, tokens_count);
1526 for (i = 0; i < tokens_count; ++i)
1528 tokens_buff_add_token (macro_tokens, virt_locs,
1529 src, src->src_loc,
1530 src->src_loc, map, i);
1531 ++src;
1533 push_extended_tokens_context (pfile, node,
1534 macro_tokens,
1535 virt_locs,
1536 (const cpp_token **)
1537 macro_tokens->base,
1538 tokens_count);
1540 else
1541 _cpp_push_token_context (pfile, node, macro->exp.tokens,
1542 tokens_count);
1543 num_macro_tokens_counter += tokens_count;
1546 if (pragma_buff)
1548 if (!pfile->state.in_directive)
1549 _cpp_push_token_context (pfile, NULL,
1550 padding_token (pfile, result), 1);
1553 unsigned tokens_count;
1554 _cpp_buff *tail = pragma_buff->next;
1555 pragma_buff->next = NULL;
1556 tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1557 - (const cpp_token **) pragma_buff->base);
1558 push_ptoken_context (pfile, NULL, pragma_buff,
1559 (const cpp_token **) pragma_buff->base,
1560 tokens_count);
1561 pragma_buff = tail;
1562 if (!CPP_OPTION (pfile, track_macro_expansion))
1563 num_macro_tokens_counter += tokens_count;
1566 while (pragma_buff != NULL);
1567 pfile->about_to_expand_macro_p = false;
1568 return 2;
1571 pfile->about_to_expand_macro_p = false;
1572 return 1;
1575 pfile->about_to_expand_macro_p = false;
1576 /* Handle built-in macros and the _Pragma operator. */
1578 location_t expand_loc;
1580 if (/* The top-level macro invocation that triggered the expansion
1581 we are looking at is with a function-like user macro ... */
1582 cpp_fun_like_macro_p (pfile->top_most_macro_node)
1583 /* ... and we are tracking the macro expansion. */
1584 && CPP_OPTION (pfile, track_macro_expansion))
1585 /* Then the location of the end of the macro invocation is the
1586 location of the expansion point of this macro. */
1587 expand_loc = location;
1588 else
1589 /* Otherwise, the location of the end of the macro invocation is
1590 the location of the expansion point of that top-level macro
1591 invocation. */
1592 expand_loc = pfile->invocation_location;
1594 return builtin_macro (pfile, node, location, expand_loc);
1598 /* De-allocate the memory used by BUFF which is an array of instances
1599 of macro_arg. NUM_ARGS is the number of instances of macro_arg
1600 present in BUFF. */
1601 static void
1602 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1604 macro_arg *macro_args;
1605 unsigned i;
1607 if (buff == NULL)
1608 return;
1610 macro_args = (macro_arg *) buff->base;
1612 /* Walk instances of macro_arg to free their expanded tokens as well
1613 as their macro_arg::virt_locs members. */
1614 for (i = 0; i < num_args; ++i)
1616 if (macro_args[i].expanded)
1618 free (macro_args[i].expanded);
1619 macro_args[i].expanded = NULL;
1621 if (macro_args[i].virt_locs)
1623 free (macro_args[i].virt_locs);
1624 macro_args[i].virt_locs = NULL;
1626 if (macro_args[i].expanded_virt_locs)
1628 free (macro_args[i].expanded_virt_locs);
1629 macro_args[i].expanded_virt_locs = NULL;
1632 _cpp_free_buff (buff);
1635 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1636 to set, LOCATION is its virtual location. "Virtual" location means
1637 the location that encodes loci across macro expansion. Otherwise
1638 it has to be TOKEN->SRC_LOC. KIND is the kind of tokens the
1639 argument ARG is supposed to contain. Note that ARG must be
1640 tailored so that it has enough room to contain INDEX + 1 numbers of
1641 tokens, at least. */
1642 static void
1643 set_arg_token (macro_arg *arg, const cpp_token *token,
1644 location_t location, size_t index,
1645 enum macro_arg_token_kind kind,
1646 bool track_macro_exp_p)
1648 const cpp_token **token_ptr;
1649 location_t *loc = NULL;
1651 token_ptr =
1652 arg_token_ptr_at (arg, index, kind,
1653 track_macro_exp_p ? &loc : NULL);
1654 *token_ptr = token;
1656 if (loc != NULL)
1658 /* We can't set the location of a stringified argument
1659 token and we can't set any location if we aren't tracking
1660 macro expansion locations. */
1661 gcc_checking_assert (kind != MACRO_ARG_TOKEN_STRINGIFIED
1662 && track_macro_exp_p);
1663 *loc = location;
1667 /* Get the pointer to the location of the argument token of the
1668 function-like macro argument ARG. This function must be called
1669 only when we -ftrack-macro-expansion is on. */
1670 static const location_t *
1671 get_arg_token_location (const macro_arg *arg,
1672 enum macro_arg_token_kind kind)
1674 const location_t *loc = NULL;
1675 const cpp_token **token_ptr =
1676 arg_token_ptr_at (arg, 0, kind, (location_t **) &loc);
1678 if (token_ptr == NULL)
1679 return NULL;
1681 return loc;
1684 /* Return the pointer to the INDEXth token of the macro argument ARG.
1685 KIND specifies the kind of token the macro argument ARG contains.
1686 If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1687 of the virtual location of the returned token if the
1688 -ftrack-macro-expansion flag is on; otherwise, it's set to the
1689 spelling location of the returned token. */
1690 static const cpp_token **
1691 arg_token_ptr_at (const macro_arg *arg, size_t index,
1692 enum macro_arg_token_kind kind,
1693 location_t **virt_location)
1695 const cpp_token **tokens_ptr = NULL;
1697 switch (kind)
1699 case MACRO_ARG_TOKEN_NORMAL:
1700 tokens_ptr = arg->first;
1701 break;
1702 case MACRO_ARG_TOKEN_STRINGIFIED:
1703 tokens_ptr = (const cpp_token **) &arg->stringified;
1704 break;
1705 case MACRO_ARG_TOKEN_EXPANDED:
1706 tokens_ptr = arg->expanded;
1707 break;
1710 if (tokens_ptr == NULL)
1711 /* This can happen for e.g, an empty token argument to a
1712 funtion-like macro. */
1713 return tokens_ptr;
1715 if (virt_location)
1717 if (kind == MACRO_ARG_TOKEN_NORMAL)
1718 *virt_location = &arg->virt_locs[index];
1719 else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1720 *virt_location = &arg->expanded_virt_locs[index];
1721 else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1722 *virt_location =
1723 (location_t *) &tokens_ptr[index]->src_loc;
1725 return &tokens_ptr[index];
1728 /* Initialize an iterator so that it iterates over the tokens of a
1729 function-like macro argument. KIND is the kind of tokens we want
1730 ITER to iterate over. TOKEN_PTR points the first token ITER will
1731 iterate over. */
1732 static void
1733 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1734 bool track_macro_exp_p,
1735 enum macro_arg_token_kind kind,
1736 const macro_arg *arg,
1737 const cpp_token **token_ptr)
1739 iter->track_macro_exp_p = track_macro_exp_p;
1740 iter->kind = kind;
1741 iter->token_ptr = token_ptr;
1742 /* Unconditionally initialize this so that the compiler doesn't warn
1743 about iter->location_ptr being possibly uninitialized later after
1744 this code has been inlined somewhere. */
1745 iter->location_ptr = NULL;
1746 if (track_macro_exp_p)
1747 iter->location_ptr = get_arg_token_location (arg, kind);
1748 #if CHECKING_P
1749 iter->num_forwards = 0;
1750 if (track_macro_exp_p
1751 && token_ptr != NULL
1752 && iter->location_ptr == NULL)
1753 abort ();
1754 #endif
1757 /* Move the iterator one token forward. Note that if IT was
1758 initialized on an argument that has a stringified token, moving it
1759 forward doesn't make sense as a stringified token is essentially one
1760 string. */
1761 static void
1762 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1764 switch (it->kind)
1766 case MACRO_ARG_TOKEN_NORMAL:
1767 case MACRO_ARG_TOKEN_EXPANDED:
1768 it->token_ptr++;
1769 if (it->track_macro_exp_p)
1770 it->location_ptr++;
1771 break;
1772 case MACRO_ARG_TOKEN_STRINGIFIED:
1773 #if CHECKING_P
1774 if (it->num_forwards > 0)
1775 abort ();
1776 #endif
1777 break;
1780 #if CHECKING_P
1781 it->num_forwards++;
1782 #endif
1785 /* Return the token pointed to by the iterator. */
1786 static const cpp_token *
1787 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1789 #if CHECKING_P
1790 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1791 && it->num_forwards > 0)
1792 abort ();
1793 #endif
1794 if (it->token_ptr == NULL)
1795 return NULL;
1796 return *it->token_ptr;
1799 /* Return the location of the token pointed to by the iterator.*/
1800 static location_t
1801 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1803 #if CHECKING_P
1804 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1805 && it->num_forwards > 0)
1806 abort ();
1807 #endif
1808 if (it->track_macro_exp_p)
1809 return *it->location_ptr;
1810 else
1811 return (*it->token_ptr)->src_loc;
1814 /* Return the index of a token [resulting from macro expansion] inside
1815 the total list of tokens resulting from a given macro
1816 expansion. The index can be different depending on whether if we
1817 want each tokens resulting from function-like macro arguments
1818 expansion to have a different location or not.
1820 E.g, consider this function-like macro:
1822 #define M(x) x - 3
1824 Then consider us "calling" it (and thus expanding it) like:
1826 M(1+4)
1828 It will be expanded into:
1830 1+4-3
1832 Let's consider the case of the token '4'.
1834 Its index can be 2 (it's the third token of the set of tokens
1835 resulting from the expansion) or it can be 0 if we consider that
1836 all tokens resulting from the expansion of the argument "1+2" have
1837 the same index, which is 0. In this later case, the index of token
1838 '-' would then be 1 and the index of token '3' would be 2.
1840 The later case is useful to use less memory e.g, for the case of
1841 the user using the option -ftrack-macro-expansion=1.
1843 ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1844 are interested in. CUR_REPLACEMENT_TOKEN is the token of the macro
1845 parameter (inside the macro replacement list) that corresponds to
1846 the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1849 If we refer to the example above, for the '4' argument token,
1850 ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1851 would be set to the token 'x', in the replacement list "x - 3" of
1852 macro M.
1854 This is a subroutine of replace_args. */
1855 inline static unsigned
1856 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1857 const cpp_token *cur_replacement_token,
1858 unsigned absolute_token_index)
1860 if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1861 return absolute_token_index;
1862 return cur_replacement_token - macro->exp.tokens;
1865 /* Copy whether PASTE_LEFT is set from SRC to *PASTE_FLAG. */
1867 static void
1868 copy_paste_flag (cpp_reader *pfile, const cpp_token **paste_flag,
1869 const cpp_token *src)
1871 cpp_token *token = _cpp_temp_token (pfile);
1872 token->type = (*paste_flag)->type;
1873 token->val = (*paste_flag)->val;
1874 if (src->flags & PASTE_LEFT)
1875 token->flags = (*paste_flag)->flags | PASTE_LEFT;
1876 else
1877 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1878 *paste_flag = token;
1881 /* True IFF the last token emitted into BUFF (if any) is PTR. */
1883 static bool
1884 last_token_is (_cpp_buff *buff, const cpp_token **ptr)
1886 return (ptr && tokens_buff_last_token_ptr (buff) == ptr);
1889 /* Replace the parameters in a function-like macro of NODE with the
1890 actual ARGS, and place the result in a newly pushed token context.
1891 Expand each argument before replacing, unless it is operated upon
1892 by the # or ## operators. EXPANSION_POINT_LOC is the location of
1893 the expansion point of the macro. E.g, the location of the
1894 function-like macro invocation. */
1895 static void
1896 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1897 macro_arg *args, location_t expansion_point_loc)
1899 unsigned int i, total;
1900 const cpp_token *src, *limit;
1901 const cpp_token **first = NULL;
1902 macro_arg *arg;
1903 _cpp_buff *buff = NULL;
1904 location_t *virt_locs = NULL;
1905 unsigned int exp_count;
1906 const line_map_macro *map = NULL;
1907 int track_macro_exp;
1909 /* First, fully macro-expand arguments, calculating the number of
1910 tokens in the final expansion as we go. The ordering of the if
1911 statements below is subtle; we must handle stringification before
1912 pasting. */
1914 /* EXP_COUNT is the number of tokens in the macro replacement
1915 list. TOTAL is the number of tokens /after/ macro parameters
1916 have been replaced by their arguments. */
1917 exp_count = macro_real_token_count (macro);
1918 total = exp_count;
1919 limit = macro->exp.tokens + exp_count;
1921 for (src = macro->exp.tokens; src < limit; src++)
1922 if (src->type == CPP_MACRO_ARG)
1924 /* Leading and trailing padding tokens. */
1925 total += 2;
1926 /* Account for leading and padding tokens in exp_count too.
1927 This is going to be important later down this function,
1928 when we want to handle the case of (track_macro_exp <
1929 2). */
1930 exp_count += 2;
1932 /* We have an argument. If it is not being stringified or
1933 pasted it is macro-replaced before insertion. */
1934 arg = &args[src->val.macro_arg.arg_no - 1];
1936 if (src->flags & STRINGIFY_ARG)
1938 if (!arg->stringified)
1939 arg->stringified = stringify_arg (pfile, arg->first, arg->count);
1941 else if ((src->flags & PASTE_LEFT)
1942 || (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1943 total += arg->count - 1;
1944 else
1946 if (!arg->expanded)
1947 expand_arg (pfile, arg);
1948 total += arg->expanded_count - 1;
1952 /* When the compiler is called with the -ftrack-macro-expansion
1953 flag, we need to keep track of the location of each token that
1954 results from macro expansion.
1956 A token resulting from macro expansion is not a new token. It is
1957 simply the same token as the token coming from the macro
1958 definition. The new things that are allocated are the buffer
1959 that holds the tokens resulting from macro expansion and a new
1960 location that records many things like the locus of the expansion
1961 point as well as the original locus inside the definition of the
1962 macro. This location is called a virtual location.
1964 So the buffer BUFF holds a set of cpp_token*, and the buffer
1965 VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1967 Both of these two buffers are going to be hung off of the macro
1968 context, when the latter is pushed. The memory allocated to
1969 store the tokens and their locations is going to be freed once
1970 the context of macro expansion is popped.
1972 As far as tokens are concerned, the memory overhead of
1973 -ftrack-macro-expansion is proportional to the number of
1974 macros that get expanded multiplied by sizeof (location_t).
1975 The good news is that extra memory gets freed when the macro
1976 context is freed, i.e shortly after the macro got expanded. */
1978 /* Is the -ftrack-macro-expansion flag in effect? */
1979 track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1981 /* Now allocate memory space for tokens and locations resulting from
1982 the macro expansion, copy the tokens and replace the arguments.
1983 This memory must be freed when the context of the macro MACRO is
1984 popped. */
1985 buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1987 first = (const cpp_token **) buff->base;
1989 /* Create a macro map to record the locations of the tokens that are
1990 involved in the expansion. Note that the expansion point is set
1991 to the location of the closing parenthesis. Otherwise, the
1992 subsequent map created for the first token that comes after the
1993 macro map might have a wrong line number. That would lead to
1994 tokens with wrong line numbers after the macro expansion. This
1995 adds up to the memory overhead of the -ftrack-macro-expansion
1996 flag; for every macro that is expanded, a "macro map" is
1997 created. */
1998 if (track_macro_exp)
2000 int num_macro_tokens = total;
2001 if (track_macro_exp < 2)
2002 /* Then the number of macro tokens won't take in account the
2003 fact that function-like macro arguments can expand to
2004 multiple tokens. This is to save memory at the expense of
2005 accuracy.
2007 Suppose we have #define SQUARE(A) A * A
2009 And then we do SQUARE(2+3)
2011 Then the tokens 2, +, 3, will have the same location,
2012 saying they come from the expansion of the argument A. */
2013 num_macro_tokens = exp_count;
2014 map = linemap_enter_macro (pfile->line_table, node,
2015 expansion_point_loc,
2016 num_macro_tokens);
2018 i = 0;
2019 vaopt_state vaopt_tracker (pfile, macro->variadic, &args[macro->paramc - 1]);
2020 const cpp_token **vaopt_start = NULL;
2021 for (src = macro->exp.tokens; src < limit; src++)
2023 unsigned int arg_tokens_count;
2024 macro_arg_token_iter from;
2025 const cpp_token **paste_flag = NULL;
2026 const cpp_token **tmp_token_ptr;
2028 /* __VA_OPT__ handling. */
2029 vaopt_state::update_type vostate = vaopt_tracker.update (src);
2030 if (__builtin_expect (vostate != vaopt_state::INCLUDE, false))
2032 if (vostate == vaopt_state::BEGIN)
2034 /* Padding on the left of __VA_OPT__ (unless RHS of ##). */
2035 if (src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
2037 const cpp_token *t = padding_token (pfile, src);
2038 unsigned index = expanded_token_index (pfile, macro, src, i);
2039 /* Allocate a virtual location for the padding token and
2040 append the token and its location to BUFF and
2041 VIRT_LOCS. */
2042 tokens_buff_add_token (buff, virt_locs, t,
2043 t->src_loc, t->src_loc,
2044 map, index);
2046 vaopt_start = tokens_buff_last_token_ptr (buff);
2048 else if (vostate == vaopt_state::END)
2050 const cpp_token **start = vaopt_start;
2051 vaopt_start = NULL;
2053 paste_flag = tokens_buff_last_token_ptr (buff);
2055 if (vaopt_tracker.stringify ())
2057 unsigned int count
2058 = start ? paste_flag - start : tokens_buff_count (buff);
2059 const cpp_token **first
2060 = start ? start + 1
2061 : (const cpp_token **) (buff->base);
2062 unsigned int i, j;
2064 /* Paste any tokens that need to be pasted before calling
2065 stringify_arg, because stringify_arg uses pfile->u_buff
2066 which paste_tokens can use as well. */
2067 for (i = 0, j = 0; i < count; i++, j++)
2069 const cpp_token *token = first[i];
2071 if (token->flags & PASTE_LEFT)
2073 location_t virt_loc = pfile->invocation_location;
2074 const cpp_token *rhs;
2077 if (i == count)
2078 abort ();
2079 rhs = first[++i];
2080 if (!paste_tokens (pfile, virt_loc, &token, rhs))
2082 --i;
2083 break;
2086 while (rhs->flags & PASTE_LEFT);
2089 first[j] = token;
2091 if (j != i)
2093 while (i-- != j)
2094 tokens_buff_remove_last_token (buff);
2095 count = j;
2098 const cpp_token *t = stringify_arg (pfile, first, count);
2099 while (count--)
2100 tokens_buff_remove_last_token (buff);
2101 if (src->flags & PASTE_LEFT)
2102 copy_paste_flag (pfile, &t, src);
2103 tokens_buff_add_token (buff, virt_locs,
2104 t, t->src_loc, t->src_loc,
2105 NULL, 0);
2106 continue;
2108 if (start && paste_flag == start && (*start)->flags & PASTE_LEFT)
2109 /* If __VA_OPT__ expands to nothing (either because __VA_ARGS__
2110 is empty or because it is __VA_OPT__() ), drop PASTE_LEFT
2111 flag from previous token. */
2112 copy_paste_flag (pfile, start, &pfile->avoid_paste);
2113 if (src->flags & PASTE_LEFT)
2115 /* Don't avoid paste after all. */
2116 while (paste_flag && paste_flag != start
2117 && *paste_flag == &pfile->avoid_paste)
2119 tokens_buff_remove_last_token (buff);
2120 paste_flag = tokens_buff_last_token_ptr (buff);
2123 /* With a non-empty __VA_OPT__ on the LHS of ##, the last
2124 token should be flagged PASTE_LEFT. */
2125 if (paste_flag && (*paste_flag)->type != CPP_PADDING)
2126 copy_paste_flag (pfile, paste_flag, src);
2128 else
2130 /* Otherwise, avoid paste on RHS, __VA_OPT__(c)d or
2131 __VA_OPT__(c)__VA_OPT__(d). */
2132 const cpp_token *t = &pfile->avoid_paste;
2133 tokens_buff_add_token (buff, virt_locs,
2134 t, t->src_loc, t->src_loc,
2135 NULL, 0);
2138 continue;
2141 if (src->type != CPP_MACRO_ARG)
2143 /* Allocate a virtual location for token SRC, and add that
2144 token and its virtual location into the buffers BUFF and
2145 VIRT_LOCS. */
2146 unsigned index = expanded_token_index (pfile, macro, src, i);
2147 tokens_buff_add_token (buff, virt_locs, src,
2148 src->src_loc, src->src_loc,
2149 map, index);
2150 i += 1;
2151 continue;
2154 paste_flag = 0;
2155 arg = &args[src->val.macro_arg.arg_no - 1];
2156 /* SRC is a macro parameter that we need to replace with its
2157 corresponding argument. So at some point we'll need to
2158 iterate over the tokens of the macro argument and copy them
2159 into the "place" now holding the correspondig macro
2160 parameter. We are going to use the iterator type
2161 macro_argo_token_iter to handle that iterating. The 'if'
2162 below is to initialize the iterator depending on the type of
2163 tokens the macro argument has. It also does some adjustment
2164 related to padding tokens and some pasting corner cases. */
2165 if (src->flags & STRINGIFY_ARG)
2167 arg_tokens_count = 1;
2168 macro_arg_token_iter_init (&from,
2169 CPP_OPTION (pfile,
2170 track_macro_expansion),
2171 MACRO_ARG_TOKEN_STRINGIFIED,
2172 arg, &arg->stringified);
2174 else if (src->flags & PASTE_LEFT)
2176 arg_tokens_count = arg->count;
2177 macro_arg_token_iter_init (&from,
2178 CPP_OPTION (pfile,
2179 track_macro_expansion),
2180 MACRO_ARG_TOKEN_NORMAL,
2181 arg, arg->first);
2183 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
2185 int num_toks;
2186 arg_tokens_count = arg->count;
2187 macro_arg_token_iter_init (&from,
2188 CPP_OPTION (pfile,
2189 track_macro_expansion),
2190 MACRO_ARG_TOKEN_NORMAL,
2191 arg, arg->first);
2193 num_toks = tokens_buff_count (buff);
2195 if (num_toks != 0)
2197 /* So the current parameter token is pasted to the previous
2198 token in the replacement list. Let's look at what
2199 we have as previous and current arguments. */
2201 /* This is the previous argument's token ... */
2202 tmp_token_ptr = tokens_buff_last_token_ptr (buff);
2204 if ((*tmp_token_ptr)->type == CPP_COMMA
2205 && macro->variadic
2206 && src->val.macro_arg.arg_no == macro->paramc)
2208 /* ... which is a comma; and the current parameter
2209 is the last parameter of a variadic function-like
2210 macro. If the argument to the current last
2211 parameter is NULL, then swallow the comma,
2212 otherwise drop the paste flag. */
2213 if (macro_arg_token_iter_get_token (&from) == NULL)
2214 tokens_buff_remove_last_token (buff);
2215 else
2216 paste_flag = tmp_token_ptr;
2218 /* Remove the paste flag if the RHS is a placemarker. */
2219 else if (arg_tokens_count == 0)
2220 paste_flag = tmp_token_ptr;
2223 else
2225 arg_tokens_count = arg->expanded_count;
2226 macro_arg_token_iter_init (&from,
2227 CPP_OPTION (pfile,
2228 track_macro_expansion),
2229 MACRO_ARG_TOKEN_EXPANDED,
2230 arg, arg->expanded);
2232 if (last_token_is (buff, vaopt_start))
2234 /* We're expanding an arg at the beginning of __VA_OPT__.
2235 Skip padding. */
2236 while (arg_tokens_count)
2238 const cpp_token *t = macro_arg_token_iter_get_token (&from);
2239 if (t->type != CPP_PADDING)
2240 break;
2241 macro_arg_token_iter_forward (&from);
2242 --arg_tokens_count;
2247 /* Padding on the left of an argument (unless RHS of ##). */
2248 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
2249 && src != macro->exp.tokens
2250 && !(src[-1].flags & PASTE_LEFT)
2251 && !last_token_is (buff, vaopt_start))
2253 const cpp_token *t = padding_token (pfile, src);
2254 unsigned index = expanded_token_index (pfile, macro, src, i);
2255 /* Allocate a virtual location for the padding token and
2256 append the token and its location to BUFF and
2257 VIRT_LOCS. */
2258 tokens_buff_add_token (buff, virt_locs, t,
2259 t->src_loc, t->src_loc,
2260 map, index);
2263 if (arg_tokens_count)
2265 /* So now we've got the number of tokens that make up the
2266 argument that is going to replace the current parameter
2267 in the macro's replacement list. */
2268 unsigned int j;
2269 for (j = 0; j < arg_tokens_count; ++j)
2271 /* So if track_macro_exp is < 2, the user wants to
2272 save extra memory while tracking macro expansion
2273 locations. So in that case here is what we do:
2275 Suppose we have #define SQUARE(A) A * A
2277 And then we do SQUARE(2+3)
2279 Then the tokens 2, +, 3, will have the same location,
2280 saying they come from the expansion of the argument
2283 So that means we are going to ignore the COUNT tokens
2284 resulting from the expansion of the current macro
2285 argument. In other words all the ARG_TOKENS_COUNT tokens
2286 resulting from the expansion of the macro argument will
2287 have the index I. Normally, each of those tokens should
2288 have index I+J. */
2289 unsigned token_index = i;
2290 unsigned index;
2291 if (track_macro_exp > 1)
2292 token_index += j;
2294 index = expanded_token_index (pfile, macro, src, token_index);
2295 const cpp_token *tok = macro_arg_token_iter_get_token (&from);
2296 tokens_buff_add_token (buff, virt_locs, tok,
2297 macro_arg_token_iter_get_location (&from),
2298 src->src_loc, map, index);
2299 macro_arg_token_iter_forward (&from);
2302 /* With a non-empty argument on the LHS of ##, the last
2303 token should be flagged PASTE_LEFT. */
2304 if (src->flags & PASTE_LEFT)
2305 paste_flag
2306 = (const cpp_token **) tokens_buff_last_token_ptr (buff);
2308 else if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99)
2309 && ! macro->syshdr && ! _cpp_in_system_header (pfile))
2311 if (CPP_OPTION (pfile, cplusplus))
2312 cpp_pedwarning (pfile, CPP_W_PEDANTIC,
2313 "invoking macro %s argument %d: "
2314 "empty macro arguments are undefined"
2315 " in ISO C++98",
2316 NODE_NAME (node), src->val.macro_arg.arg_no);
2317 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat))
2318 cpp_pedwarning (pfile,
2319 CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2320 ? CPP_W_C90_C99_COMPAT : CPP_W_PEDANTIC,
2321 "invoking macro %s argument %d: "
2322 "empty macro arguments are undefined"
2323 " in ISO C90",
2324 NODE_NAME (node), src->val.macro_arg.arg_no);
2326 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2327 && ! CPP_OPTION (pfile, cplusplus)
2328 && ! macro->syshdr && ! _cpp_in_system_header (pfile))
2329 cpp_warning (pfile, CPP_W_C90_C99_COMPAT,
2330 "invoking macro %s argument %d: "
2331 "empty macro arguments are undefined"
2332 " in ISO C90",
2333 NODE_NAME (node), src->val.macro_arg.arg_no);
2335 /* Avoid paste on RHS (even case count == 0). */
2336 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
2338 const cpp_token *t = &pfile->avoid_paste;
2339 tokens_buff_add_token (buff, virt_locs,
2340 t, t->src_loc, t->src_loc,
2341 NULL, 0);
2344 /* Add a new paste flag, or remove an unwanted one. */
2345 if (paste_flag)
2346 copy_paste_flag (pfile, paste_flag, src);
2348 i += arg_tokens_count;
2351 if (track_macro_exp)
2352 push_extended_tokens_context (pfile, node, buff, virt_locs, first,
2353 tokens_buff_count (buff));
2354 else
2355 push_ptoken_context (pfile, node, buff, first,
2356 tokens_buff_count (buff));
2358 num_macro_tokens_counter += tokens_buff_count (buff);
2361 /* Return a special padding token, with padding inherited from SOURCE. */
2362 static const cpp_token *
2363 padding_token (cpp_reader *pfile, const cpp_token *source)
2365 cpp_token *result = _cpp_temp_token (pfile);
2367 result->type = CPP_PADDING;
2369 /* Data in GCed data structures cannot be made const so far, so we
2370 need a cast here. */
2371 result->val.source = (cpp_token *) source;
2372 result->flags = 0;
2373 return result;
2376 /* Get a new uninitialized context. Create a new one if we cannot
2377 re-use an old one. */
2378 static cpp_context *
2379 next_context (cpp_reader *pfile)
2381 cpp_context *result = pfile->context->next;
2383 if (result == 0)
2385 result = XNEW (cpp_context);
2386 memset (result, 0, sizeof (cpp_context));
2387 result->prev = pfile->context;
2388 result->next = 0;
2389 pfile->context->next = result;
2392 pfile->context = result;
2393 return result;
2396 /* Push a list of pointers to tokens. */
2397 static void
2398 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
2399 const cpp_token **first, unsigned int count)
2401 cpp_context *context = next_context (pfile);
2403 context->tokens_kind = TOKENS_KIND_INDIRECT;
2404 context->c.macro = macro;
2405 context->buff = buff;
2406 FIRST (context).ptoken = first;
2407 LAST (context).ptoken = first + count;
2410 /* Push a list of tokens.
2412 A NULL macro means that we should continue the current macro
2413 expansion, in essence. That means that if we are currently in a
2414 macro expansion context, we'll make the new pfile->context refer to
2415 the current macro. */
2416 void
2417 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
2418 const cpp_token *first, unsigned int count)
2420 cpp_context *context;
2422 if (macro == NULL)
2423 macro = macro_of_context (pfile->context);
2425 context = next_context (pfile);
2426 context->tokens_kind = TOKENS_KIND_DIRECT;
2427 context->c.macro = macro;
2428 context->buff = NULL;
2429 FIRST (context).token = first;
2430 LAST (context).token = first + count;
2433 /* Build a context containing a list of tokens as well as their
2434 virtual locations and push it. TOKENS_BUFF is the buffer that
2435 contains the tokens pointed to by FIRST. If TOKENS_BUFF is
2436 non-NULL, it means that the context owns it, meaning that
2437 _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
2438 contains the virtual locations.
2440 A NULL macro means that we should continue the current macro
2441 expansion, in essence. That means that if we are currently in a
2442 macro expansion context, we'll make the new pfile->context refer to
2443 the current macro. */
2444 static void
2445 push_extended_tokens_context (cpp_reader *pfile,
2446 cpp_hashnode *macro,
2447 _cpp_buff *token_buff,
2448 location_t *virt_locs,
2449 const cpp_token **first,
2450 unsigned int count)
2452 cpp_context *context;
2453 macro_context *m;
2455 if (macro == NULL)
2456 macro = macro_of_context (pfile->context);
2458 context = next_context (pfile);
2459 context->tokens_kind = TOKENS_KIND_EXTENDED;
2460 context->buff = token_buff;
2462 m = XNEW (macro_context);
2463 m->macro_node = macro;
2464 m->virt_locs = virt_locs;
2465 m->cur_virt_loc = virt_locs;
2466 context->c.mc = m;
2467 FIRST (context).ptoken = first;
2468 LAST (context).ptoken = first + count;
2471 /* Push a traditional macro's replacement text. */
2472 void
2473 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
2474 const uchar *start, size_t len)
2476 cpp_context *context = next_context (pfile);
2478 context->tokens_kind = TOKENS_KIND_DIRECT;
2479 context->c.macro = macro;
2480 context->buff = NULL;
2481 CUR (context) = start;
2482 RLIMIT (context) = start + len;
2483 macro->flags |= NODE_DISABLED;
2486 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
2487 for the purpose of storing them on a cpp_context. If VIRT_LOCS is
2488 non-null (which means that -ftrack-macro-expansion is on),
2489 *VIRT_LOCS is set to a newly allocated buffer that is supposed to
2490 hold the virtual locations of the tokens resulting from macro
2491 expansion. */
2492 static _cpp_buff*
2493 tokens_buff_new (cpp_reader *pfile, size_t len,
2494 location_t **virt_locs)
2496 size_t tokens_size = len * sizeof (cpp_token *);
2497 size_t locs_size = len * sizeof (location_t);
2499 if (virt_locs != NULL)
2500 *virt_locs = XNEWVEC (location_t, locs_size);
2501 return _cpp_get_buff (pfile, tokens_size);
2504 /* Returns the number of tokens contained in a token buffer. The
2505 buffer holds a set of cpp_token*. */
2506 static size_t
2507 tokens_buff_count (_cpp_buff *buff)
2509 return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
2512 /* Return a pointer to the last token contained in the token buffer
2513 BUFF. */
2514 static const cpp_token **
2515 tokens_buff_last_token_ptr (_cpp_buff *buff)
2517 if (BUFF_FRONT (buff) == buff->base)
2518 return NULL;
2519 return &((const cpp_token **) BUFF_FRONT (buff))[-1];
2522 /* Remove the last token contained in the token buffer TOKENS_BUFF.
2523 If VIRT_LOCS_BUFF is non-NULL, it should point at the buffer
2524 containing the virtual locations of the tokens in TOKENS_BUFF; in
2525 which case the function updates that buffer as well. */
2526 static inline void
2527 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
2530 if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
2531 BUFF_FRONT (tokens_buff) =
2532 (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
2535 /* Insert a token into the token buffer at the position pointed to by
2536 DEST. Note that the buffer is not enlarged so the previous token
2537 that was at *DEST is overwritten. VIRT_LOC_DEST, if non-null,
2538 means -ftrack-macro-expansion is effect; it then points to where to
2539 insert the virtual location of TOKEN. TOKEN is the token to
2540 insert. VIRT_LOC is the virtual location of the token, i.e, the
2541 location possibly encoding its locus across macro expansion. If
2542 TOKEN is an argument of a function-like macro (inside a macro
2543 replacement list), PARM_DEF_LOC is the spelling location of the
2544 macro parameter that TOKEN is replacing, in the replacement list of
2545 the macro. If TOKEN is not an argument of a function-like macro or
2546 if it doesn't come from a macro expansion, then VIRT_LOC can just
2547 be set to the same value as PARM_DEF_LOC. If MAP is non null, it
2548 means TOKEN comes from a macro expansion and MAP is the macro map
2549 associated to the macro. MACRO_TOKEN_INDEX points to the index of
2550 the token in the macro map; it is not considered if MAP is NULL.
2552 Upon successful completion this function returns the a pointer to
2553 the position of the token coming right after the insertion
2554 point. */
2555 static inline const cpp_token **
2556 tokens_buff_put_token_to (const cpp_token **dest,
2557 location_t *virt_loc_dest,
2558 const cpp_token *token,
2559 location_t virt_loc,
2560 location_t parm_def_loc,
2561 const line_map_macro *map,
2562 unsigned int macro_token_index)
2564 location_t macro_loc = virt_loc;
2565 const cpp_token **result;
2567 if (virt_loc_dest)
2569 /* -ftrack-macro-expansion is on. */
2570 if (map)
2571 macro_loc = linemap_add_macro_token (map, macro_token_index,
2572 virt_loc, parm_def_loc);
2573 *virt_loc_dest = macro_loc;
2575 *dest = token;
2576 result = &dest[1];
2578 return result;
2581 /* Adds a token at the end of the tokens contained in BUFFER. Note
2582 that this function doesn't enlarge BUFFER when the number of tokens
2583 reaches BUFFER's size; it aborts in that situation.
2585 TOKEN is the token to append. VIRT_LOC is the virtual location of
2586 the token, i.e, the location possibly encoding its locus across
2587 macro expansion. If TOKEN is an argument of a function-like macro
2588 (inside a macro replacement list), PARM_DEF_LOC is the location of
2589 the macro parameter that TOKEN is replacing. If TOKEN doesn't come
2590 from a macro expansion, then VIRT_LOC can just be set to the same
2591 value as PARM_DEF_LOC. If MAP is non null, it means TOKEN comes
2592 from a macro expansion and MAP is the macro map associated to the
2593 macro. MACRO_TOKEN_INDEX points to the index of the token in the
2594 macro map; It is not considered if MAP is NULL. If VIRT_LOCS is
2595 non-null, it means -ftrack-macro-expansion is on; in which case
2596 this function adds the virtual location DEF_LOC to the VIRT_LOCS
2597 array, at the same index as the one of TOKEN in BUFFER. Upon
2598 successful completion this function returns the a pointer to the
2599 position of the token coming right after the insertion point. */
2600 static const cpp_token **
2601 tokens_buff_add_token (_cpp_buff *buffer,
2602 location_t *virt_locs,
2603 const cpp_token *token,
2604 location_t virt_loc,
2605 location_t parm_def_loc,
2606 const line_map_macro *map,
2607 unsigned int macro_token_index)
2609 const cpp_token **result;
2610 location_t *virt_loc_dest = NULL;
2611 unsigned token_index =
2612 (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2614 /* Abort if we pass the end the buffer. */
2615 if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2616 abort ();
2618 if (virt_locs != NULL)
2619 virt_loc_dest = &virt_locs[token_index];
2621 result =
2622 tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2623 virt_loc_dest, token, virt_loc, parm_def_loc,
2624 map, macro_token_index);
2626 BUFF_FRONT (buffer) = (unsigned char *) result;
2627 return result;
2630 /* Allocate space for the function-like macro argument ARG to store
2631 the tokens resulting from the macro-expansion of the tokens that
2632 make up ARG itself. That space is allocated in ARG->expanded and
2633 needs to be freed using free. */
2634 static void
2635 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2637 gcc_checking_assert (arg->expanded == NULL
2638 && arg->expanded_virt_locs == NULL);
2640 arg->expanded = XNEWVEC (const cpp_token *, capacity);
2641 if (CPP_OPTION (pfile, track_macro_expansion))
2642 arg->expanded_virt_locs = XNEWVEC (location_t, capacity);
2646 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2647 tokens. */
2648 static void
2649 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2650 size_t size, size_t *expanded_capacity)
2652 if (size <= *expanded_capacity)
2653 return;
2655 size *= 2;
2657 arg->expanded =
2658 XRESIZEVEC (const cpp_token *, arg->expanded, size);
2659 *expanded_capacity = size;
2661 if (CPP_OPTION (pfile, track_macro_expansion))
2663 if (arg->expanded_virt_locs == NULL)
2664 arg->expanded_virt_locs = XNEWVEC (location_t, size);
2665 else
2666 arg->expanded_virt_locs = XRESIZEVEC (location_t,
2667 arg->expanded_virt_locs,
2668 size);
2672 /* Expand an argument ARG before replacing parameters in a
2673 function-like macro. This works by pushing a context with the
2674 argument's tokens, and then expanding that into a temporary buffer
2675 as if it were a normal part of the token stream. collect_args()
2676 has terminated the argument's tokens with a CPP_EOF so that we know
2677 when we have fully expanded the argument. */
2678 static void
2679 expand_arg (cpp_reader *pfile, macro_arg *arg)
2681 size_t capacity;
2682 bool saved_warn_trad;
2683 bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2684 bool saved_ignore__Pragma;
2686 if (arg->count == 0
2687 || arg->expanded != NULL)
2688 return;
2690 /* Don't warn about funlike macros when pre-expanding. */
2691 saved_warn_trad = CPP_WTRADITIONAL (pfile);
2692 CPP_WTRADITIONAL (pfile) = 0;
2694 /* Loop, reading in the tokens of the argument. */
2695 capacity = 256;
2696 alloc_expanded_arg_mem (pfile, arg, capacity);
2698 if (track_macro_exp_p)
2699 push_extended_tokens_context (pfile, NULL, NULL,
2700 arg->virt_locs,
2701 arg->first,
2702 arg->count + 1);
2703 else
2704 push_ptoken_context (pfile, NULL, NULL,
2705 arg->first, arg->count + 1);
2707 saved_ignore__Pragma = pfile->state.ignore__Pragma;
2708 pfile->state.ignore__Pragma = 1;
2710 for (;;)
2712 const cpp_token *token;
2713 location_t location;
2715 ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2716 &capacity);
2718 token = cpp_get_token_1 (pfile, &location);
2720 if (token->type == CPP_EOF)
2721 break;
2723 set_arg_token (arg, token, location,
2724 arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2725 CPP_OPTION (pfile, track_macro_expansion));
2726 arg->expanded_count++;
2729 _cpp_pop_context (pfile);
2731 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2732 pfile->state.ignore__Pragma = saved_ignore__Pragma;
2735 /* Returns the macro associated to the current context if we are in
2736 the context a macro expansion, NULL otherwise. */
2737 static cpp_hashnode*
2738 macro_of_context (cpp_context *context)
2740 if (context == NULL)
2741 return NULL;
2743 return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2744 ? context->c.mc->macro_node
2745 : context->c.macro;
2748 /* Return TRUE iff we are expanding a macro or are about to start
2749 expanding one. If we are effectively expanding a macro, the
2750 function macro_of_context returns a pointer to the macro being
2751 expanded. */
2752 static bool
2753 in_macro_expansion_p (cpp_reader *pfile)
2755 if (pfile == NULL)
2756 return false;
2758 return (pfile->about_to_expand_macro_p
2759 || macro_of_context (pfile->context));
2762 /* Pop the current context off the stack, re-enabling the macro if the
2763 context represented a macro's replacement list. Initially the
2764 context structure was not freed so that we can re-use it later, but
2765 now we do free it to reduce peak memory consumption. */
2766 void
2767 _cpp_pop_context (cpp_reader *pfile)
2769 cpp_context *context = pfile->context;
2771 /* We should not be popping the base context. */
2772 gcc_assert (context != &pfile->base_context);
2774 if (context->c.macro)
2776 cpp_hashnode *macro;
2777 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2779 macro_context *mc = context->c.mc;
2780 macro = mc->macro_node;
2781 /* If context->buff is set, it means the life time of tokens
2782 is bound to the life time of this context; so we must
2783 free the tokens; that means we must free the virtual
2784 locations of these tokens too. */
2785 if (context->buff && mc->virt_locs)
2787 free (mc->virt_locs);
2788 mc->virt_locs = NULL;
2790 free (mc);
2791 context->c.mc = NULL;
2793 else
2794 macro = context->c.macro;
2796 /* Beware that MACRO can be NULL in cases like when we are
2797 called from expand_arg. In those cases, a dummy context with
2798 tokens is pushed just for the purpose of walking them using
2799 cpp_get_token_1. In that case, no 'macro' field is set into
2800 the dummy context. */
2801 if (macro != NULL
2802 /* Several contiguous macro expansion contexts can be
2803 associated to the same macro; that means it's the same
2804 macro expansion that spans across all these (sub)
2805 contexts. So we should re-enable an expansion-disabled
2806 macro only when we are sure we are really out of that
2807 macro expansion. */
2808 && macro_of_context (context->prev) != macro)
2809 macro->flags &= ~NODE_DISABLED;
2811 if (macro == pfile->top_most_macro_node && context->prev == NULL)
2812 /* We are popping the context of the top-most macro node. */
2813 pfile->top_most_macro_node = NULL;
2816 if (context->buff)
2818 /* Decrease memory peak consumption by freeing the memory used
2819 by the context. */
2820 _cpp_free_buff (context->buff);
2823 pfile->context = context->prev;
2824 /* decrease peak memory consumption by feeing the context. */
2825 pfile->context->next = NULL;
2826 free (context);
2829 /* Return TRUE if we reached the end of the set of tokens stored in
2830 CONTEXT, FALSE otherwise. */
2831 static inline bool
2832 reached_end_of_context (cpp_context *context)
2834 if (context->tokens_kind == TOKENS_KIND_DIRECT)
2835 return FIRST (context).token == LAST (context).token;
2836 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2837 || context->tokens_kind == TOKENS_KIND_EXTENDED)
2838 return FIRST (context).ptoken == LAST (context).ptoken;
2839 else
2840 abort ();
2843 /* Consume the next token contained in the current context of PFILE,
2844 and return it in *TOKEN. It's "full location" is returned in
2845 *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2846 means the location encoding the locus of the token across macro
2847 expansion; otherwise it's just is the "normal" location of the
2848 token which (*TOKEN)->src_loc. */
2849 static inline void
2850 consume_next_token_from_context (cpp_reader *pfile,
2851 const cpp_token ** token,
2852 location_t *location)
2854 cpp_context *c = pfile->context;
2856 if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2858 *token = FIRST (c).token;
2859 *location = (*token)->src_loc;
2860 FIRST (c).token++;
2862 else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2864 *token = *FIRST (c).ptoken;
2865 *location = (*token)->src_loc;
2866 FIRST (c).ptoken++;
2868 else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2870 macro_context *m = c->c.mc;
2871 *token = *FIRST (c).ptoken;
2872 if (m->virt_locs)
2874 *location = *m->cur_virt_loc;
2875 m->cur_virt_loc++;
2877 else
2878 *location = (*token)->src_loc;
2879 FIRST (c).ptoken++;
2881 else
2882 abort ();
2885 /* In the traditional mode of the preprocessor, if we are currently in
2886 a directive, the location of a token must be the location of the
2887 start of the directive line. This function returns the proper
2888 location if we are in the traditional mode, and just returns
2889 LOCATION otherwise. */
2891 static inline location_t
2892 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, location_t location)
2894 if (CPP_OPTION (pfile, traditional))
2896 if (pfile->state.in_directive)
2897 return pfile->directive_line;
2899 return location;
2902 /* Routine to get a token as well as its location.
2904 Macro expansions and directives are transparently handled,
2905 including entering included files. Thus tokens are post-macro
2906 expansion, and after any intervening directives. External callers
2907 see CPP_EOF only at EOF. Internal callers also see it when meeting
2908 a directive inside a macro call, when at the end of a directive and
2909 state.in_directive is still 1, and at the end of argument
2910 pre-expansion.
2912 LOC is an out parameter; *LOC is set to the location "as expected
2913 by the user". Please read the comment of
2914 cpp_get_token_with_location to learn more about the meaning of this
2915 location. */
2916 static const cpp_token*
2917 cpp_get_token_1 (cpp_reader *pfile, location_t *location)
2919 const cpp_token *result;
2920 /* This token is a virtual token that either encodes a location
2921 related to macro expansion or a spelling location. */
2922 location_t virt_loc = 0;
2923 /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2924 to functions that push macro contexts. So let's save it so that
2925 we can restore it when we are about to leave this routine. */
2926 bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2928 for (;;)
2930 cpp_hashnode *node;
2931 cpp_context *context = pfile->context;
2933 /* Context->prev == 0 <=> base context. */
2934 if (!context->prev)
2936 result = _cpp_lex_token (pfile);
2937 virt_loc = result->src_loc;
2939 else if (!reached_end_of_context (context))
2941 consume_next_token_from_context (pfile, &result,
2942 &virt_loc);
2943 if (result->flags & PASTE_LEFT)
2945 paste_all_tokens (pfile, result);
2946 if (pfile->state.in_directive)
2947 continue;
2948 result = padding_token (pfile, result);
2949 goto out;
2952 else
2954 if (pfile->context->c.macro)
2955 ++num_expanded_macros_counter;
2956 _cpp_pop_context (pfile);
2957 if (pfile->state.in_directive)
2958 continue;
2959 result = &pfile->avoid_paste;
2960 goto out;
2963 if (pfile->state.in_directive && result->type == CPP_COMMENT)
2964 continue;
2966 if (result->type != CPP_NAME)
2967 break;
2969 node = result->val.node.node;
2971 if (node->type == NT_VOID || (result->flags & NO_EXPAND))
2972 break;
2974 if (!(node->flags & NODE_USED)
2975 && node->type == NT_USER_MACRO
2976 && !node->value.macro
2977 && !cpp_get_deferred_macro (pfile, node, result->src_loc))
2978 break;
2980 if (!(node->flags & NODE_DISABLED))
2982 int ret = 0;
2983 /* If not in a macro context, and we're going to start an
2984 expansion, record the location and the top level macro
2985 about to be expanded. */
2986 if (!in_macro_expansion_p (pfile))
2988 pfile->invocation_location = result->src_loc;
2989 pfile->top_most_macro_node = node;
2991 if (pfile->state.prevent_expansion)
2992 break;
2994 /* Conditional macros require that a predicate be evaluated
2995 first. */
2996 if ((node->flags & NODE_CONDITIONAL) != 0)
2998 if (pfile->cb.macro_to_expand)
3000 bool whitespace_after;
3001 const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
3003 whitespace_after = (peek_tok->type == CPP_PADDING
3004 || (peek_tok->flags & PREV_WHITE));
3005 node = pfile->cb.macro_to_expand (pfile, result);
3006 if (node)
3007 ret = enter_macro_context (pfile, node, result, virt_loc);
3008 else if (whitespace_after)
3010 /* If macro_to_expand hook returned NULL and it
3011 ate some tokens, see if we don't need to add
3012 a padding token in between this and the
3013 next token. */
3014 peek_tok = cpp_peek_token (pfile, 0);
3015 if (peek_tok->type != CPP_PADDING
3016 && (peek_tok->flags & PREV_WHITE) == 0)
3017 _cpp_push_token_context (pfile, NULL,
3018 padding_token (pfile,
3019 peek_tok), 1);
3023 else
3024 ret = enter_macro_context (pfile, node, result, virt_loc);
3025 if (ret)
3027 if (pfile->state.in_directive || ret == 2)
3028 continue;
3029 result = padding_token (pfile, result);
3030 goto out;
3033 else
3035 /* Flag this token as always unexpandable. FIXME: move this
3036 to collect_args()?. */
3037 cpp_token *t = _cpp_temp_token (pfile);
3038 t->type = result->type;
3039 t->flags = result->flags | NO_EXPAND;
3040 t->val = result->val;
3041 result = t;
3044 break;
3047 out:
3048 if (location != NULL)
3050 if (virt_loc == 0)
3051 virt_loc = result->src_loc;
3052 *location = virt_loc;
3054 if (!CPP_OPTION (pfile, track_macro_expansion)
3055 && macro_of_context (pfile->context) != NULL)
3056 /* We are in a macro expansion context, are not tracking
3057 virtual location, but were asked to report the location
3058 of the expansion point of the macro being expanded. */
3059 *location = pfile->invocation_location;
3061 *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
3064 pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
3066 if (pfile->state.directive_file_token
3067 && !pfile->state.parsing_args
3068 && !(result->type == CPP_PADDING || result->type == CPP_COMMENT)
3069 && !(15 & --pfile->state.directive_file_token))
3071 /* Do header-name frobbery. Concatenate < ... > as approprate.
3072 Do header search if needed, and finally drop the outer <> or
3073 "". */
3074 pfile->state.angled_headers = false;
3076 /* Do angle-header reconstitution. Then do include searching.
3077 We'll always end up with a ""-quoted header-name in that
3078 case. If searching finds nothing, we emit a diagnostic and
3079 an empty string. */
3080 size_t len = 0;
3081 char *fname = NULL;
3083 cpp_token *tmp = _cpp_temp_token (pfile);
3084 *tmp = *result;
3086 tmp->type = CPP_HEADER_NAME;
3087 bool need_search = !pfile->state.directive_file_token;
3088 pfile->state.directive_file_token = 0;
3090 bool angle = result->type != CPP_STRING;
3091 if (result->type == CPP_HEADER_NAME
3092 || (result->type == CPP_STRING && result->val.str.text[0] != 'R'))
3094 len = result->val.str.len - 2;
3095 fname = XNEWVEC (char, len + 1);
3096 memcpy (fname, result->val.str.text + 1, len);
3097 fname[len] = 0;
3099 else if (result->type == CPP_LESS)
3100 fname = _cpp_bracket_include (pfile);
3102 if (fname)
3104 /* We have a header-name. Look it up. This will emit an
3105 unfound diagnostic. Canonicalize the found name. */
3106 const char *found = fname;
3108 if (need_search)
3110 found = _cpp_find_header_unit (pfile, fname, angle, tmp->src_loc);
3111 if (!found)
3112 found = "";
3113 len = strlen (found);
3115 /* Force a leading './' if it's not absolute. */
3116 bool dotme = (found[0] == '.' ? !IS_DIR_SEPARATOR (found[1])
3117 : found[0] && !IS_ABSOLUTE_PATH (found));
3119 if (BUFF_ROOM (pfile->u_buff) < len + 1 + dotme * 2)
3120 _cpp_extend_buff (pfile, &pfile->u_buff, len + 1 + dotme * 2);
3121 unsigned char *buf = BUFF_FRONT (pfile->u_buff);
3122 size_t pos = 0;
3124 if (dotme)
3126 buf[pos++] = '.';
3127 /* Apparently '/' is unconditional. */
3128 buf[pos++] = '/';
3130 memcpy (&buf[pos], found, len);
3131 pos += len;
3132 buf[pos] = 0;
3134 tmp->val.str.len = pos;
3135 tmp->val.str.text = buf;
3137 tmp->type = CPP_HEADER_NAME;
3138 XDELETEVEC (fname);
3140 result = tmp;
3144 return result;
3147 /* External routine to get a token. Also used nearly everywhere
3148 internally, except for places where we know we can safely call
3149 _cpp_lex_token directly, such as lexing a directive name.
3151 Macro expansions and directives are transparently handled,
3152 including entering included files. Thus tokens are post-macro
3153 expansion, and after any intervening directives. External callers
3154 see CPP_EOF only at EOF. Internal callers also see it when meeting
3155 a directive inside a macro call, when at the end of a directive and
3156 state.in_directive is still 1, and at the end of argument
3157 pre-expansion. */
3158 const cpp_token *
3159 cpp_get_token (cpp_reader *pfile)
3161 return cpp_get_token_1 (pfile, NULL);
3164 /* Like cpp_get_token, but also returns a virtual token location
3165 separate from the spelling location carried by the returned token.
3167 LOC is an out parameter; *LOC is set to the location "as expected
3168 by the user". This matters when a token results from macro
3169 expansion; in that case the token's spelling location indicates the
3170 locus of the token in the definition of the macro but *LOC
3171 virtually encodes all the other meaningful locuses associated to
3172 the token.
3174 What? virtual location? Yes, virtual location.
3176 If the token results from macro expansion and if macro expansion
3177 location tracking is enabled its virtual location encodes (at the
3178 same time):
3180 - the spelling location of the token
3182 - the locus of the macro expansion point
3184 - the locus of the point where the token got instantiated as part
3185 of the macro expansion process.
3187 You have to use the linemap API to get the locus you are interested
3188 in from a given virtual location.
3190 Note however that virtual locations are not necessarily ordered for
3191 relations '<' and '>'. One must use the function
3192 linemap_location_before_p instead of using the relational operator
3193 '<'.
3195 If macro expansion tracking is off and if the token results from
3196 macro expansion the virtual location is the expansion point of the
3197 macro that got expanded.
3199 When the token doesn't result from macro expansion, the virtual
3200 location is just the same thing as its spelling location. */
3202 const cpp_token *
3203 cpp_get_token_with_location (cpp_reader *pfile, location_t *loc)
3205 return cpp_get_token_1 (pfile, loc);
3208 /* Returns true if we're expanding an object-like macro that was
3209 defined in a system header. Just checks the macro at the top of
3210 the stack. Used for diagnostic suppression.
3211 Also return true for builtin macros. */
3213 cpp_sys_macro_p (cpp_reader *pfile)
3215 cpp_hashnode *node = NULL;
3217 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
3218 node = pfile->context->c.mc->macro_node;
3219 else
3220 node = pfile->context->c.macro;
3222 if (!node)
3223 return false;
3224 if (cpp_builtin_macro_p (node))
3225 return true;
3226 return node->value.macro && node->value.macro->syshdr;
3229 /* Read each token in, until end of the current file. Directives are
3230 transparently processed. */
3231 void
3232 cpp_scan_nooutput (cpp_reader *pfile)
3234 /* Request a CPP_EOF token at the end of this file, rather than
3235 transparently continuing with the including file. */
3236 pfile->buffer->return_at_eof = true;
3238 pfile->state.discarding_output++;
3239 pfile->state.prevent_expansion++;
3241 if (CPP_OPTION (pfile, traditional))
3242 while (_cpp_read_logical_line_trad (pfile))
3244 else
3245 while (cpp_get_token (pfile)->type != CPP_EOF)
3248 pfile->state.discarding_output--;
3249 pfile->state.prevent_expansion--;
3252 /* Step back one or more tokens obtained from the lexer. */
3253 void
3254 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
3256 pfile->lookaheads += count;
3257 while (count--)
3259 pfile->cur_token--;
3260 if (pfile->cur_token == pfile->cur_run->base
3261 /* Possible with -fpreprocessed and no leading #line. */
3262 && pfile->cur_run->prev != NULL)
3264 pfile->cur_run = pfile->cur_run->prev;
3265 pfile->cur_token = pfile->cur_run->limit;
3270 /* Step back one (or more) tokens. Can only step back more than 1 if
3271 they are from the lexer, and not from macro expansion. */
3272 void
3273 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
3275 if (pfile->context->prev == NULL)
3276 _cpp_backup_tokens_direct (pfile, count);
3277 else
3279 if (count != 1)
3280 abort ();
3281 if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
3282 FIRST (pfile->context).token--;
3283 else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
3284 FIRST (pfile->context).ptoken--;
3285 else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
3287 FIRST (pfile->context).ptoken--;
3288 if (pfile->context->c.macro)
3290 macro_context *m = pfile->context->c.mc;
3291 m->cur_virt_loc--;
3292 gcc_checking_assert (m->cur_virt_loc >= m->virt_locs);
3294 else
3295 abort ();
3297 else
3298 abort ();
3302 /* #define directive parsing and handling. */
3304 /* Returns true if a macro redefinition warning is required. */
3305 static bool
3306 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
3307 const cpp_macro *macro2)
3309 /* Some redefinitions need to be warned about regardless. */
3310 if (node->flags & NODE_WARN)
3311 return true;
3313 /* Suppress warnings for builtins that lack the NODE_WARN flag,
3314 unless Wbuiltin-macro-redefined. */
3315 if (cpp_builtin_macro_p (node))
3316 return CPP_OPTION (pfile, warn_builtin_macro_redefined);
3318 /* Redefinitions of conditional (context-sensitive) macros, on
3319 the other hand, must be allowed silently. */
3320 if (node->flags & NODE_CONDITIONAL)
3321 return false;
3323 if (cpp_macro *macro1 = get_deferred_or_lazy_macro (pfile, node, macro2->line))
3324 return cpp_compare_macros (macro1, macro2);
3325 return false;
3328 /* Return TRUE if MACRO1 and MACRO2 differ. */
3330 bool
3331 cpp_compare_macros (const cpp_macro *macro1, const cpp_macro *macro2)
3333 /* Redefinition of a macro is allowed if and only if the old and new
3334 definitions are the same. (6.10.3 paragraph 2). */
3336 /* Don't check count here as it can be different in valid
3337 traditional redefinitions with just whitespace differences. */
3338 if (macro1->paramc != macro2->paramc
3339 || macro1->fun_like != macro2->fun_like
3340 || macro1->variadic != macro2->variadic)
3341 return true;
3343 /* Check parameter spellings. */
3344 for (unsigned i = macro1->paramc; i--; )
3345 if (macro1->parm.params[i] != macro2->parm.params[i])
3346 return true;
3348 /* Check the replacement text or tokens. */
3349 if (macro1->kind == cmk_traditional)
3350 return _cpp_expansions_different_trad (macro1, macro2);
3352 if (macro1->count != macro2->count)
3353 return true;
3355 for (unsigned i= macro1->count; i--; )
3356 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
3357 return true;
3359 return false;
3362 /* Free the definition of hashnode H. */
3363 void
3364 _cpp_free_definition (cpp_hashnode *h)
3366 /* Macros and assertions no longer have anything to free. */
3367 h->type = NT_VOID;
3368 h->value.answers = NULL;
3369 h->flags &= ~(NODE_DISABLED | NODE_USED);
3372 /* Save parameter NODE (spelling SPELLING) to the parameter list of
3373 macro MACRO. Returns true on success, false on failure. */
3374 bool
3375 _cpp_save_parameter (cpp_reader *pfile, unsigned n, cpp_hashnode *node,
3376 cpp_hashnode *spelling)
3378 /* Constraint 6.10.3.6 - duplicate parameter names. */
3379 if (node->type == NT_MACRO_ARG)
3381 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
3382 NODE_NAME (node));
3383 return false;
3386 unsigned len = (n + 1) * sizeof (struct macro_arg_saved_data);
3387 if (len > pfile->macro_buffer_len)
3389 pfile->macro_buffer
3390 = XRESIZEVEC (unsigned char, pfile->macro_buffer, len);
3391 pfile->macro_buffer_len = len;
3394 macro_arg_saved_data *saved = (macro_arg_saved_data *)pfile->macro_buffer;
3395 saved[n].canonical_node = node;
3396 saved[n].value = node->value;
3397 saved[n].type = node->type;
3399 void *base = _cpp_reserve_room (pfile, n * sizeof (cpp_hashnode *),
3400 sizeof (cpp_hashnode *));
3401 ((cpp_hashnode **)base)[n] = spelling;
3403 /* Morph into a macro arg. */
3404 node->type = NT_MACRO_ARG;
3405 /* Index is 1 based. */
3406 node->value.arg_index = n + 1;
3408 return true;
3411 /* Restore the parameters to their previous state. */
3412 void
3413 _cpp_unsave_parameters (cpp_reader *pfile, unsigned n)
3415 /* Clear the fast argument lookup indices. */
3416 while (n--)
3418 struct macro_arg_saved_data *save =
3419 &((struct macro_arg_saved_data *) pfile->macro_buffer)[n];
3421 struct cpp_hashnode *node = save->canonical_node;
3422 node->type = save->type;
3423 node->value = save->value;
3427 /* Check the syntax of the parameters in a MACRO definition. Return
3428 false on failure. Set *N_PTR and *VARADIC_PTR as appropriate.
3429 '(' ')'
3430 '(' parm-list ',' last-parm ')'
3431 '(' last-parm ')'
3432 parm-list: name
3433 | parm-list, name
3434 last-parm: name
3435 | name '...'
3436 | '...'
3439 static bool
3440 parse_params (cpp_reader *pfile, unsigned *n_ptr, bool *variadic_ptr)
3442 unsigned nparms = 0;
3443 bool ok = false;
3445 for (bool prev_ident = false;;)
3447 const cpp_token *token = _cpp_lex_token (pfile);
3449 switch (token->type)
3451 case CPP_COMMENT:
3452 /* Allow/ignore comments in parameter lists if we are
3453 preserving comments in macro expansions. */
3454 if (!CPP_OPTION (pfile, discard_comments_in_macro_exp))
3455 break;
3457 /* FALLTHRU */
3458 default:
3459 bad:
3461 const char *const msgs[5] =
3463 N_("expected parameter name, found \"%s\""),
3464 N_("expected ',' or ')', found \"%s\""),
3465 N_("expected parameter name before end of line"),
3466 N_("expected ')' before end of line"),
3467 N_("expected ')' after \"...\"")
3469 unsigned ix = prev_ident;
3470 const unsigned char *as_text = NULL;
3471 if (*variadic_ptr)
3472 ix = 4;
3473 else if (token->type == CPP_EOF)
3474 ix += 2;
3475 else
3476 as_text = cpp_token_as_text (pfile, token);
3477 cpp_error (pfile, CPP_DL_ERROR, msgs[ix], as_text);
3479 goto out;
3481 case CPP_NAME:
3482 if (prev_ident || *variadic_ptr)
3483 goto bad;
3484 prev_ident = true;
3486 if (!_cpp_save_parameter (pfile, nparms, token->val.node.node,
3487 token->val.node.spelling))
3488 goto out;
3489 nparms++;
3490 break;
3492 case CPP_CLOSE_PAREN:
3493 if (prev_ident || !nparms || *variadic_ptr)
3495 ok = true;
3496 goto out;
3499 /* FALLTHRU */
3500 case CPP_COMMA:
3501 if (!prev_ident || *variadic_ptr)
3502 goto bad;
3503 prev_ident = false;
3504 break;
3506 case CPP_ELLIPSIS:
3507 if (*variadic_ptr)
3508 goto bad;
3509 *variadic_ptr = true;
3510 if (!prev_ident)
3512 /* An ISO bare ellipsis. */
3513 _cpp_save_parameter (pfile, nparms,
3514 pfile->spec_nodes.n__VA_ARGS__,
3515 pfile->spec_nodes.n__VA_ARGS__);
3516 nparms++;
3517 pfile->state.va_args_ok = 1;
3518 if (! CPP_OPTION (pfile, c99)
3519 && CPP_OPTION (pfile, cpp_pedantic)
3520 && CPP_OPTION (pfile, warn_variadic_macros))
3521 cpp_pedwarning
3522 (pfile, CPP_W_VARIADIC_MACROS,
3523 CPP_OPTION (pfile, cplusplus)
3524 ? N_("anonymous variadic macros were introduced in C++11")
3525 : N_("anonymous variadic macros were introduced in C99"));
3526 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
3527 && ! CPP_OPTION (pfile, cplusplus))
3528 cpp_error (pfile, CPP_DL_WARNING,
3529 "anonymous variadic macros were introduced in C99");
3531 else if (CPP_OPTION (pfile, cpp_pedantic)
3532 && CPP_OPTION (pfile, warn_variadic_macros))
3533 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
3534 CPP_OPTION (pfile, cplusplus)
3535 ? N_("ISO C++ does not permit named variadic macros")
3536 : N_("ISO C does not permit named variadic macros"));
3537 break;
3541 out:
3542 *n_ptr = nparms;
3544 return ok;
3547 /* Lex a token from the expansion of MACRO, but mark parameters as we
3548 find them and warn of traditional stringification. */
3549 static cpp_macro *
3550 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
3552 macro = (cpp_macro *)_cpp_reserve_room (pfile,
3553 sizeof (cpp_macro) - sizeof (cpp_token)
3554 + macro->count * sizeof (cpp_token),
3555 sizeof (cpp_token));
3556 cpp_token *saved_cur_token = pfile->cur_token;
3557 pfile->cur_token = &macro->exp.tokens[macro->count];
3558 cpp_token *token = _cpp_lex_direct (pfile);
3559 pfile->cur_token = saved_cur_token;
3561 /* Is this a parameter? */
3562 if (token->type == CPP_NAME && token->val.node.node->type == NT_MACRO_ARG)
3564 /* Morph into a parameter reference. */
3565 cpp_hashnode *spelling = token->val.node.spelling;
3566 token->type = CPP_MACRO_ARG;
3567 token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
3568 token->val.macro_arg.spelling = spelling;
3570 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
3571 && (token->type == CPP_STRING || token->type == CPP_CHAR))
3572 check_trad_stringification (pfile, macro, &token->val.str);
3574 return macro;
3577 static cpp_macro *
3578 create_iso_definition (cpp_reader *pfile)
3580 bool following_paste_op = false;
3581 const char *paste_op_error_msg =
3582 N_("'##' cannot appear at either end of a macro expansion");
3583 unsigned int num_extra_tokens = 0;
3584 unsigned nparms = 0;
3585 cpp_hashnode **params = NULL;
3586 bool variadic = false;
3587 bool ok = false;
3588 cpp_macro *macro = NULL;
3590 /* Look at the first token, to see if this is a function-like
3591 macro. */
3592 cpp_token first;
3593 cpp_token *saved_cur_token = pfile->cur_token;
3594 pfile->cur_token = &first;
3595 cpp_token *token = _cpp_lex_direct (pfile);
3596 pfile->cur_token = saved_cur_token;
3598 if (token->flags & PREV_WHITE)
3599 /* Preceeded by space, must be part of expansion. */;
3600 else if (token->type == CPP_OPEN_PAREN)
3602 /* An open-paren, get a parameter list. */
3603 if (!parse_params (pfile, &nparms, &variadic))
3604 goto out;
3606 params = (cpp_hashnode **)_cpp_commit_buff
3607 (pfile, sizeof (cpp_hashnode *) * nparms);
3608 token = NULL;
3610 else if (token->type != CPP_EOF
3611 && !(token->type == CPP_COMMENT
3612 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp)))
3614 /* While ISO C99 requires whitespace before replacement text
3615 in a macro definition, ISO C90 with TC1 allows characters
3616 from the basic source character set there. */
3617 if (CPP_OPTION (pfile, c99))
3618 cpp_error (pfile, CPP_DL_PEDWARN,
3619 CPP_OPTION (pfile, cplusplus)
3620 ? N_("ISO C++11 requires whitespace after the macro name")
3621 : N_("ISO C99 requires whitespace after the macro name"));
3622 else
3624 enum cpp_diagnostic_level warntype = CPP_DL_WARNING;
3625 switch (token->type)
3627 case CPP_ATSIGN:
3628 case CPP_AT_NAME:
3629 case CPP_OBJC_STRING:
3630 /* '@' is not in basic character set. */
3631 warntype = CPP_DL_PEDWARN;
3632 break;
3633 case CPP_OTHER:
3634 /* Basic character set sans letters, digits and _. */
3635 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
3636 token->val.str.text[0]) == NULL)
3637 warntype = CPP_DL_PEDWARN;
3638 break;
3639 default:
3640 /* All other tokens start with a character from basic
3641 character set. */
3642 break;
3644 cpp_error (pfile, warntype,
3645 "missing whitespace after the macro name");
3649 macro = _cpp_new_macro (pfile, cmk_macro,
3650 _cpp_reserve_room (pfile, 0, sizeof (cpp_macro)));
3652 if (!token)
3654 macro->variadic = variadic;
3655 macro->paramc = nparms;
3656 macro->parm.params = params;
3657 macro->fun_like = true;
3659 else
3661 /* Preserve the token we peeked, there is already a single slot for it. */
3662 macro->exp.tokens[0] = *token;
3663 token = &macro->exp.tokens[0];
3664 macro->count = 1;
3667 for (vaopt_state vaopt_tracker (pfile, macro->variadic, NULL);; token = NULL)
3669 if (!token)
3671 macro = lex_expansion_token (pfile, macro);
3672 token = &macro->exp.tokens[macro->count++];
3675 /* Check the stringifying # constraint 6.10.3.2.1 of
3676 function-like macros when lexing the subsequent token. */
3677 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
3679 if (token->type == CPP_MACRO_ARG
3680 || (macro->variadic
3681 && token->type == CPP_NAME
3682 && token->val.node.node == pfile->spec_nodes.n__VA_OPT__))
3684 if (token->flags & PREV_WHITE)
3685 token->flags |= SP_PREV_WHITE;
3686 if (token[-1].flags & DIGRAPH)
3687 token->flags |= SP_DIGRAPH;
3688 token->flags &= ~PREV_WHITE;
3689 token->flags |= STRINGIFY_ARG;
3690 token->flags |= token[-1].flags & PREV_WHITE;
3691 token[-1] = token[0];
3692 macro->count--;
3694 /* Let assembler get away with murder. */
3695 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
3697 cpp_error (pfile, CPP_DL_ERROR,
3698 "'#' is not followed by a macro parameter");
3699 goto out;
3703 if (token->type == CPP_EOF)
3705 /* Paste operator constraint 6.10.3.3.1:
3706 Token-paste ##, can appear in both object-like and
3707 function-like macros, but not at the end. */
3708 if (following_paste_op)
3710 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3711 goto out;
3713 if (!vaopt_tracker.completed ())
3714 goto out;
3715 break;
3718 /* Paste operator constraint 6.10.3.3.1. */
3719 if (token->type == CPP_PASTE)
3721 /* Token-paste ##, can appear in both object-like and
3722 function-like macros, but not at the beginning. */
3723 if (macro->count == 1)
3725 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3726 goto out;
3729 if (following_paste_op)
3731 /* Consecutive paste operators. This one will be moved
3732 to the end. */
3733 num_extra_tokens++;
3734 token->val.token_no = macro->count - 1;
3736 else
3738 /* Drop the paste operator. */
3739 --macro->count;
3740 token[-1].flags |= PASTE_LEFT;
3741 if (token->flags & DIGRAPH)
3742 token[-1].flags |= SP_DIGRAPH;
3743 if (token->flags & PREV_WHITE)
3744 token[-1].flags |= SP_PREV_WHITE;
3746 following_paste_op = true;
3748 else
3749 following_paste_op = false;
3751 if (vaopt_tracker.update (token) == vaopt_state::ERROR)
3752 goto out;
3755 /* We're committed to winning now. */
3756 ok = true;
3758 /* Don't count the CPP_EOF. */
3759 macro->count--;
3761 macro = (cpp_macro *)_cpp_commit_buff
3762 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
3763 + sizeof (cpp_token) * macro->count);
3765 /* Clear whitespace on first token. */
3766 if (macro->count)
3767 macro->exp.tokens[0].flags &= ~PREV_WHITE;
3769 if (num_extra_tokens)
3771 /* Place second and subsequent ## or %:%: tokens in sequences of
3772 consecutive such tokens at the end of the list to preserve
3773 information about where they appear, how they are spelt and
3774 whether they are preceded by whitespace without otherwise
3775 interfering with macro expansion. Remember, this is
3776 extremely rare, so efficiency is not a priority. */
3777 cpp_token *temp = (cpp_token *)_cpp_reserve_room
3778 (pfile, 0, num_extra_tokens * sizeof (cpp_token));
3779 unsigned extra_ix = 0, norm_ix = 0;
3780 cpp_token *exp = macro->exp.tokens;
3781 for (unsigned ix = 0; ix != macro->count; ix++)
3782 if (exp[ix].type == CPP_PASTE)
3783 temp[extra_ix++] = exp[ix];
3784 else
3785 exp[norm_ix++] = exp[ix];
3786 memcpy (&exp[norm_ix], temp, num_extra_tokens * sizeof (cpp_token));
3788 /* Record there are extra tokens. */
3789 macro->extra_tokens = 1;
3792 out:
3793 pfile->state.va_args_ok = 0;
3794 _cpp_unsave_parameters (pfile, nparms);
3796 return ok ? macro : NULL;
3799 cpp_macro *
3800 _cpp_new_macro (cpp_reader *pfile, cpp_macro_kind kind, void *placement)
3802 cpp_macro *macro = (cpp_macro *) placement;
3804 /* Zero init all the fields. This'll tell the compiler know all the
3805 following inits are writing a virgin object. */
3806 memset (macro, 0, offsetof (cpp_macro, exp));
3808 macro->line = pfile->directive_line;
3809 macro->parm.params = 0;
3810 macro->lazy = 0;
3811 macro->paramc = 0;
3812 macro->variadic = 0;
3813 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3814 macro->count = 0;
3815 macro->fun_like = 0;
3816 macro->imported_p = false;
3817 macro->extra_tokens = 0;
3818 /* To suppress some diagnostics. */
3819 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3821 macro->kind = kind;
3823 return macro;
3826 /* Parse a macro and save its expansion. Returns nonzero on success. */
3827 bool
3828 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node,
3829 location_t name_loc)
3831 cpp_macro *macro;
3833 if (CPP_OPTION (pfile, traditional))
3834 macro = _cpp_create_trad_definition (pfile);
3835 else
3836 macro = create_iso_definition (pfile);
3838 if (!macro)
3839 return false;
3841 /* _cpp_new_macro () has set macro->line to pfile->directive_line, which
3842 denotes the line containing the #define with no column information. If
3843 provided, change to name_loc, which will be the token src_loc for the
3844 macro name, including the location and range information. */
3845 if (name_loc)
3846 macro->line = name_loc;
3848 if (cpp_macro_p (node))
3850 if (CPP_OPTION (pfile, warn_unused_macros))
3851 _cpp_warn_if_unused_macro (pfile, node, NULL);
3853 if (warn_of_redefinition (pfile, node, macro))
3855 const enum cpp_warning_reason reason
3856 = (cpp_builtin_macro_p (node) && !(node->flags & NODE_WARN))
3857 ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3859 bool warned =
3860 cpp_pedwarning_with_line (pfile, reason,
3861 macro->line, 0,
3862 "\"%s\" redefined", NODE_NAME (node));
3864 if (warned && cpp_user_macro_p (node))
3865 cpp_error_with_line (pfile, CPP_DL_NOTE,
3866 node->value.macro->line, 0,
3867 "this is the location of the previous definition");
3869 _cpp_free_definition (node);
3872 /* Enter definition in hash table. */
3873 node->type = NT_USER_MACRO;
3874 node->value.macro = macro;
3875 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3876 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3877 /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3878 in the C standard, as something that one must use in C++.
3879 However DR#593 and C++11 indicate that they play no role in C++.
3880 We special-case them anyway. */
3881 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3882 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3883 node->flags |= NODE_WARN;
3885 /* If user defines one of the conditional macros, remove the
3886 conditional flag */
3887 node->flags &= ~NODE_CONDITIONAL;
3889 return true;
3892 extern void
3893 cpp_define_lazily (cpp_reader *pfile, cpp_hashnode *node, unsigned num)
3895 cpp_macro *macro = node->value.macro;
3897 gcc_checking_assert (pfile->cb.user_lazy_macro && macro && num < UCHAR_MAX);
3899 macro->lazy = num + 1;
3902 /* NODE is a deferred macro, resolve it, returning the definition
3903 (which may be NULL). */
3904 cpp_macro *
3905 cpp_get_deferred_macro (cpp_reader *pfile, cpp_hashnode *node,
3906 location_t loc)
3908 gcc_checking_assert (node->type == NT_USER_MACRO);
3910 node->value.macro = pfile->cb.user_deferred_macro (pfile, loc, node);
3912 if (!node->value.macro)
3913 node->type = NT_VOID;
3915 return node->value.macro;
3918 static cpp_macro *
3919 get_deferred_or_lazy_macro (cpp_reader *pfile, cpp_hashnode *node,
3920 location_t loc)
3922 cpp_macro *macro = node->value.macro;
3923 if (!macro)
3925 macro = cpp_get_deferred_macro (pfile, node, loc);
3926 gcc_checking_assert (!macro || !macro->lazy);
3928 else if (macro->lazy)
3930 pfile->cb.user_lazy_macro (pfile, macro, macro->lazy - 1);
3931 macro->lazy = 0;
3934 return macro;
3937 /* Notify the use of NODE in a macro-aware context (i.e. expanding it,
3938 or testing its existance). Also applies any lazy definition.
3939 Return FALSE if the macro isn't really there. */
3941 extern bool
3942 _cpp_notify_macro_use (cpp_reader *pfile, cpp_hashnode *node,
3943 location_t loc)
3945 node->flags |= NODE_USED;
3946 switch (node->type)
3948 case NT_USER_MACRO:
3949 if (!get_deferred_or_lazy_macro (pfile, node, loc))
3950 return false;
3951 /* FALLTHROUGH. */
3953 case NT_BUILTIN_MACRO:
3954 if (pfile->cb.used_define)
3955 pfile->cb.used_define (pfile, loc, node);
3956 break;
3958 case NT_VOID:
3959 if (pfile->cb.used_undef)
3960 pfile->cb.used_undef (pfile, loc, node);
3961 break;
3963 default:
3964 abort ();
3967 return true;
3970 /* Warn if a token in STRING matches one of a function-like MACRO's
3971 parameters. */
3972 static void
3973 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3974 const cpp_string *string)
3976 unsigned int i, len;
3977 const uchar *p, *q, *limit;
3979 /* Loop over the string. */
3980 limit = string->text + string->len - 1;
3981 for (p = string->text + 1; p < limit; p = q)
3983 /* Find the start of an identifier. */
3984 while (p < limit && !is_idstart (*p))
3985 p++;
3987 /* Find the end of the identifier. */
3988 q = p;
3989 while (q < limit && is_idchar (*q))
3990 q++;
3992 len = q - p;
3994 /* Loop over the function macro arguments to see if the
3995 identifier inside the string matches one of them. */
3996 for (i = 0; i < macro->paramc; i++)
3998 const cpp_hashnode *node = macro->parm.params[i];
4000 if (NODE_LEN (node) == len
4001 && !memcmp (p, NODE_NAME (node), len))
4003 cpp_warning (pfile, CPP_W_TRADITIONAL,
4004 "macro argument \"%s\" would be stringified in traditional C",
4005 NODE_NAME (node));
4006 break;
4012 /* Returns the name, arguments and expansion of a macro, in a format
4013 suitable to be read back in again, and therefore also for DWARF 2
4014 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
4015 Caller is expected to generate the "#define" bit if needed. The
4016 returned text is temporary, and automatically freed later. */
4017 const unsigned char *
4018 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
4020 gcc_checking_assert (cpp_user_macro_p (node));
4022 if (const cpp_macro *macro = get_deferred_or_lazy_macro (pfile, node, 0))
4023 return cpp_macro_definition (pfile, node, macro);
4024 return NULL;
4027 const unsigned char *
4028 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node,
4029 const cpp_macro *macro)
4031 unsigned int i, len;
4032 unsigned char *buffer;
4034 /* Calculate length. */
4035 len = NODE_LEN (node) * 10 + 2; /* ' ' and NUL. */
4036 if (macro->fun_like)
4038 len += 4; /* "()" plus possible final ".." of named
4039 varargs (we have + 1 below). */
4040 for (i = 0; i < macro->paramc; i++)
4041 len += NODE_LEN (macro->parm.params[i]) + 1; /* "," */
4044 /* This should match below where we fill in the buffer. */
4045 if (CPP_OPTION (pfile, traditional))
4046 len += _cpp_replacement_text_len (macro);
4047 else
4049 unsigned int count = macro_real_token_count (macro);
4050 for (i = 0; i < count; i++)
4052 const cpp_token *token = &macro->exp.tokens[i];
4054 if (token->type == CPP_MACRO_ARG)
4055 len += NODE_LEN (token->val.macro_arg.spelling);
4056 else
4057 len += cpp_token_len (token);
4059 if (token->flags & STRINGIFY_ARG)
4060 len++; /* "#" */
4061 if (token->flags & PASTE_LEFT)
4062 len += 3; /* " ##" */
4063 if (token->flags & PREV_WHITE)
4064 len++; /* " " */
4068 if (len > pfile->macro_buffer_len)
4070 pfile->macro_buffer = XRESIZEVEC (unsigned char,
4071 pfile->macro_buffer, len);
4072 pfile->macro_buffer_len = len;
4075 /* Fill in the buffer. Start with the macro name. */
4076 buffer = pfile->macro_buffer;
4077 buffer = _cpp_spell_ident_ucns (buffer, node);
4079 /* Parameter names. */
4080 if (macro->fun_like)
4082 *buffer++ = '(';
4083 for (i = 0; i < macro->paramc; i++)
4085 cpp_hashnode *param = macro->parm.params[i];
4087 if (param != pfile->spec_nodes.n__VA_ARGS__)
4089 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
4090 buffer += NODE_LEN (param);
4093 if (i + 1 < macro->paramc)
4094 /* Don't emit a space after the comma here; we're trying
4095 to emit a Dwarf-friendly definition, and the Dwarf spec
4096 forbids spaces in the argument list. */
4097 *buffer++ = ',';
4098 else if (macro->variadic)
4099 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
4101 *buffer++ = ')';
4104 /* The Dwarf spec requires a space after the macro name, even if the
4105 definition is the empty string. */
4106 *buffer++ = ' ';
4108 if (CPP_OPTION (pfile, traditional))
4109 buffer = _cpp_copy_replacement_text (macro, buffer);
4110 else if (macro->count)
4111 /* Expansion tokens. */
4113 unsigned int count = macro_real_token_count (macro);
4114 for (i = 0; i < count; i++)
4116 const cpp_token *token = &macro->exp.tokens[i];
4118 if (token->flags & PREV_WHITE)
4119 *buffer++ = ' ';
4120 if (token->flags & STRINGIFY_ARG)
4121 *buffer++ = '#';
4123 if (token->type == CPP_MACRO_ARG)
4125 memcpy (buffer,
4126 NODE_NAME (token->val.macro_arg.spelling),
4127 NODE_LEN (token->val.macro_arg.spelling));
4128 buffer += NODE_LEN (token->val.macro_arg.spelling);
4130 else
4131 buffer = cpp_spell_token (pfile, token, buffer, true);
4133 if (token->flags & PASTE_LEFT)
4135 *buffer++ = ' ';
4136 *buffer++ = '#';
4137 *buffer++ = '#';
4138 /* Next has PREV_WHITE; see _cpp_create_definition. */
4143 *buffer = '\0';
4144 return pfile->macro_buffer;