* de.po: Update.
[official-gcc.git] / libcpp / macro.c
blob6d46027e4ea4a0e36ff0b98d18ee071917ddf7cf
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 if (CPP_OPTION (pfile, track_macro_expansion))
1113 unsigned int i, count = macro->count;
1114 const cpp_token *src = macro->exp.tokens;
1115 const struct line_map *map;
1116 source_location *virt_locs = NULL;
1117 _cpp_buff *macro_tokens =
1118 tokens_buff_new (pfile, count, &virt_locs);
1120 /* Create a macro map to record the locations of the
1121 tokens that are involved in the expansion. LOCATION
1122 is the location of the macro expansion point. */
1123 map = linemap_enter_macro (pfile->line_table,
1124 node, location, count);
1125 for (i = 0; i < count; ++i)
1127 tokens_buff_add_token (macro_tokens, virt_locs,
1128 src, src->src_loc,
1129 src->src_loc, map, i);
1130 ++src;
1132 push_extended_tokens_context (pfile, node,
1133 macro_tokens,
1134 virt_locs,
1135 (const cpp_token **)
1136 macro_tokens->base,
1137 count);
1138 num_macro_tokens_counter += count;
1140 else
1142 unsigned tokens_count = macro_real_token_count (macro);
1143 _cpp_push_token_context (pfile, node, macro->exp.tokens,
1144 tokens_count);
1145 num_macro_tokens_counter += tokens_count;
1149 if (pragma_buff)
1151 if (!pfile->state.in_directive)
1152 _cpp_push_token_context (pfile, NULL,
1153 padding_token (pfile, result), 1);
1156 unsigned tokens_count;
1157 _cpp_buff *tail = pragma_buff->next;
1158 pragma_buff->next = NULL;
1159 tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1160 - (const cpp_token **) pragma_buff->base);
1161 push_ptoken_context (pfile, NULL, pragma_buff,
1162 (const cpp_token **) pragma_buff->base,
1163 tokens_count);
1164 pragma_buff = tail;
1165 if (!CPP_OPTION (pfile, track_macro_expansion))
1166 num_macro_tokens_counter += tokens_count;
1169 while (pragma_buff != NULL);
1170 pfile->about_to_expand_macro_p = false;
1171 return 2;
1174 pfile->about_to_expand_macro_p = false;
1175 return 1;
1178 pfile->about_to_expand_macro_p = false;
1179 /* Handle built-in macros and the _Pragma operator. */
1180 return builtin_macro (pfile, node);
1183 /* De-allocate the memory used by BUFF which is an array of instances
1184 of macro_arg. NUM_ARGS is the number of instances of macro_arg
1185 present in BUFF. */
1186 static void
1187 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1189 macro_arg *macro_args;
1190 unsigned i;
1192 if (buff == NULL)
1193 return;
1195 macro_args = (macro_arg *) buff->base;
1197 /* Walk instances of macro_arg to free their expanded tokens as well
1198 as their macro_arg::virt_locs members. */
1199 for (i = 0; i < num_args; ++i)
1201 if (macro_args[i].expanded)
1203 free (macro_args[i].expanded);
1204 macro_args[i].expanded = NULL;
1206 if (macro_args[i].virt_locs)
1208 free (macro_args[i].virt_locs);
1209 macro_args[i].virt_locs = NULL;
1211 if (macro_args[i].expanded_virt_locs)
1213 free (macro_args[i].expanded_virt_locs);
1214 macro_args[i].expanded_virt_locs = NULL;
1217 _cpp_free_buff (buff);
1220 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1221 to set, LOCATION is its virtual location. "Virtual" location means
1222 the location that encodes loci across macro expansion. Otherwise
1223 it has to be TOKEN->SRC_LOC. KIND is the kind of tokens the
1224 argument ARG is supposed to contain. Note that ARG must be
1225 tailored so that it has enough room to contain INDEX + 1 numbers of
1226 tokens, at least. */
1227 static void
1228 set_arg_token (macro_arg *arg, const cpp_token *token,
1229 source_location location, size_t index,
1230 enum macro_arg_token_kind kind,
1231 bool track_macro_exp_p)
1233 const cpp_token **token_ptr;
1234 source_location *loc = NULL;
1236 token_ptr =
1237 arg_token_ptr_at (arg, index, kind,
1238 track_macro_exp_p ? &loc : NULL);
1239 *token_ptr = token;
1241 if (loc != NULL)
1243 #ifdef ENABLE_CHECKING
1244 if (kind == MACRO_ARG_TOKEN_STRINGIFIED
1245 || !track_macro_exp_p)
1246 /* We can't set the location of a stringified argument
1247 token and we can't set any location if we aren't tracking
1248 macro expansion locations. */
1249 abort ();
1250 #endif
1251 *loc = location;
1255 /* Get the pointer to the location of the argument token of the
1256 function-like macro argument ARG. This function must be called
1257 only when we -ftrack-macro-expansion is on. */
1258 static const source_location *
1259 get_arg_token_location (const macro_arg *arg,
1260 enum macro_arg_token_kind kind)
1262 const source_location *loc = NULL;
1263 const cpp_token **token_ptr =
1264 arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1266 if (token_ptr == NULL)
1267 return NULL;
1269 return loc;
1272 /* Return the pointer to the INDEXth token of the macro argument ARG.
1273 KIND specifies the kind of token the macro argument ARG contains.
1274 If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1275 of the virtual location of the returned token if the
1276 -ftrack-macro-expansion flag is on; otherwise, it's set to the
1277 spelling location of the returned token. */
1278 static const cpp_token **
1279 arg_token_ptr_at (const macro_arg *arg, size_t index,
1280 enum macro_arg_token_kind kind,
1281 source_location **virt_location)
1283 const cpp_token **tokens_ptr = NULL;
1285 switch (kind)
1287 case MACRO_ARG_TOKEN_NORMAL:
1288 tokens_ptr = arg->first;
1289 break;
1290 case MACRO_ARG_TOKEN_STRINGIFIED:
1291 tokens_ptr = (const cpp_token **) &arg->stringified;
1292 break;
1293 case MACRO_ARG_TOKEN_EXPANDED:
1294 tokens_ptr = arg->expanded;
1295 break;
1298 if (tokens_ptr == NULL)
1299 /* This can happen for e.g, an empty token argument to a
1300 funtion-like macro. */
1301 return tokens_ptr;
1303 if (virt_location)
1305 if (kind == MACRO_ARG_TOKEN_NORMAL)
1306 *virt_location = &arg->virt_locs[index];
1307 else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1308 *virt_location = &arg->expanded_virt_locs[index];
1309 else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1310 *virt_location =
1311 (source_location *) &tokens_ptr[index]->src_loc;
1313 return &tokens_ptr[index];
1316 /* Initialize an iterator so that it iterates over the tokens of a
1317 function-like macro argument. KIND is the kind of tokens we want
1318 ITER to iterate over. TOKEN_PTR points the first token ITER will
1319 iterate over. */
1320 static void
1321 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1322 bool track_macro_exp_p,
1323 enum macro_arg_token_kind kind,
1324 const macro_arg *arg,
1325 const cpp_token **token_ptr)
1327 iter->track_macro_exp_p = track_macro_exp_p;
1328 iter->kind = kind;
1329 iter->token_ptr = token_ptr;
1330 /* Unconditionally initialize this so that the compiler doesn't warn
1331 about iter->location_ptr being possibly uninitialized later after
1332 this code has been inlined somewhere. */
1333 iter->location_ptr = NULL;
1334 if (track_macro_exp_p)
1335 iter->location_ptr = get_arg_token_location (arg, kind);
1336 #ifdef ENABLE_CHECKING
1337 iter->num_forwards = 0;
1338 if (track_macro_exp_p
1339 && token_ptr != NULL
1340 && iter->location_ptr == NULL)
1341 abort ();
1342 #endif
1345 /* Move the iterator one token forward. Note that if IT was
1346 initialized on an argument that has a stringified token, moving it
1347 forward doesn't make sense as a stringified token is essentially one
1348 string. */
1349 static void
1350 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1352 switch (it->kind)
1354 case MACRO_ARG_TOKEN_NORMAL:
1355 case MACRO_ARG_TOKEN_EXPANDED:
1356 it->token_ptr++;
1357 if (it->track_macro_exp_p)
1358 it->location_ptr++;
1359 break;
1360 case MACRO_ARG_TOKEN_STRINGIFIED:
1361 #ifdef ENABLE_CHECKING
1362 if (it->num_forwards > 0)
1363 abort ();
1364 #endif
1365 break;
1368 #ifdef ENABLE_CHECKING
1369 it->num_forwards++;
1370 #endif
1373 /* Return the token pointed to by the iterator. */
1374 static const cpp_token *
1375 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1377 #ifdef ENABLE_CHECKING
1378 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1379 && it->num_forwards > 0)
1380 abort ();
1381 #endif
1382 if (it->token_ptr == NULL)
1383 return NULL;
1384 return *it->token_ptr;
1387 /* Return the location of the token pointed to by the iterator.*/
1388 static source_location
1389 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1391 #ifdef ENABLE_CHECKING
1392 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1393 && it->num_forwards > 0)
1394 abort ();
1395 #endif
1396 if (it->track_macro_exp_p)
1397 return *it->location_ptr;
1398 else
1399 return (*it->token_ptr)->src_loc;
1402 /* Return the index of a token [resulting from macro expansion] inside
1403 the total list of tokens resulting from a given macro
1404 expansion. The index can be different depending on whether if we
1405 want each tokens resulting from function-like macro arguments
1406 expansion to have a different location or not.
1408 E.g, consider this function-like macro:
1410 #define M(x) x - 3
1412 Then consider us "calling" it (and thus expanding it) like:
1414 M(1+4)
1416 It will be expanded into:
1418 1+4-3
1420 Let's consider the case of the token '4'.
1422 Its index can be 2 (it's the third token of the set of tokens
1423 resulting from the expansion) or it can be 0 if we consider that
1424 all tokens resulting from the expansion of the argument "1+2" have
1425 the same index, which is 0. In this later case, the index of token
1426 '-' would then be 1 and the index of token '3' would be 2.
1428 The later case is useful to use less memory e.g, for the case of
1429 the user using the option -ftrack-macro-expansion=1.
1431 ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1432 are interested in. CUR_REPLACEMENT_TOKEN is the token of the macro
1433 parameter (inside the macro replacement list) that corresponds to
1434 the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1437 If we refer to the example above, for the '4' argument token,
1438 ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1439 would be set to the token 'x', in the replacement list "x - 3" of
1440 macro M.
1442 This is a subroutine of replace_args. */
1443 inline static unsigned
1444 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1445 const cpp_token *cur_replacement_token,
1446 unsigned absolute_token_index)
1448 if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1449 return absolute_token_index;
1450 return cur_replacement_token - macro->exp.tokens;
1453 /* Replace the parameters in a function-like macro of NODE with the
1454 actual ARGS, and place the result in a newly pushed token context.
1455 Expand each argument before replacing, unless it is operated upon
1456 by the # or ## operators. EXPANSION_POINT_LOC is the location of
1457 the expansion point of the macro. E.g, the location of the
1458 function-like macro invocation. */
1459 static void
1460 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1461 macro_arg *args, source_location expansion_point_loc)
1463 unsigned int i, total;
1464 const cpp_token *src, *limit;
1465 const cpp_token **first = NULL;
1466 macro_arg *arg;
1467 _cpp_buff *buff = NULL;
1468 source_location *virt_locs = NULL;
1469 unsigned int exp_count;
1470 const struct line_map *map = NULL;
1471 int track_macro_exp;
1473 /* First, fully macro-expand arguments, calculating the number of
1474 tokens in the final expansion as we go. The ordering of the if
1475 statements below is subtle; we must handle stringification before
1476 pasting. */
1478 /* EXP_COUNT is the number of tokens in the macro replacement
1479 list. TOTAL is the number of tokens /after/ macro parameters
1480 have been replaced by their arguments. */
1481 exp_count = macro_real_token_count (macro);
1482 total = exp_count;
1483 limit = macro->exp.tokens + exp_count;
1485 for (src = macro->exp.tokens; src < limit; src++)
1486 if (src->type == CPP_MACRO_ARG)
1488 /* Leading and trailing padding tokens. */
1489 total += 2;
1490 /* Account for leading and padding tokens in exp_count too.
1491 This is going to be important later down this function,
1492 when we want to handle the case of (track_macro_exp <
1493 2). */
1494 exp_count += 2;
1496 /* We have an argument. If it is not being stringified or
1497 pasted it is macro-replaced before insertion. */
1498 arg = &args[src->val.macro_arg.arg_no - 1];
1500 if (src->flags & STRINGIFY_ARG)
1502 if (!arg->stringified)
1503 arg->stringified = stringify_arg (pfile, arg);
1505 else if ((src->flags & PASTE_LEFT)
1506 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1507 total += arg->count - 1;
1508 else
1510 if (!arg->expanded)
1511 expand_arg (pfile, arg);
1512 total += arg->expanded_count - 1;
1516 /* When the compiler is called with the -ftrack-macro-expansion
1517 flag, we need to keep track of the location of each token that
1518 results from macro expansion.
1520 A token resulting from macro expansion is not a new token. It is
1521 simply the same token as the token coming from the macro
1522 definition. The new things that are allocated are the buffer
1523 that holds the tokens resulting from macro expansion and a new
1524 location that records many things like the locus of the expansion
1525 point as well as the original locus inside the definition of the
1526 macro. This location is called a virtual location.
1528 So the buffer BUFF holds a set of cpp_token*, and the buffer
1529 VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1531 Both of these two buffers are going to be hung off of the macro
1532 context, when the latter is pushed. The memory allocated to
1533 store the tokens and their locations is going to be freed once
1534 the context of macro expansion is popped.
1536 As far as tokens are concerned, the memory overhead of
1537 -ftrack-macro-expansion is proportional to the number of
1538 macros that get expanded multiplied by sizeof (source_location).
1539 The good news is that extra memory gets freed when the macro
1540 context is freed, i.e shortly after the macro got expanded. */
1542 /* Is the -ftrack-macro-expansion flag in effect? */
1543 track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1545 /* Now allocate memory space for tokens and locations resulting from
1546 the macro expansion, copy the tokens and replace the arguments.
1547 This memory must be freed when the context of the macro MACRO is
1548 popped. */
1549 buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1551 first = (const cpp_token **) buff->base;
1553 /* Create a macro map to record the locations of the tokens that are
1554 involved in the expansion. Note that the expansion point is set
1555 to the location of the closing parenthesis. Otherwise, the
1556 subsequent map created for the first token that comes after the
1557 macro map might have a wrong line number. That would lead to
1558 tokens with wrong line numbers after the macro expansion. This
1559 adds up to the memory overhead of the -ftrack-macro-expansion
1560 flag; for every macro that is expanded, a "macro map" is
1561 created. */
1562 if (track_macro_exp)
1564 int num_macro_tokens = total;
1565 if (track_macro_exp < 2)
1566 /* Then the number of macro tokens won't take in account the
1567 fact that function-like macro arguments can expand to
1568 multiple tokens. This is to save memory at the expense of
1569 accuracy.
1571 Suppose we have #define SQARE(A) A * A
1573 And then we do SQARE(2+3)
1575 Then the tokens 2, +, 3, will have the same location,
1576 saying they come from the expansion of the argument A. */
1577 num_macro_tokens = exp_count;
1578 map = linemap_enter_macro (pfile->line_table, node,
1579 expansion_point_loc,
1580 num_macro_tokens);
1582 i = 0;
1583 for (src = macro->exp.tokens; src < limit; src++)
1585 unsigned int arg_tokens_count;
1586 macro_arg_token_iter from;
1587 const cpp_token **paste_flag = NULL;
1588 const cpp_token **tmp_token_ptr;
1590 if (src->type != CPP_MACRO_ARG)
1592 /* Allocate a virtual location for token SRC, and add that
1593 token and its virtual location into the buffers BUFF and
1594 VIRT_LOCS. */
1595 unsigned index = expanded_token_index (pfile, macro, src, i);
1596 tokens_buff_add_token (buff, virt_locs, src,
1597 src->src_loc, src->src_loc,
1598 map, index);
1599 i += 1;
1600 continue;
1603 paste_flag = 0;
1604 arg = &args[src->val.macro_arg.arg_no - 1];
1605 /* SRC is a macro parameter that we need to replace with its
1606 corresponding argument. So at some point we'll need to
1607 iterate over the tokens of the macro argument and copy them
1608 into the "place" now holding the correspondig macro
1609 parameter. We are going to use the iterator type
1610 macro_argo_token_iter to handle that iterating. The 'if'
1611 below is to initialize the iterator depending on the type of
1612 tokens the macro argument has. It also does some adjustment
1613 related to padding tokens and some pasting corner cases. */
1614 if (src->flags & STRINGIFY_ARG)
1616 arg_tokens_count = 1;
1617 macro_arg_token_iter_init (&from,
1618 CPP_OPTION (pfile,
1619 track_macro_expansion),
1620 MACRO_ARG_TOKEN_STRINGIFIED,
1621 arg, &arg->stringified);
1623 else if (src->flags & PASTE_LEFT)
1625 arg_tokens_count = arg->count;
1626 macro_arg_token_iter_init (&from,
1627 CPP_OPTION (pfile,
1628 track_macro_expansion),
1629 MACRO_ARG_TOKEN_NORMAL,
1630 arg, arg->first);
1632 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1634 int num_toks;
1635 arg_tokens_count = arg->count;
1636 macro_arg_token_iter_init (&from,
1637 CPP_OPTION (pfile,
1638 track_macro_expansion),
1639 MACRO_ARG_TOKEN_NORMAL,
1640 arg, arg->first);
1642 num_toks = tokens_buff_count (buff);
1644 if (num_toks != 0)
1646 /* So the current parameter token is pasted to the previous
1647 token in the replacement list. Let's look at what
1648 we have as previous and current arguments. */
1650 /* This is the previous argument's token ... */
1651 tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1653 if ((*tmp_token_ptr)->type == CPP_COMMA
1654 && macro->variadic
1655 && src->val.macro_arg.arg_no == macro->paramc)
1657 /* ... which is a comma; and the current parameter
1658 is the last parameter of a variadic function-like
1659 macro. If the argument to the current last
1660 parameter is NULL, then swallow the comma,
1661 otherwise drop the paste flag. */
1662 if (macro_arg_token_iter_get_token (&from) == NULL)
1663 tokens_buff_remove_last_token (buff);
1664 else
1665 paste_flag = tmp_token_ptr;
1667 /* Remove the paste flag if the RHS is a placemarker. */
1668 else if (arg_tokens_count == 0)
1669 paste_flag = tmp_token_ptr;
1672 else
1674 arg_tokens_count = arg->expanded_count;
1675 macro_arg_token_iter_init (&from,
1676 CPP_OPTION (pfile,
1677 track_macro_expansion),
1678 MACRO_ARG_TOKEN_EXPANDED,
1679 arg, arg->expanded);
1682 /* Padding on the left of an argument (unless RHS of ##). */
1683 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1684 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1686 const cpp_token *t = padding_token (pfile, src);
1687 unsigned index = expanded_token_index (pfile, macro, src, i);
1688 /* Allocate a virtual location for the padding token and
1689 append the token and its location to BUFF and
1690 VIRT_LOCS. */
1691 tokens_buff_add_token (buff, virt_locs, t,
1692 t->src_loc, t->src_loc,
1693 map, index);
1696 if (arg_tokens_count)
1698 /* So now we've got the number of tokens that make up the
1699 argument that is going to replace the current parameter
1700 in the macro's replacement list. */
1701 unsigned int j;
1702 for (j = 0; j < arg_tokens_count; ++j)
1704 /* So if track_macro_exp is < 2, the user wants to
1705 save extra memory while tracking macro expansion
1706 locations. So in that case here is what we do:
1708 Suppose we have #define SQARE(A) A * A
1710 And then we do SQARE(2+3)
1712 Then the tokens 2, +, 3, will have the same location,
1713 saying they come from the expansion of the argument
1716 So that means we are going to ignore the COUNT tokens
1717 resulting from the expansion of the current macro
1718 arugment. In other words all the ARG_TOKENS_COUNT tokens
1719 resulting from the expansion of the macro argument will
1720 have the index I. Normally, each of those token should
1721 have index I+J. */
1722 unsigned token_index = i;
1723 unsigned index;
1724 if (track_macro_exp > 1)
1725 token_index += j;
1727 index = expanded_token_index (pfile, macro, src, token_index);
1728 tokens_buff_add_token (buff, virt_locs,
1729 macro_arg_token_iter_get_token (&from),
1730 macro_arg_token_iter_get_location (&from),
1731 src->src_loc, map, index);
1732 macro_arg_token_iter_forward (&from);
1735 /* With a non-empty argument on the LHS of ##, the last
1736 token should be flagged PASTE_LEFT. */
1737 if (src->flags & PASTE_LEFT)
1738 paste_flag =
1739 (const cpp_token **) tokens_buff_last_token_ptr (buff);
1741 else if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1742 && ! CPP_OPTION (pfile, c99)
1743 && ! cpp_in_system_header (pfile))
1745 cpp_error (pfile, CPP_DL_PEDWARN,
1746 "invoking macro %s argument %d: "
1747 "empty macro arguments are undefined"
1748 " in ISO C90 and ISO C++98",
1749 NODE_NAME (node),
1750 src->val.macro_arg.arg_no);
1753 /* Avoid paste on RHS (even case count == 0). */
1754 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
1756 const cpp_token *t = &pfile->avoid_paste;
1757 tokens_buff_add_token (buff, virt_locs,
1758 t, t->src_loc, t->src_loc,
1759 NULL, 0);
1762 /* Add a new paste flag, or remove an unwanted one. */
1763 if (paste_flag)
1765 cpp_token *token = _cpp_temp_token (pfile);
1766 token->type = (*paste_flag)->type;
1767 token->val = (*paste_flag)->val;
1768 if (src->flags & PASTE_LEFT)
1769 token->flags = (*paste_flag)->flags | PASTE_LEFT;
1770 else
1771 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1772 *paste_flag = token;
1775 i += arg_tokens_count;
1778 if (track_macro_exp)
1779 push_extended_tokens_context (pfile, node, buff, virt_locs, first,
1780 tokens_buff_count (buff));
1781 else
1782 push_ptoken_context (pfile, node, buff, first,
1783 tokens_buff_count (buff));
1785 num_macro_tokens_counter += tokens_buff_count (buff);
1788 /* Return a special padding token, with padding inherited from SOURCE. */
1789 static const cpp_token *
1790 padding_token (cpp_reader *pfile, const cpp_token *source)
1792 cpp_token *result = _cpp_temp_token (pfile);
1794 result->type = CPP_PADDING;
1796 /* Data in GCed data structures cannot be made const so far, so we
1797 need a cast here. */
1798 result->val.source = (cpp_token *) source;
1799 result->flags = 0;
1800 return result;
1803 /* Get a new uninitialized context. Create a new one if we cannot
1804 re-use an old one. */
1805 static cpp_context *
1806 next_context (cpp_reader *pfile)
1808 cpp_context *result = pfile->context->next;
1810 if (result == 0)
1812 result = XNEW (cpp_context);
1813 memset (result, 0, sizeof (cpp_context));
1814 result->prev = pfile->context;
1815 result->next = 0;
1816 pfile->context->next = result;
1819 pfile->context = result;
1820 return result;
1823 /* Push a list of pointers to tokens. */
1824 static void
1825 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
1826 const cpp_token **first, unsigned int count)
1828 cpp_context *context = next_context (pfile);
1830 context->tokens_kind = TOKENS_KIND_INDIRECT;
1831 context->c.macro = macro;
1832 context->buff = buff;
1833 FIRST (context).ptoken = first;
1834 LAST (context).ptoken = first + count;
1837 /* Push a list of tokens.
1839 A NULL macro means that we should continue the current macro
1840 expansion, in essence. That means that if we are currently in a
1841 macro expansion context, we'll make the new pfile->context refer to
1842 the current macro. */
1843 void
1844 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
1845 const cpp_token *first, unsigned int count)
1847 cpp_context *context;
1849 if (macro == NULL)
1850 macro = macro_of_context (pfile->context);
1852 context = next_context (pfile);
1853 context->tokens_kind = TOKENS_KIND_DIRECT;
1854 context->c.macro = macro;
1855 context->buff = NULL;
1856 FIRST (context).token = first;
1857 LAST (context).token = first + count;
1860 /* Build a context containing a list of tokens as well as their
1861 virtual locations and push it. TOKENS_BUFF is the buffer that
1862 contains the tokens pointed to by FIRST. If TOKENS_BUFF is
1863 non-NULL, it means that the context owns it, meaning that
1864 _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
1865 contains the virtual locations.
1867 A NULL macro means that we should continue the current macro
1868 expansion, in essence. That means that if we are currently in a
1869 macro expansion context, we'll make the new pfile->context refer to
1870 the current macro. */
1871 static void
1872 push_extended_tokens_context (cpp_reader *pfile,
1873 cpp_hashnode *macro,
1874 _cpp_buff *token_buff,
1875 source_location *virt_locs,
1876 const cpp_token **first,
1877 unsigned int count)
1879 cpp_context *context;
1880 macro_context *m;
1882 if (macro == NULL)
1883 macro = macro_of_context (pfile->context);
1885 context = next_context (pfile);
1886 context->tokens_kind = TOKENS_KIND_EXTENDED;
1887 context->buff = token_buff;
1889 m = XNEW (macro_context);
1890 m->macro_node = macro;
1891 m->virt_locs = virt_locs;
1892 m->cur_virt_loc = virt_locs;
1893 context->c.mc = m;
1894 FIRST (context).ptoken = first;
1895 LAST (context).ptoken = first + count;
1898 /* Push a traditional macro's replacement text. */
1899 void
1900 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
1901 const uchar *start, size_t len)
1903 cpp_context *context = next_context (pfile);
1905 context->tokens_kind = TOKENS_KIND_DIRECT;
1906 context->c.macro = macro;
1907 context->buff = NULL;
1908 CUR (context) = start;
1909 RLIMIT (context) = start + len;
1910 macro->flags |= NODE_DISABLED;
1913 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
1914 for the purpose of storing them on a cpp_context. If VIRT_LOCS is
1915 non-null (which means that -ftrack-macro-expansion is on),
1916 *VIRT_LOCS is set to a newly allocated buffer that is supposed to
1917 hold the virtual locations of the tokens resulting from macro
1918 expansion. */
1919 static _cpp_buff*
1920 tokens_buff_new (cpp_reader *pfile, size_t len,
1921 source_location **virt_locs)
1923 size_t tokens_size = len * sizeof (cpp_token *);
1924 size_t locs_size = len * sizeof (source_location);
1926 if (virt_locs != NULL)
1927 *virt_locs = XNEWVEC (source_location, locs_size);
1928 return _cpp_get_buff (pfile, tokens_size);
1931 /* Returns the number of tokens contained in a token buffer. The
1932 buffer holds a set of cpp_token*. */
1933 static size_t
1934 tokens_buff_count (_cpp_buff *buff)
1936 return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
1939 /* Return a pointer to the last token contained in the token buffer
1940 BUFF. */
1941 static const cpp_token **
1942 tokens_buff_last_token_ptr (_cpp_buff *buff)
1944 return &((const cpp_token **) BUFF_FRONT (buff))[-1];
1947 /* Remove the last token contained in the token buffer TOKENS_BUFF.
1948 If VIRT_LOCS_BUFF is non-NULL, it should point at the buffer
1949 containing the virtual locations of the tokens in TOKENS_BUFF; in
1950 which case the function updates that buffer as well. */
1951 static inline void
1952 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
1955 if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
1956 BUFF_FRONT (tokens_buff) =
1957 (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
1960 /* Insert a token into the token buffer at the position pointed to by
1961 DEST. Note that the buffer is not enlarged so the previous token
1962 that was at *DEST is overwritten. VIRT_LOC_DEST, if non-null,
1963 means -ftrack-macro-expansion is effect; it then points to where to
1964 insert the virtual location of TOKEN. TOKEN is the token to
1965 insert. VIRT_LOC is the virtual location of the token, i.e, the
1966 location possibly encoding its locus across macro expansion. If
1967 TOKEN is an argument of a function-like macro (inside a macro
1968 replacement list), PARM_DEF_LOC is the spelling location of the
1969 macro parameter that TOKEN is replacing, in the replacement list of
1970 the macro. If TOKEN is not an argument of a function-like macro or
1971 if it doesn't come from a macro expansion, then VIRT_LOC can just
1972 be set to the same value as PARM_DEF_LOC. If MAP is non null, it
1973 means TOKEN comes from a macro expansion and MAP is the macro map
1974 associated to the macro. MACRO_TOKEN_INDEX points to the index of
1975 the token in the macro map; it is not considered if MAP is NULL.
1977 Upon successful completion this function returns the a pointer to
1978 the position of the token coming right after the insertion
1979 point. */
1980 static inline const cpp_token **
1981 tokens_buff_put_token_to (const cpp_token **dest,
1982 source_location *virt_loc_dest,
1983 const cpp_token *token,
1984 source_location virt_loc,
1985 source_location parm_def_loc,
1986 const struct line_map *map,
1987 unsigned int macro_token_index)
1989 source_location macro_loc = virt_loc;
1990 const cpp_token **result;
1992 if (virt_loc_dest)
1994 /* -ftrack-macro-expansion is on. */
1995 if (map)
1996 macro_loc = linemap_add_macro_token (map, macro_token_index,
1997 virt_loc, parm_def_loc);
1998 *virt_loc_dest = macro_loc;
2000 *dest = token;
2001 result = &dest[1];
2003 return result;
2006 /* Adds a token at the end of the tokens contained in BUFFER. Note
2007 that this function doesn't enlarge BUFFER when the number of tokens
2008 reaches BUFFER's size; it aborts in that situation.
2010 TOKEN is the token to append. VIRT_LOC is the virtual location of
2011 the token, i.e, the location possibly encoding its locus across
2012 macro expansion. If TOKEN is an argument of a function-like macro
2013 (inside a macro replacement list), PARM_DEF_LOC is the location of
2014 the macro parameter that TOKEN is replacing. If TOKEN doesn't come
2015 from a macro expansion, then VIRT_LOC can just be set to the same
2016 value as PARM_DEF_LOC. If MAP is non null, it means TOKEN comes
2017 from a macro expansion and MAP is the macro map associated to the
2018 macro. MACRO_TOKEN_INDEX points to the index of the token in the
2019 macro map; It is not considered if MAP is NULL. If VIRT_LOCS is
2020 non-null, it means -ftrack-macro-expansion is on; in which case
2021 this function adds the virtual location DEF_LOC to the VIRT_LOCS
2022 array, at the same index as the one of TOKEN in BUFFER. Upon
2023 successful completion this function returns the a pointer to the
2024 position of the token coming right after the insertion point. */
2025 static const cpp_token **
2026 tokens_buff_add_token (_cpp_buff *buffer,
2027 source_location *virt_locs,
2028 const cpp_token *token,
2029 source_location virt_loc,
2030 source_location parm_def_loc,
2031 const struct line_map *map,
2032 unsigned int macro_token_index)
2034 const cpp_token **result;
2035 source_location *virt_loc_dest = NULL;
2036 unsigned token_index =
2037 (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2039 /* Abort if we pass the end the buffer. */
2040 if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2041 abort ();
2043 if (virt_locs != NULL)
2044 virt_loc_dest = &virt_locs[token_index];
2046 result =
2047 tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2048 virt_loc_dest, token, virt_loc, parm_def_loc,
2049 map, macro_token_index);
2051 BUFF_FRONT (buffer) = (unsigned char *) result;
2052 return result;
2055 /* Allocate space for the function-like macro argument ARG to store
2056 the tokens resulting from the macro-expansion of the tokens that
2057 make up ARG itself. That space is allocated in ARG->expanded and
2058 needs to be freed using free. */
2059 static void
2060 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2062 #ifdef ENABLE_CHECKING
2063 if (arg->expanded != NULL
2064 || arg->expanded_virt_locs != NULL)
2065 abort ();
2066 #endif
2067 arg->expanded = XNEWVEC (const cpp_token *, capacity);
2068 if (CPP_OPTION (pfile, track_macro_expansion))
2069 arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2073 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2074 tokens. */
2075 static void
2076 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2077 size_t size, size_t *expanded_capacity)
2079 if (size <= *expanded_capacity)
2080 return;
2082 size *= 2;
2084 arg->expanded =
2085 XRESIZEVEC (const cpp_token *, arg->expanded, size);
2086 *expanded_capacity = size;
2088 if (CPP_OPTION (pfile, track_macro_expansion))
2090 if (arg->expanded_virt_locs == NULL)
2091 arg->expanded_virt_locs = XNEWVEC (source_location, size);
2092 else
2093 arg->expanded_virt_locs = XRESIZEVEC (source_location,
2094 arg->expanded_virt_locs,
2095 size);
2099 /* Expand an argument ARG before replacing parameters in a
2100 function-like macro. This works by pushing a context with the
2101 argument's tokens, and then expanding that into a temporary buffer
2102 as if it were a normal part of the token stream. collect_args()
2103 has terminated the argument's tokens with a CPP_EOF so that we know
2104 when we have fully expanded the argument. */
2105 static void
2106 expand_arg (cpp_reader *pfile, macro_arg *arg)
2108 size_t capacity;
2109 bool saved_warn_trad;
2110 bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2112 if (arg->count == 0
2113 || arg->expanded != NULL)
2114 return;
2116 /* Don't warn about funlike macros when pre-expanding. */
2117 saved_warn_trad = CPP_WTRADITIONAL (pfile);
2118 CPP_WTRADITIONAL (pfile) = 0;
2120 /* Loop, reading in the tokens of the argument. */
2121 capacity = 256;
2122 alloc_expanded_arg_mem (pfile, arg, capacity);
2124 if (track_macro_exp_p)
2125 push_extended_tokens_context (pfile, NULL, NULL,
2126 arg->virt_locs,
2127 arg->first,
2128 arg->count + 1);
2129 else
2130 push_ptoken_context (pfile, NULL, NULL,
2131 arg->first, arg->count + 1);
2133 for (;;)
2135 const cpp_token *token;
2136 source_location location;
2138 ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2139 &capacity);
2141 token = cpp_get_token_1 (pfile, &location);
2143 if (token->type == CPP_EOF)
2144 break;
2146 set_arg_token (arg, token, location,
2147 arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2148 CPP_OPTION (pfile, track_macro_expansion));
2149 arg->expanded_count++;
2152 _cpp_pop_context (pfile);
2154 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2157 /* Returns the macro associated to the current context if we are in
2158 the context a macro expansion, NULL otherwise. */
2159 static cpp_hashnode*
2160 macro_of_context (cpp_context *context)
2162 if (context == NULL)
2163 return NULL;
2165 return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2166 ? context->c.mc->macro_node
2167 : context->c.macro;
2170 /* Return TRUE iff we are expanding a macro or are about to start
2171 expanding one. If we are effectively expanding a macro, the
2172 function macro_of_context returns a pointer to the macro being
2173 expanded. */
2174 static bool
2175 in_macro_expansion_p (cpp_reader *pfile)
2177 if (pfile == NULL)
2178 return false;
2180 return (pfile->about_to_expand_macro_p
2181 || macro_of_context (pfile->context));
2184 /* Pop the current context off the stack, re-enabling the macro if the
2185 context represented a macro's replacement list. Initially the
2186 context structure was not freed so that we can re-use it later, but
2187 now we do free it to reduce peak memory consumption. */
2188 void
2189 _cpp_pop_context (cpp_reader *pfile)
2191 cpp_context *context = pfile->context;
2193 /* We should not be popping the base context. */
2194 if (context == &pfile->base_context)
2195 abort ();
2197 if (context->c.macro)
2199 cpp_hashnode *macro;
2200 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2202 macro_context *mc = context->c.mc;
2203 macro = mc->macro_node;
2204 /* If context->buff is set, it means the life time of tokens
2205 is bound to the life time of this context; so we must
2206 free the tokens; that means we must free the virtual
2207 locations of these tokens too. */
2208 if (context->buff && mc->virt_locs)
2210 free (mc->virt_locs);
2211 mc->virt_locs = NULL;
2213 free (mc);
2214 context->c.mc = NULL;
2216 else
2217 macro = context->c.macro;
2219 /* Beware that MACRO can be NULL in cases like when we are
2220 called from expand_arg. In those cases, a dummy context with
2221 tokens is pushed just for the purpose of walking them using
2222 cpp_get_token_1. In that case, no 'macro' field is set into
2223 the dummy context. */
2224 if (macro != NULL
2225 /* Several contiguous macro expansion contexts can be
2226 associated to the same macro; that means it's the same
2227 macro expansion that spans across all these (sub)
2228 contexts. So we should re-enable an expansion-disabled
2229 macro only when we are sure we are really out of that
2230 macro expansion. */
2231 && macro_of_context (context->prev) != macro)
2232 macro->flags &= ~NODE_DISABLED;
2235 if (context->buff)
2237 /* Decrease memory peak consumption by freeing the memory used
2238 by the context. */
2239 _cpp_free_buff (context->buff);
2242 pfile->context = context->prev;
2243 /* decrease peak memory consumption by feeing the context. */
2244 pfile->context->next = NULL;
2245 free (context);
2248 /* Return TRUE if we reached the end of the set of tokens stored in
2249 CONTEXT, FALSE otherwise. */
2250 static inline bool
2251 reached_end_of_context (cpp_context *context)
2253 if (context->tokens_kind == TOKENS_KIND_DIRECT)
2254 return FIRST (context).token == LAST (context).token;
2255 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2256 || context->tokens_kind == TOKENS_KIND_EXTENDED)
2257 return FIRST (context).ptoken == LAST (context).ptoken;
2258 else
2259 abort ();
2262 /* Consume the next token contained in the current context of PFILE,
2263 and return it in *TOKEN. It's "full location" is returned in
2264 *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2265 means the location encoding the locus of the token across macro
2266 expansion; otherwise it's just is the "normal" location of the
2267 token which (*TOKEN)->src_loc. */
2268 static inline void
2269 consume_next_token_from_context (cpp_reader *pfile,
2270 const cpp_token ** token,
2271 source_location *location)
2273 cpp_context *c = pfile->context;
2275 if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2277 *token = FIRST (c).token;
2278 *location = (*token)->src_loc;
2279 FIRST (c).token++;
2281 else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2283 *token = *FIRST (c).ptoken;
2284 *location = (*token)->src_loc;
2285 FIRST (c).ptoken++;
2287 else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2289 macro_context *m = c->c.mc;
2290 *token = *FIRST (c).ptoken;
2291 if (m->virt_locs)
2293 *location = *m->cur_virt_loc;
2294 m->cur_virt_loc++;
2296 else
2297 *location = (*token)->src_loc;
2298 FIRST (c).ptoken++;
2300 else
2301 abort ();
2304 /* In the traditional mode of the preprocessor, if we are currently in
2305 a directive, the location of a token must be the location of the
2306 start of the directive line. This function returns the proper
2307 location if we are in the traditional mode, and just returns
2308 LOCATION otherwise. */
2310 static inline source_location
2311 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2313 if (CPP_OPTION (pfile, traditional))
2315 if (pfile->state.in_directive)
2316 return pfile->directive_line;
2318 return location;
2321 /* Routine to get a token as well as its location.
2323 Macro expansions and directives are transparently handled,
2324 including entering included files. Thus tokens are post-macro
2325 expansion, and after any intervening directives. External callers
2326 see CPP_EOF only at EOF. Internal callers also see it when meeting
2327 a directive inside a macro call, when at the end of a directive and
2328 state.in_directive is still 1, and at the end of argument
2329 pre-expansion.
2331 LOC is an out parameter; *LOC is set to the location "as expected
2332 by the user". Please read the comment of
2333 cpp_get_token_with_location to learn more about the meaning of this
2334 location. */
2335 static const cpp_token*
2336 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2338 const cpp_token *result;
2339 /* This token is a virtual token that either encodes a location
2340 related to macro expansion or a spelling location. */
2341 source_location virt_loc = 0;
2342 /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2343 to functions that push macro contexts. So let's save it so that
2344 we can restore it when we are about to leave this routine. */
2345 bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2347 for (;;)
2349 cpp_hashnode *node;
2350 cpp_context *context = pfile->context;
2352 /* Context->prev == 0 <=> base context. */
2353 if (!context->prev)
2355 result = _cpp_lex_token (pfile);
2356 virt_loc = result->src_loc;
2358 else if (!reached_end_of_context (context))
2360 consume_next_token_from_context (pfile, &result,
2361 &virt_loc);
2362 if (result->flags & PASTE_LEFT)
2364 paste_all_tokens (pfile, result);
2365 if (pfile->state.in_directive)
2366 continue;
2367 result = padding_token (pfile, result);
2368 goto out;
2371 else
2373 if (pfile->context->c.macro)
2374 ++num_expanded_macros_counter;
2375 _cpp_pop_context (pfile);
2376 if (pfile->state.in_directive)
2377 continue;
2378 result = &pfile->avoid_paste;
2379 goto out;
2382 if (pfile->state.in_directive && result->type == CPP_COMMENT)
2383 continue;
2385 if (result->type != CPP_NAME)
2386 break;
2388 node = result->val.node.node;
2390 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2391 break;
2393 if (!(node->flags & NODE_DISABLED))
2395 int ret = 0;
2396 /* If not in a macro context, and we're going to start an
2397 expansion, record the location. */
2398 if (!in_macro_expansion_p (pfile))
2399 pfile->invocation_location = result->src_loc;
2400 if (pfile->state.prevent_expansion)
2401 break;
2403 /* Conditional macros require that a predicate be evaluated
2404 first. */
2405 if ((node->flags & NODE_CONDITIONAL) != 0)
2407 if (pfile->cb.macro_to_expand)
2409 bool whitespace_after;
2410 const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2412 whitespace_after = (peek_tok->type == CPP_PADDING
2413 || (peek_tok->flags & PREV_WHITE));
2414 node = pfile->cb.macro_to_expand (pfile, result);
2415 if (node)
2416 ret = enter_macro_context (pfile, node, result,
2417 virt_loc);
2418 else if (whitespace_after)
2420 /* If macro_to_expand hook returned NULL and it
2421 ate some tokens, see if we don't need to add
2422 a padding token in between this and the
2423 next token. */
2424 peek_tok = cpp_peek_token (pfile, 0);
2425 if (peek_tok->type != CPP_PADDING
2426 && (peek_tok->flags & PREV_WHITE) == 0)
2427 _cpp_push_token_context (pfile, NULL,
2428 padding_token (pfile,
2429 peek_tok), 1);
2433 else
2434 ret = enter_macro_context (pfile, node, result,
2435 virt_loc);
2436 if (ret)
2438 if (pfile->state.in_directive || ret == 2)
2439 continue;
2440 result = padding_token (pfile, result);
2441 goto out;
2444 else
2446 /* Flag this token as always unexpandable. FIXME: move this
2447 to collect_args()?. */
2448 cpp_token *t = _cpp_temp_token (pfile);
2449 t->type = result->type;
2450 t->flags = result->flags | NO_EXPAND;
2451 t->val = result->val;
2452 result = t;
2455 break;
2458 out:
2459 if (location != NULL)
2461 if (virt_loc == 0)
2462 virt_loc = result->src_loc;
2463 *location = virt_loc;
2465 if (!CPP_OPTION (pfile, track_macro_expansion)
2466 && macro_of_context (pfile->context) != NULL)
2467 /* We are in a macro expansion context, are not tracking
2468 virtual location, but were asked to report the location
2469 of the expansion point of the macro being expanded. */
2470 *location = pfile->invocation_location;
2472 *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2475 pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
2476 return result;
2479 /* External routine to get a token. Also used nearly everywhere
2480 internally, except for places where we know we can safely call
2481 _cpp_lex_token directly, such as lexing a directive name.
2483 Macro expansions and directives are transparently handled,
2484 including entering included files. Thus tokens are post-macro
2485 expansion, and after any intervening directives. External callers
2486 see CPP_EOF only at EOF. Internal callers also see it when meeting
2487 a directive inside a macro call, when at the end of a directive and
2488 state.in_directive is still 1, and at the end of argument
2489 pre-expansion. */
2490 const cpp_token *
2491 cpp_get_token (cpp_reader *pfile)
2493 return cpp_get_token_1 (pfile, NULL);
2496 /* Like cpp_get_token, but also returns a virtual token location
2497 separate from the spelling location carried by the returned token.
2499 LOC is an out parameter; *LOC is set to the location "as expected
2500 by the user". This matters when a token results from macro
2501 expansion; in that case the token's spelling location indicates the
2502 locus of the token in the definition of the macro but *LOC
2503 virtually encodes all the other meaningful locuses associated to
2504 the token.
2506 What? virtual location? Yes, virtual location.
2508 If the token results from macro expansion and if macro expansion
2509 location tracking is enabled its virtual location encodes (at the
2510 same time):
2512 - the spelling location of the token
2514 - the locus of the macro expansion point
2516 - the locus of the point where the token got instantiated as part
2517 of the macro expansion process.
2519 You have to use the linemap API to get the locus you are interested
2520 in from a given virtual location.
2522 Note however that virtual locations are not necessarily ordered for
2523 relations '<' and '>'. One must use the function
2524 linemap_location_before_p instead of using the relational operator
2525 '<'.
2527 If macro expansion tracking is off and if the token results from
2528 macro expansion the virtual location is the expansion point of the
2529 macro that got expanded.
2531 When the token doesn't result from macro expansion, the virtual
2532 location is just the same thing as its spelling location. */
2534 const cpp_token *
2535 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2537 return cpp_get_token_1 (pfile, loc);
2540 /* Returns true if we're expanding an object-like macro that was
2541 defined in a system header. Just checks the macro at the top of
2542 the stack. Used for diagnostic suppression. */
2544 cpp_sys_macro_p (cpp_reader *pfile)
2546 cpp_hashnode *node = NULL;
2548 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2549 node = pfile->context->c.mc->macro_node;
2550 else
2551 node = pfile->context->c.macro;
2553 return node && node->value.macro && node->value.macro->syshdr;
2556 /* Read each token in, until end of the current file. Directives are
2557 transparently processed. */
2558 void
2559 cpp_scan_nooutput (cpp_reader *pfile)
2561 /* Request a CPP_EOF token at the end of this file, rather than
2562 transparently continuing with the including file. */
2563 pfile->buffer->return_at_eof = true;
2565 pfile->state.discarding_output++;
2566 pfile->state.prevent_expansion++;
2568 if (CPP_OPTION (pfile, traditional))
2569 while (_cpp_read_logical_line_trad (pfile))
2571 else
2572 while (cpp_get_token (pfile)->type != CPP_EOF)
2575 pfile->state.discarding_output--;
2576 pfile->state.prevent_expansion--;
2579 /* Step back one or more tokens obtained from the lexer. */
2580 void
2581 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2583 pfile->lookaheads += count;
2584 while (count--)
2586 pfile->cur_token--;
2587 if (pfile->cur_token == pfile->cur_run->base
2588 /* Possible with -fpreprocessed and no leading #line. */
2589 && pfile->cur_run->prev != NULL)
2591 pfile->cur_run = pfile->cur_run->prev;
2592 pfile->cur_token = pfile->cur_run->limit;
2597 /* Step back one (or more) tokens. Can only step back more than 1 if
2598 they are from the lexer, and not from macro expansion. */
2599 void
2600 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2602 if (pfile->context->prev == NULL)
2603 _cpp_backup_tokens_direct (pfile, count);
2604 else
2606 if (count != 1)
2607 abort ();
2608 if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2609 FIRST (pfile->context).token--;
2610 else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2611 FIRST (pfile->context).ptoken--;
2612 else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2614 FIRST (pfile->context).ptoken--;
2615 if (pfile->context->c.macro)
2617 macro_context *m = pfile->context->c.mc;
2618 m->cur_virt_loc--;
2619 #ifdef ENABLE_CHECKING
2620 if (m->cur_virt_loc < m->virt_locs)
2621 abort ();
2622 #endif
2624 else
2625 abort ();
2627 else
2628 abort ();
2632 /* #define directive parsing and handling. */
2634 /* Returns nonzero if a macro redefinition warning is required. */
2635 static bool
2636 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2637 const cpp_macro *macro2)
2639 const cpp_macro *macro1;
2640 unsigned int i;
2642 /* Some redefinitions need to be warned about regardless. */
2643 if (node->flags & NODE_WARN)
2644 return true;
2646 /* Suppress warnings for builtins that lack the NODE_WARN flag. */
2647 if (node->flags & NODE_BUILTIN)
2649 if (!pfile->cb.user_builtin_macro
2650 || !pfile->cb.user_builtin_macro (pfile, node))
2651 return false;
2654 /* Redefinitions of conditional (context-sensitive) macros, on
2655 the other hand, must be allowed silently. */
2656 if (node->flags & NODE_CONDITIONAL)
2657 return false;
2659 /* Redefinition of a macro is allowed if and only if the old and new
2660 definitions are the same. (6.10.3 paragraph 2). */
2661 macro1 = node->value.macro;
2663 /* Don't check count here as it can be different in valid
2664 traditional redefinitions with just whitespace differences. */
2665 if (macro1->paramc != macro2->paramc
2666 || macro1->fun_like != macro2->fun_like
2667 || macro1->variadic != macro2->variadic)
2668 return true;
2670 /* Check parameter spellings. */
2671 for (i = 0; i < macro1->paramc; i++)
2672 if (macro1->params[i] != macro2->params[i])
2673 return true;
2675 /* Check the replacement text or tokens. */
2676 if (CPP_OPTION (pfile, traditional))
2677 return _cpp_expansions_different_trad (macro1, macro2);
2679 if (macro1->count != macro2->count)
2680 return true;
2682 for (i = 0; i < macro1->count; i++)
2683 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2684 return true;
2686 return false;
2689 /* Free the definition of hashnode H. */
2690 void
2691 _cpp_free_definition (cpp_hashnode *h)
2693 /* Macros and assertions no longer have anything to free. */
2694 h->type = NT_VOID;
2695 /* Clear builtin flag in case of redefinition. */
2696 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2699 /* Save parameter NODE to the parameter list of macro MACRO. Returns
2700 zero on success, nonzero if the parameter is a duplicate. */
2701 bool
2702 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
2704 unsigned int len;
2705 /* Constraint 6.10.3.6 - duplicate parameter names. */
2706 if (node->flags & NODE_MACRO_ARG)
2708 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2709 NODE_NAME (node));
2710 return true;
2713 if (BUFF_ROOM (pfile->a_buff)
2714 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2715 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2717 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
2718 node->flags |= NODE_MACRO_ARG;
2719 len = macro->paramc * sizeof (union _cpp_hashnode_value);
2720 if (len > pfile->macro_buffer_len)
2722 pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2723 len);
2724 pfile->macro_buffer_len = len;
2726 ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
2727 = node->value;
2729 node->value.arg_index = macro->paramc;
2730 return false;
2733 /* Check the syntax of the parameters in a MACRO definition. Returns
2734 false if an error occurs. */
2735 static bool
2736 parse_params (cpp_reader *pfile, cpp_macro *macro)
2738 unsigned int prev_ident = 0;
2740 for (;;)
2742 const cpp_token *token = _cpp_lex_token (pfile);
2744 switch (token->type)
2746 default:
2747 /* Allow/ignore comments in parameter lists if we are
2748 preserving comments in macro expansions. */
2749 if (token->type == CPP_COMMENT
2750 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
2751 continue;
2753 cpp_error (pfile, CPP_DL_ERROR,
2754 "\"%s\" may not appear in macro parameter list",
2755 cpp_token_as_text (pfile, token));
2756 return false;
2758 case CPP_NAME:
2759 if (prev_ident)
2761 cpp_error (pfile, CPP_DL_ERROR,
2762 "macro parameters must be comma-separated");
2763 return false;
2765 prev_ident = 1;
2767 if (_cpp_save_parameter (pfile, macro, token->val.node.node))
2768 return false;
2769 continue;
2771 case CPP_CLOSE_PAREN:
2772 if (prev_ident || macro->paramc == 0)
2773 return true;
2775 /* Fall through to pick up the error. */
2776 case CPP_COMMA:
2777 if (!prev_ident)
2779 cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
2780 return false;
2782 prev_ident = 0;
2783 continue;
2785 case CPP_ELLIPSIS:
2786 macro->variadic = 1;
2787 if (!prev_ident)
2789 _cpp_save_parameter (pfile, macro,
2790 pfile->spec_nodes.n__VA_ARGS__);
2791 pfile->state.va_args_ok = 1;
2792 if (! CPP_OPTION (pfile, c99)
2793 && CPP_OPTION (pfile, cpp_pedantic)
2794 && CPP_OPTION (pfile, warn_variadic_macros))
2795 cpp_pedwarning
2796 (pfile, CPP_W_VARIADIC_MACROS,
2797 "anonymous variadic macros were introduced in C99");
2799 else if (CPP_OPTION (pfile, cpp_pedantic)
2800 && CPP_OPTION (pfile, warn_variadic_macros))
2801 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2802 "ISO C does not permit named variadic macros");
2804 /* We're at the end, and just expect a closing parenthesis. */
2805 token = _cpp_lex_token (pfile);
2806 if (token->type == CPP_CLOSE_PAREN)
2807 return true;
2808 /* Fall through. */
2810 case CPP_EOF:
2811 cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
2812 return false;
2817 /* Allocate room for a token from a macro's replacement list. */
2818 static cpp_token *
2819 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2821 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
2822 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
2824 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
2827 /* Lex a token from the expansion of MACRO, but mark parameters as we
2828 find them and warn of traditional stringification. */
2829 static cpp_token *
2830 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2832 cpp_token *token, *saved_cur_token;
2834 saved_cur_token = pfile->cur_token;
2835 pfile->cur_token = alloc_expansion_token (pfile, macro);
2836 token = _cpp_lex_direct (pfile);
2837 pfile->cur_token = saved_cur_token;
2839 /* Is this a parameter? */
2840 if (token->type == CPP_NAME
2841 && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
2843 token->type = CPP_MACRO_ARG;
2844 token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
2846 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
2847 && (token->type == CPP_STRING || token->type == CPP_CHAR))
2848 check_trad_stringification (pfile, macro, &token->val.str);
2850 return token;
2853 static bool
2854 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
2856 cpp_token *token;
2857 const cpp_token *ctoken;
2858 bool following_paste_op = false;
2859 const char *paste_op_error_msg =
2860 N_("'##' cannot appear at either end of a macro expansion");
2861 unsigned int num_extra_tokens = 0;
2863 /* Get the first token of the expansion (or the '(' of a
2864 function-like macro). */
2865 ctoken = _cpp_lex_token (pfile);
2867 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
2869 bool ok = parse_params (pfile, macro);
2870 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
2871 if (!ok)
2872 return false;
2874 /* Success. Commit or allocate the parameter array. */
2875 if (pfile->hash_table->alloc_subobject)
2877 cpp_hashnode **params =
2878 (cpp_hashnode **) pfile->hash_table->alloc_subobject
2879 (sizeof (cpp_hashnode *) * macro->paramc);
2880 memcpy (params, macro->params,
2881 sizeof (cpp_hashnode *) * macro->paramc);
2882 macro->params = params;
2884 else
2885 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
2886 macro->fun_like = 1;
2888 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
2890 /* While ISO C99 requires whitespace before replacement text
2891 in a macro definition, ISO C90 with TC1 allows there characters
2892 from the basic source character set. */
2893 if (CPP_OPTION (pfile, c99))
2894 cpp_error (pfile, CPP_DL_PEDWARN,
2895 "ISO C99 requires whitespace after the macro name");
2896 else
2898 int warntype = CPP_DL_WARNING;
2899 switch (ctoken->type)
2901 case CPP_ATSIGN:
2902 case CPP_AT_NAME:
2903 case CPP_OBJC_STRING:
2904 /* '@' is not in basic character set. */
2905 warntype = CPP_DL_PEDWARN;
2906 break;
2907 case CPP_OTHER:
2908 /* Basic character set sans letters, digits and _. */
2909 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
2910 ctoken->val.str.text[0]) == NULL)
2911 warntype = CPP_DL_PEDWARN;
2912 break;
2913 default:
2914 /* All other tokens start with a character from basic
2915 character set. */
2916 break;
2918 cpp_error (pfile, warntype,
2919 "missing whitespace after the macro name");
2923 if (macro->fun_like)
2924 token = lex_expansion_token (pfile, macro);
2925 else
2927 token = alloc_expansion_token (pfile, macro);
2928 *token = *ctoken;
2931 for (;;)
2933 /* Check the stringifying # constraint 6.10.3.2.1 of
2934 function-like macros when lexing the subsequent token. */
2935 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
2937 if (token->type == CPP_MACRO_ARG)
2939 if (token->flags & PREV_WHITE)
2940 token->flags |= SP_PREV_WHITE;
2941 if (token[-1].flags & DIGRAPH)
2942 token->flags |= SP_DIGRAPH;
2943 token->flags &= ~PREV_WHITE;
2944 token->flags |= STRINGIFY_ARG;
2945 token->flags |= token[-1].flags & PREV_WHITE;
2946 token[-1] = token[0];
2947 macro->count--;
2949 /* Let assembler get away with murder. */
2950 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
2952 cpp_error (pfile, CPP_DL_ERROR,
2953 "'#' is not followed by a macro parameter");
2954 return false;
2958 if (token->type == CPP_EOF)
2960 /* Paste operator constraint 6.10.3.3.1:
2961 Token-paste ##, can appear in both object-like and
2962 function-like macros, but not at the end. */
2963 if (following_paste_op)
2965 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
2966 return false;
2968 break;
2971 /* Paste operator constraint 6.10.3.3.1. */
2972 if (token->type == CPP_PASTE)
2974 /* Token-paste ##, can appear in both object-like and
2975 function-like macros, but not at the beginning. */
2976 if (macro->count == 1)
2978 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
2979 return false;
2982 if (token[-1].flags & PASTE_LEFT)
2984 macro->extra_tokens = 1;
2985 num_extra_tokens++;
2986 token->val.token_no = macro->count - 1;
2988 else
2990 --macro->count;
2991 token[-1].flags |= PASTE_LEFT;
2992 if (token->flags & DIGRAPH)
2993 token[-1].flags |= SP_DIGRAPH;
2994 if (token->flags & PREV_WHITE)
2995 token[-1].flags |= SP_PREV_WHITE;
2999 following_paste_op = (token->type == CPP_PASTE);
3000 token = lex_expansion_token (pfile, macro);
3003 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
3004 macro->traditional = 0;
3006 /* Don't count the CPP_EOF. */
3007 macro->count--;
3009 /* Clear whitespace on first token for warn_of_redefinition(). */
3010 if (macro->count)
3011 macro->exp.tokens[0].flags &= ~PREV_WHITE;
3013 /* Commit or allocate the memory. */
3014 if (pfile->hash_table->alloc_subobject)
3016 cpp_token *tokns =
3017 (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
3018 * macro->count);
3019 if (num_extra_tokens)
3021 /* Place second and subsequent ## or %:%: tokens in
3022 sequences of consecutive such tokens at the end of the
3023 list to preserve information about where they appear, how
3024 they are spelt and whether they are preceded by
3025 whitespace without otherwise interfering with macro
3026 expansion. */
3027 cpp_token *normal_dest = tokns;
3028 cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
3029 unsigned int i;
3030 for (i = 0; i < macro->count; i++)
3032 if (macro->exp.tokens[i].type == CPP_PASTE)
3033 *extra_dest++ = macro->exp.tokens[i];
3034 else
3035 *normal_dest++ = macro->exp.tokens[i];
3038 else
3039 memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
3040 macro->exp.tokens = tokns;
3042 else
3043 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
3045 return true;
3048 /* Parse a macro and save its expansion. Returns nonzero on success. */
3049 bool
3050 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3052 cpp_macro *macro;
3053 unsigned int i;
3054 bool ok;
3056 if (pfile->hash_table->alloc_subobject)
3057 macro = (cpp_macro *) pfile->hash_table->alloc_subobject
3058 (sizeof (cpp_macro));
3059 else
3060 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
3061 macro->line = pfile->directive_line;
3062 macro->params = 0;
3063 macro->paramc = 0;
3064 macro->variadic = 0;
3065 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3066 macro->count = 0;
3067 macro->fun_like = 0;
3068 macro->extra_tokens = 0;
3069 /* To suppress some diagnostics. */
3070 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3072 if (CPP_OPTION (pfile, traditional))
3073 ok = _cpp_create_trad_definition (pfile, macro);
3074 else
3076 ok = create_iso_definition (pfile, macro);
3078 /* We set the type for SEEN_EOL() in directives.c.
3080 Longer term we should lex the whole line before coming here,
3081 and just copy the expansion. */
3083 /* Stop the lexer accepting __VA_ARGS__. */
3084 pfile->state.va_args_ok = 0;
3087 /* Clear the fast argument lookup indices. */
3088 for (i = macro->paramc; i-- > 0; )
3090 struct cpp_hashnode *node = macro->params[i];
3091 node->flags &= ~ NODE_MACRO_ARG;
3092 node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
3095 if (!ok)
3096 return ok;
3098 if (node->type == NT_MACRO)
3100 if (CPP_OPTION (pfile, warn_unused_macros))
3101 _cpp_warn_if_unused_macro (pfile, node, NULL);
3103 if (warn_of_redefinition (pfile, node, macro))
3105 const int reason = (node->flags & NODE_BUILTIN)
3106 ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3107 bool warned;
3109 warned = cpp_pedwarning_with_line (pfile, reason,
3110 pfile->directive_line, 0,
3111 "\"%s\" redefined",
3112 NODE_NAME (node));
3114 if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3115 cpp_error_with_line (pfile, CPP_DL_NOTE,
3116 node->value.macro->line, 0,
3117 "this is the location of the previous definition");
3121 if (node->type != NT_VOID)
3122 _cpp_free_definition (node);
3124 /* Enter definition in hash table. */
3125 node->type = NT_MACRO;
3126 node->value.macro = macro;
3127 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3128 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3129 /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3130 in the C standard, as something that one must use in C++.
3131 However DR#593 indicates that these aren't actually mentioned
3132 in the C++ standard. We special-case them anyway. */
3133 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3134 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3135 node->flags |= NODE_WARN;
3137 /* If user defines one of the conditional macros, remove the
3138 conditional flag */
3139 node->flags &= ~NODE_CONDITIONAL;
3141 return ok;
3144 /* Warn if a token in STRING matches one of a function-like MACRO's
3145 parameters. */
3146 static void
3147 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3148 const cpp_string *string)
3150 unsigned int i, len;
3151 const uchar *p, *q, *limit;
3153 /* Loop over the string. */
3154 limit = string->text + string->len - 1;
3155 for (p = string->text + 1; p < limit; p = q)
3157 /* Find the start of an identifier. */
3158 while (p < limit && !is_idstart (*p))
3159 p++;
3161 /* Find the end of the identifier. */
3162 q = p;
3163 while (q < limit && is_idchar (*q))
3164 q++;
3166 len = q - p;
3168 /* Loop over the function macro arguments to see if the
3169 identifier inside the string matches one of them. */
3170 for (i = 0; i < macro->paramc; i++)
3172 const cpp_hashnode *node = macro->params[i];
3174 if (NODE_LEN (node) == len
3175 && !memcmp (p, NODE_NAME (node), len))
3177 cpp_error (pfile, CPP_DL_WARNING,
3178 "macro argument \"%s\" would be stringified in traditional C",
3179 NODE_NAME (node));
3180 break;
3186 /* Returns the name, arguments and expansion of a macro, in a format
3187 suitable to be read back in again, and therefore also for DWARF 2
3188 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3189 Caller is expected to generate the "#define" bit if needed. The
3190 returned text is temporary, and automatically freed later. */
3191 const unsigned char *
3192 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3194 unsigned int i, len;
3195 const cpp_macro *macro;
3196 unsigned char *buffer;
3198 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3200 if (node->type != NT_MACRO
3201 || !pfile->cb.user_builtin_macro
3202 || !pfile->cb.user_builtin_macro (pfile, node))
3204 cpp_error (pfile, CPP_DL_ICE,
3205 "invalid hash type %d in cpp_macro_definition",
3206 node->type);
3207 return 0;
3211 macro = node->value.macro;
3212 /* Calculate length. */
3213 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
3214 if (macro->fun_like)
3216 len += 4; /* "()" plus possible final ".." of named
3217 varargs (we have + 1 below). */
3218 for (i = 0; i < macro->paramc; i++)
3219 len += NODE_LEN (macro->params[i]) + 1; /* "," */
3222 /* This should match below where we fill in the buffer. */
3223 if (CPP_OPTION (pfile, traditional))
3224 len += _cpp_replacement_text_len (macro);
3225 else
3227 unsigned int count = macro_real_token_count (macro);
3228 for (i = 0; i < count; i++)
3230 cpp_token *token = &macro->exp.tokens[i];
3232 if (token->type == CPP_MACRO_ARG)
3233 len += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3234 else
3235 len += cpp_token_len (token);
3237 if (token->flags & STRINGIFY_ARG)
3238 len++; /* "#" */
3239 if (token->flags & PASTE_LEFT)
3240 len += 3; /* " ##" */
3241 if (token->flags & PREV_WHITE)
3242 len++; /* " " */
3246 if (len > pfile->macro_buffer_len)
3248 pfile->macro_buffer = XRESIZEVEC (unsigned char,
3249 pfile->macro_buffer, len);
3250 pfile->macro_buffer_len = len;
3253 /* Fill in the buffer. Start with the macro name. */
3254 buffer = pfile->macro_buffer;
3255 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
3256 buffer += NODE_LEN (node);
3258 /* Parameter names. */
3259 if (macro->fun_like)
3261 *buffer++ = '(';
3262 for (i = 0; i < macro->paramc; i++)
3264 cpp_hashnode *param = macro->params[i];
3266 if (param != pfile->spec_nodes.n__VA_ARGS__)
3268 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3269 buffer += NODE_LEN (param);
3272 if (i + 1 < macro->paramc)
3273 /* Don't emit a space after the comma here; we're trying
3274 to emit a Dwarf-friendly definition, and the Dwarf spec
3275 forbids spaces in the argument list. */
3276 *buffer++ = ',';
3277 else if (macro->variadic)
3278 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3280 *buffer++ = ')';
3283 /* The Dwarf spec requires a space after the macro name, even if the
3284 definition is the empty string. */
3285 *buffer++ = ' ';
3287 if (CPP_OPTION (pfile, traditional))
3288 buffer = _cpp_copy_replacement_text (macro, buffer);
3289 else if (macro->count)
3290 /* Expansion tokens. */
3292 unsigned int count = macro_real_token_count (macro);
3293 for (i = 0; i < count; i++)
3295 cpp_token *token = &macro->exp.tokens[i];
3297 if (token->flags & PREV_WHITE)
3298 *buffer++ = ' ';
3299 if (token->flags & STRINGIFY_ARG)
3300 *buffer++ = '#';
3302 if (token->type == CPP_MACRO_ARG)
3304 memcpy (buffer,
3305 NODE_NAME (macro->params[token->val.macro_arg.arg_no - 1]),
3306 NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]));
3307 buffer += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3309 else
3310 buffer = cpp_spell_token (pfile, token, buffer, false);
3312 if (token->flags & PASTE_LEFT)
3314 *buffer++ = ' ';
3315 *buffer++ = '#';
3316 *buffer++ = '#';
3317 /* Next has PREV_WHITE; see _cpp_create_definition. */
3322 *buffer = '\0';
3323 return pfile->macro_buffer;