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