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