2014-07-10 Edward Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / libcpp / macro.c
blobab4817e8af60c599d1e5d64b056dcc15c7358f98
1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986-2014 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 if (CPP_OPTION (pfile, warn_date_time))
236 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
237 "reproducible builds", NODE_NAME (node));
239 cpp_buffer *pbuffer = cpp_get_buffer (pfile);
240 if (pbuffer->timestamp == NULL)
242 /* Initialize timestamp value of the assotiated file. */
243 struct _cpp_file *file = cpp_get_file (pbuffer);
244 if (file)
246 /* Generate __TIMESTAMP__ string, that represents
247 the date and time of the last modification
248 of the current source file. The string constant
249 looks like "Sun Sep 16 01:03:52 1973". */
250 struct tm *tb = NULL;
251 struct stat *st = _cpp_get_file_stat (file);
252 if (st)
253 tb = localtime (&st->st_mtime);
254 if (tb)
256 char *str = asctime (tb);
257 size_t len = strlen (str);
258 unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
259 buf[0] = '"';
260 strcpy ((char *) buf + 1, str);
261 buf[len] = '"';
262 pbuffer->timestamp = buf;
264 else
266 cpp_errno (pfile, CPP_DL_WARNING,
267 "could not determine file timestamp");
268 pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
272 result = pbuffer->timestamp;
274 break;
275 case BT_FILE:
276 case BT_BASE_FILE:
278 unsigned int len;
279 const char *name;
280 uchar *buf;
282 if (node->value.builtin == BT_FILE)
283 name = linemap_get_expansion_filename (pfile->line_table,
284 pfile->line_table->highest_line);
285 else
287 name = _cpp_get_file_name (pfile->main_file);
288 if (!name)
289 abort ();
291 len = strlen (name);
292 buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
293 result = buf;
294 *buf = '"';
295 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
296 *buf++ = '"';
297 *buf = '\0';
299 break;
301 case BT_INCLUDE_LEVEL:
302 /* The line map depth counts the primary source as level 1, but
303 historically __INCLUDE_DEPTH__ has called the primary source
304 level 0. */
305 number = pfile->line_table->depth - 1;
306 break;
308 case BT_SPECLINE:
309 /* If __LINE__ is embedded in a macro, it must expand to the
310 line of the macro's invocation, not its definition.
311 Otherwise things like assert() will not work properly. */
312 number = linemap_get_expansion_line (pfile->line_table,
313 CPP_OPTION (pfile, traditional)
314 ? pfile->line_table->highest_line
315 : pfile->cur_token[-1].src_loc);
316 break;
318 /* __STDC__ has the value 1 under normal circumstances.
319 However, if (a) we are in a system header, (b) the option
320 stdc_0_in_system_headers is true (set by target config), and
321 (c) we are not in strictly conforming mode, then it has the
322 value 0. (b) and (c) are already checked in cpp_init_builtins. */
323 case BT_STDC:
324 if (cpp_in_system_header (pfile))
325 number = 0;
326 else
327 number = 1;
328 break;
330 case BT_DATE:
331 case BT_TIME:
332 if (CPP_OPTION (pfile, warn_date_time))
333 cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
334 "reproducible builds", NODE_NAME (node));
335 if (pfile->date == NULL)
337 /* Allocate __DATE__ and __TIME__ strings from permanent
338 storage. We only do this once, and don't generate them
339 at init time, because time() and localtime() are very
340 slow on some systems. */
341 time_t tt;
342 struct tm *tb = NULL;
344 /* (time_t) -1 is a legitimate value for "number of seconds
345 since the Epoch", so we have to do a little dance to
346 distinguish that from a genuine error. */
347 errno = 0;
348 tt = time(NULL);
349 if (tt != (time_t)-1 || errno == 0)
350 tb = localtime (&tt);
352 if (tb)
354 pfile->date = _cpp_unaligned_alloc (pfile,
355 sizeof ("\"Oct 11 1347\""));
356 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
357 monthnames[tb->tm_mon], tb->tm_mday,
358 tb->tm_year + 1900);
360 pfile->time = _cpp_unaligned_alloc (pfile,
361 sizeof ("\"12:34:56\""));
362 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
363 tb->tm_hour, tb->tm_min, tb->tm_sec);
365 else
367 cpp_errno (pfile, CPP_DL_WARNING,
368 "could not determine date and time");
370 pfile->date = UC"\"??? ?? ????\"";
371 pfile->time = UC"\"??:??:??\"";
375 if (node->value.builtin == BT_DATE)
376 result = pfile->date;
377 else
378 result = pfile->time;
379 break;
381 case BT_COUNTER:
382 if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
383 cpp_error (pfile, CPP_DL_ERROR,
384 "__COUNTER__ expanded inside directive with -fdirectives-only");
385 number = pfile->counter++;
386 break;
389 if (result == NULL)
391 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
392 result = _cpp_unaligned_alloc (pfile, 21);
393 sprintf ((char *) result, "%u", number);
396 return result;
399 /* Convert builtin macros like __FILE__ to a token and push it on the
400 context stack. Also handles _Pragma, for which a new token may not
401 be created. Returns 1 if it generates a new token context, 0 to
402 return the token to the caller. */
403 static int
404 builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
406 const uchar *buf;
407 size_t len;
408 char *nbuf;
410 if (node->value.builtin == BT_PRAGMA)
412 /* Don't interpret _Pragma within directives. The standard is
413 not clear on this, but to me this makes most sense. */
414 if (pfile->state.in_directive)
415 return 0;
417 return _cpp_do__Pragma (pfile);
420 buf = _cpp_builtin_macro_text (pfile, node);
421 len = ustrlen (buf);
422 nbuf = (char *) alloca (len + 1);
423 memcpy (nbuf, buf, len);
424 nbuf[len]='\n';
426 cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
427 _cpp_clean_line (pfile);
429 /* Set pfile->cur_token as required by _cpp_lex_direct. */
430 pfile->cur_token = _cpp_temp_token (pfile);
431 _cpp_push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
432 if (pfile->buffer->cur != pfile->buffer->rlimit)
433 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
434 NODE_NAME (node));
435 _cpp_pop_buffer (pfile);
437 return 1;
440 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
441 backslashes and double quotes. DEST must be of sufficient size.
442 Returns a pointer to the end of the string. */
443 uchar *
444 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
446 while (len--)
448 uchar c = *src++;
450 if (c == '\\' || c == '"')
452 *dest++ = '\\';
453 *dest++ = c;
455 else
456 *dest++ = c;
459 return dest;
462 /* Convert a token sequence ARG to a single string token according to
463 the rules of the ISO C #-operator. */
464 static const cpp_token *
465 stringify_arg (cpp_reader *pfile, macro_arg *arg)
467 unsigned char *dest;
468 unsigned int i, escape_it, backslash_count = 0;
469 const cpp_token *source = NULL;
470 size_t len;
472 if (BUFF_ROOM (pfile->u_buff) < 3)
473 _cpp_extend_buff (pfile, &pfile->u_buff, 3);
474 dest = BUFF_FRONT (pfile->u_buff);
475 *dest++ = '"';
477 /* Loop, reading in the argument's tokens. */
478 for (i = 0; i < arg->count; i++)
480 const cpp_token *token = arg->first[i];
482 if (token->type == CPP_PADDING)
484 if (source == NULL
485 || (!(source->flags & PREV_WHITE)
486 && token->val.source == NULL))
487 source = token->val.source;
488 continue;
491 escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
492 || token->type == CPP_WSTRING || token->type == CPP_WCHAR
493 || token->type == CPP_STRING32 || token->type == CPP_CHAR32
494 || token->type == CPP_STRING16 || token->type == CPP_CHAR16
495 || token->type == CPP_UTF8STRING
496 || cpp_userdef_string_p (token->type)
497 || cpp_userdef_char_p (token->type));
499 /* Room for each char being written in octal, initial space and
500 final quote and NUL. */
501 len = cpp_token_len (token);
502 if (escape_it)
503 len *= 4;
504 len += 3;
506 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
508 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
509 _cpp_extend_buff (pfile, &pfile->u_buff, len);
510 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
513 /* Leading white space? */
514 if (dest - 1 != BUFF_FRONT (pfile->u_buff))
516 if (source == NULL)
517 source = token;
518 if (source->flags & PREV_WHITE)
519 *dest++ = ' ';
521 source = NULL;
523 if (escape_it)
525 _cpp_buff *buff = _cpp_get_buff (pfile, len);
526 unsigned char *buf = BUFF_FRONT (buff);
527 len = cpp_spell_token (pfile, token, buf, true) - buf;
528 dest = cpp_quote_string (dest, buf, len);
529 _cpp_release_buff (pfile, buff);
531 else
532 dest = cpp_spell_token (pfile, token, dest, true);
534 if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
535 backslash_count++;
536 else
537 backslash_count = 0;
540 /* Ignore the final \ of invalid string literals. */
541 if (backslash_count & 1)
543 cpp_error (pfile, CPP_DL_WARNING,
544 "invalid string literal, ignoring final '\\'");
545 dest--;
548 /* Commit the memory, including NUL, and return the token. */
549 *dest++ = '"';
550 len = dest - BUFF_FRONT (pfile->u_buff);
551 BUFF_FRONT (pfile->u_buff) = dest + 1;
552 return new_string_token (pfile, dest - len, len);
555 /* Try to paste two tokens. On success, return nonzero. In any
556 case, PLHS is updated to point to the pasted token, which is
557 guaranteed to not have the PASTE_LEFT flag set. LOCATION is
558 the virtual location used for error reporting. */
559 static bool
560 paste_tokens (cpp_reader *pfile, source_location location,
561 const cpp_token **plhs, const cpp_token *rhs)
563 unsigned char *buf, *end, *lhsend;
564 cpp_token *lhs;
565 unsigned int len;
567 len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
568 buf = (unsigned char *) alloca (len);
569 end = lhsend = cpp_spell_token (pfile, *plhs, buf, false);
571 /* Avoid comment headers, since they are still processed in stage 3.
572 It is simpler to insert a space here, rather than modifying the
573 lexer to ignore comments in some circumstances. Simply returning
574 false doesn't work, since we want to clear the PASTE_LEFT flag. */
575 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
576 *end++ = ' ';
577 /* In one obscure case we might see padding here. */
578 if (rhs->type != CPP_PADDING)
579 end = cpp_spell_token (pfile, rhs, end, false);
580 *end = '\n';
582 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
583 _cpp_clean_line (pfile);
585 /* Set pfile->cur_token as required by _cpp_lex_direct. */
586 pfile->cur_token = _cpp_temp_token (pfile);
587 lhs = _cpp_lex_direct (pfile);
588 if (pfile->buffer->cur != pfile->buffer->rlimit)
590 source_location saved_loc = lhs->src_loc;
592 _cpp_pop_buffer (pfile);
593 _cpp_backup_tokens (pfile, 1);
594 *lhsend = '\0';
596 /* We have to remove the PASTE_LEFT flag from the old lhs, but
597 we want to keep the new location. */
598 *lhs = **plhs;
599 *plhs = lhs;
600 lhs->src_loc = saved_loc;
601 lhs->flags &= ~PASTE_LEFT;
603 /* Mandatory error for all apart from assembler. */
604 if (CPP_OPTION (pfile, lang) != CLK_ASM)
605 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
606 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
607 buf, cpp_token_as_text (pfile, rhs));
608 return false;
611 *plhs = lhs;
612 _cpp_pop_buffer (pfile);
613 return true;
616 /* Handles an arbitrarily long sequence of ## operators, with initial
617 operand LHS. This implementation is left-associative,
618 non-recursive, and finishes a paste before handling succeeding
619 ones. If a paste fails, we back up to the RHS of the failing ##
620 operator before pushing the context containing the result of prior
621 successful pastes, with the effect that the RHS appears in the
622 output stream after the pasted LHS normally. */
623 static void
624 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
626 const cpp_token *rhs = NULL;
627 cpp_context *context = pfile->context;
628 source_location virt_loc = 0;
630 /* We are expanding a macro and we must have been called on a token
631 that appears at the left hand side of a ## operator. */
632 if (macro_of_context (pfile->context) == NULL
633 || (!(lhs->flags & PASTE_LEFT)))
634 abort ();
636 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
637 /* The caller must have called consume_next_token_from_context
638 right before calling us. That has incremented the pointer to
639 the current virtual location. So it now points to the location
640 of the token that comes right after *LHS. We want the
641 resulting pasted token to have the location of the current
642 *LHS, though. */
643 virt_loc = context->c.mc->cur_virt_loc[-1];
644 else
645 /* We are not tracking macro expansion. So the best virtual
646 location we can get here is the expansion point of the macro we
647 are currently expanding. */
648 virt_loc = pfile->invocation_location;
652 /* Take the token directly from the current context. We can do
653 this, because we are in the replacement list of either an
654 object-like macro, or a function-like macro with arguments
655 inserted. In either case, the constraints to #define
656 guarantee we have at least one more token. */
657 if (context->tokens_kind == TOKENS_KIND_DIRECT)
658 rhs = FIRST (context).token++;
659 else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
660 rhs = *FIRST (context).ptoken++;
661 else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
663 /* So we are in presence of an extended token context, which
664 means that each token in this context has a virtual
665 location attached to it. So let's not forget to update
666 the pointer to the current virtual location of the
667 current token when we update the pointer to the current
668 token */
670 rhs = *FIRST (context).ptoken++;
671 /* context->c.mc must be non-null, as if we were not in a
672 macro context, context->tokens_kind could not be equal to
673 TOKENS_KIND_EXTENDED. */
674 context->c.mc->cur_virt_loc++;
677 if (rhs->type == CPP_PADDING)
679 if (rhs->flags & PASTE_LEFT)
680 abort ();
682 if (!paste_tokens (pfile, virt_loc, &lhs, rhs))
683 break;
685 while (rhs->flags & PASTE_LEFT);
687 /* Put the resulting token in its own context. */
688 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
690 source_location *virt_locs = NULL;
691 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
692 tokens_buff_add_token (token_buf, virt_locs, lhs,
693 virt_loc, 0, NULL, 0);
694 push_extended_tokens_context (pfile, context->c.mc->macro_node,
695 token_buf, virt_locs,
696 (const cpp_token **)token_buf->base, 1);
698 else
699 _cpp_push_token_context (pfile, NULL, lhs, 1);
702 /* Returns TRUE if the number of arguments ARGC supplied in an
703 invocation of the MACRO referenced by NODE is valid. An empty
704 invocation to a macro with no parameters should pass ARGC as zero.
706 Note that MACRO cannot necessarily be deduced from NODE, in case
707 NODE was redefined whilst collecting arguments. */
708 bool
709 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
711 if (argc == macro->paramc)
712 return true;
714 if (argc < macro->paramc)
716 /* As an extension, variadic arguments are allowed to not appear in
717 the invocation at all.
718 e.g. #define debug(format, args...) something
719 debug("string");
721 This is exactly the same as if an empty variadic list had been
722 supplied - debug("string", ). */
724 if (argc + 1 == macro->paramc && macro->variadic)
726 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
728 if (CPP_OPTION (pfile, cplusplus))
729 cpp_error (pfile, CPP_DL_PEDWARN,
730 "ISO C++11 requires at least one argument "
731 "for the \"...\" in a variadic macro");
732 else
733 cpp_error (pfile, CPP_DL_PEDWARN,
734 "ISO C99 requires at least one argument "
735 "for the \"...\" in a variadic macro");
737 return true;
740 cpp_error (pfile, CPP_DL_ERROR,
741 "macro \"%s\" requires %u arguments, but only %u given",
742 NODE_NAME (node), macro->paramc, argc);
744 else
745 cpp_error (pfile, CPP_DL_ERROR,
746 "macro \"%s\" passed %u arguments, but takes just %u",
747 NODE_NAME (node), argc, macro->paramc);
749 return false;
752 /* Reads and returns the arguments to a function-like macro
753 invocation. Assumes the opening parenthesis has been processed.
754 If there is an error, emits an appropriate diagnostic and returns
755 NULL. Each argument is terminated by a CPP_EOF token, for the
756 future benefit of expand_arg(). If there are any deferred
757 #pragma directives among macro arguments, store pointers to the
758 CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
760 What is returned is the buffer that contains the memory allocated
761 to hold the macro arguments. NODE is the name of the macro this
762 function is dealing with. If NUM_ARGS is non-NULL, *NUM_ARGS is
763 set to the actual number of macro arguments allocated in the
764 returned buffer. */
765 static _cpp_buff *
766 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
767 _cpp_buff **pragma_buff, unsigned *num_args)
769 _cpp_buff *buff, *base_buff;
770 cpp_macro *macro;
771 macro_arg *args, *arg;
772 const cpp_token *token;
773 unsigned int argc;
774 source_location virt_loc;
775 bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
776 unsigned num_args_alloced = 0;
778 macro = node->value.macro;
779 if (macro->paramc)
780 argc = macro->paramc;
781 else
782 argc = 1;
784 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
785 #define ARG_TOKENS_EXTENT 1000
787 buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
788 * sizeof (cpp_token *)
789 + sizeof (macro_arg)));
790 base_buff = buff;
791 args = (macro_arg *) buff->base;
792 memset (args, 0, argc * sizeof (macro_arg));
793 buff->cur = (unsigned char *) &args[argc];
794 arg = args, argc = 0;
796 /* Collect the tokens making up each argument. We don't yet know
797 how many arguments have been supplied, whether too many or too
798 few. Hence the slightly bizarre usage of "argc" and "arg". */
801 unsigned int paren_depth = 0;
802 unsigned int ntokens = 0;
803 unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
804 num_args_alloced++;
806 argc++;
807 arg->first = (const cpp_token **) buff->cur;
808 if (track_macro_expansion_p)
810 virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
811 arg->virt_locs = XNEWVEC (source_location,
812 virt_locs_capacity);
815 for (;;)
817 /* Require space for 2 new tokens (including a CPP_EOF). */
818 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
820 buff = _cpp_append_extend_buff (pfile, buff,
821 ARG_TOKENS_EXTENT
822 * sizeof (cpp_token *));
823 arg->first = (const cpp_token **) buff->cur;
825 if (track_macro_expansion_p
826 && (ntokens + 2 > virt_locs_capacity))
828 virt_locs_capacity += ARG_TOKENS_EXTENT;
829 arg->virt_locs = XRESIZEVEC (source_location,
830 arg->virt_locs,
831 virt_locs_capacity);
834 token = cpp_get_token_1 (pfile, &virt_loc);
836 if (token->type == CPP_PADDING)
838 /* Drop leading padding. */
839 if (ntokens == 0)
840 continue;
842 else if (token->type == CPP_OPEN_PAREN)
843 paren_depth++;
844 else if (token->type == CPP_CLOSE_PAREN)
846 if (paren_depth-- == 0)
847 break;
849 else if (token->type == CPP_COMMA)
851 /* A comma does not terminate an argument within
852 parentheses or as part of a variable argument. */
853 if (paren_depth == 0
854 && ! (macro->variadic && argc == macro->paramc))
855 break;
857 else if (token->type == CPP_EOF
858 || (token->type == CPP_HASH && token->flags & BOL))
859 break;
860 else if (token->type == CPP_PRAGMA)
862 cpp_token *newtok = _cpp_temp_token (pfile);
864 /* CPP_PRAGMA token lives in directive_result, which will
865 be overwritten on the next directive. */
866 *newtok = *token;
867 token = newtok;
870 if (*pragma_buff == NULL
871 || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
873 _cpp_buff *next;
874 if (*pragma_buff == NULL)
875 *pragma_buff
876 = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
877 else
879 next = *pragma_buff;
880 *pragma_buff
881 = _cpp_get_buff (pfile,
882 (BUFF_FRONT (*pragma_buff)
883 - (*pragma_buff)->base) * 2);
884 (*pragma_buff)->next = next;
887 *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
888 BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
889 if (token->type == CPP_PRAGMA_EOL)
890 break;
891 token = cpp_get_token_1 (pfile, &virt_loc);
893 while (token->type != CPP_EOF);
895 /* In deferred pragmas parsing_args and prevent_expansion
896 had been changed, reset it. */
897 pfile->state.parsing_args = 2;
898 pfile->state.prevent_expansion = 1;
900 if (token->type == CPP_EOF)
901 break;
902 else
903 continue;
905 set_arg_token (arg, token, virt_loc,
906 ntokens, MACRO_ARG_TOKEN_NORMAL,
907 CPP_OPTION (pfile, track_macro_expansion));
908 ntokens++;
911 /* Drop trailing padding. */
912 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
913 ntokens--;
915 arg->count = ntokens;
916 set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
917 ntokens, MACRO_ARG_TOKEN_NORMAL,
918 CPP_OPTION (pfile, track_macro_expansion));
920 /* Terminate the argument. Excess arguments loop back and
921 overwrite the final legitimate argument, before failing. */
922 if (argc <= macro->paramc)
924 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
925 if (argc != macro->paramc)
926 arg++;
929 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
931 if (token->type == CPP_EOF)
933 /* We still need the CPP_EOF to end directives, and to end
934 pre-expansion of a macro argument. Step back is not
935 unconditional, since we don't want to return a CPP_EOF to our
936 callers at the end of an -include-d file. */
937 if (pfile->context->prev || pfile->state.in_directive)
938 _cpp_backup_tokens (pfile, 1);
939 cpp_error (pfile, CPP_DL_ERROR,
940 "unterminated argument list invoking macro \"%s\"",
941 NODE_NAME (node));
943 else
945 /* A single empty argument is counted as no argument. */
946 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
947 argc = 0;
948 if (_cpp_arguments_ok (pfile, macro, node, argc))
950 /* GCC has special semantics for , ## b where b is a varargs
951 parameter: we remove the comma if b was omitted entirely.
952 If b was merely an empty argument, the comma is retained.
953 If the macro takes just one (varargs) parameter, then we
954 retain the comma only if we are standards conforming.
956 If FIRST is NULL replace_args () swallows the comma. */
957 if (macro->variadic && (argc < macro->paramc
958 || (argc == 1 && args[0].count == 0
959 && !CPP_OPTION (pfile, std))))
960 args[macro->paramc - 1].first = NULL;
961 if (num_args)
962 *num_args = num_args_alloced;
963 return base_buff;
967 /* An error occurred. */
968 _cpp_release_buff (pfile, base_buff);
969 return NULL;
972 /* Search for an opening parenthesis to the macro of NODE, in such a
973 way that, if none is found, we don't lose the information in any
974 intervening padding tokens. If we find the parenthesis, collect
975 the arguments and return the buffer containing them. PRAGMA_BUFF
976 argument is the same as in collect_args. If NUM_ARGS is non-NULL,
977 *NUM_ARGS is set to the number of arguments contained in the
978 returned buffer. */
979 static _cpp_buff *
980 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
981 _cpp_buff **pragma_buff, unsigned *num_args)
983 const cpp_token *token, *padding = NULL;
985 for (;;)
987 token = cpp_get_token (pfile);
988 if (token->type != CPP_PADDING)
989 break;
990 if (padding == NULL
991 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
992 padding = token;
995 if (token->type == CPP_OPEN_PAREN)
997 pfile->state.parsing_args = 2;
998 return collect_args (pfile, node, pragma_buff, num_args);
1001 /* CPP_EOF can be the end of macro arguments, or the end of the
1002 file. We mustn't back up over the latter. Ugh. */
1003 if (token->type != CPP_EOF || token == &pfile->eof)
1005 /* Back up. We may have skipped padding, in which case backing
1006 up more than one token when expanding macros is in general
1007 too difficult. We re-insert it in its own context. */
1008 _cpp_backup_tokens (pfile, 1);
1009 if (padding)
1010 _cpp_push_token_context (pfile, NULL, padding, 1);
1013 return NULL;
1016 /* Return the real number of tokens in the expansion of MACRO. */
1017 static inline unsigned int
1018 macro_real_token_count (const cpp_macro *macro)
1020 unsigned int i;
1021 if (__builtin_expect (!macro->extra_tokens, true))
1022 return macro->count;
1023 for (i = 0; i < macro->count; i++)
1024 if (macro->exp.tokens[i].type == CPP_PASTE)
1025 return i;
1026 abort ();
1029 /* Push the context of a macro with hash entry NODE onto the context
1030 stack. If we can successfully expand the macro, we push a context
1031 containing its yet-to-be-rescanned replacement list and return one.
1032 If there were additionally any unexpanded deferred #pragma
1033 directives among macro arguments, push another context containing
1034 the pragma tokens before the yet-to-be-rescanned replacement list
1035 and return two. Otherwise, we don't push a context and return
1036 zero. LOCATION is the location of the expansion point of the
1037 macro. */
1038 static int
1039 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1040 const cpp_token *result, source_location location)
1042 /* The presence of a macro invalidates a file's controlling macro. */
1043 pfile->mi_valid = false;
1045 pfile->state.angled_headers = false;
1047 /* From here to when we push the context for the macro later down
1048 this function, we need to flag the fact that we are about to
1049 expand a macro. This is useful when -ftrack-macro-expansion is
1050 turned off. In that case, we need to record the location of the
1051 expansion point of the top-most macro we are about to to expand,
1052 into pfile->invocation_location. But we must not record any such
1053 location once the process of expanding the macro starts; that is,
1054 we must not do that recording between now and later down this
1055 function where set this flag to FALSE. */
1056 pfile->about_to_expand_macro_p = true;
1058 if ((node->flags & NODE_BUILTIN) && !(node->flags & NODE_USED))
1060 node->flags |= NODE_USED;
1061 if ((!pfile->cb.user_builtin_macro
1062 || !pfile->cb.user_builtin_macro (pfile, node))
1063 && pfile->cb.used_define)
1064 pfile->cb.used_define (pfile, pfile->directive_line, node);
1067 /* Handle standard macros. */
1068 if (! (node->flags & NODE_BUILTIN))
1070 cpp_macro *macro = node->value.macro;
1071 _cpp_buff *pragma_buff = NULL;
1073 if (macro->fun_like)
1075 _cpp_buff *buff;
1076 unsigned num_args = 0;
1078 pfile->state.prevent_expansion++;
1079 pfile->keep_tokens++;
1080 pfile->state.parsing_args = 1;
1081 buff = funlike_invocation_p (pfile, node, &pragma_buff,
1082 &num_args);
1083 pfile->state.parsing_args = 0;
1084 pfile->keep_tokens--;
1085 pfile->state.prevent_expansion--;
1087 if (buff == NULL)
1089 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1090 cpp_warning (pfile, CPP_W_TRADITIONAL,
1091 "function-like macro \"%s\" must be used with arguments in traditional C",
1092 NODE_NAME (node));
1094 if (pragma_buff)
1095 _cpp_release_buff (pfile, pragma_buff);
1097 pfile->about_to_expand_macro_p = false;
1098 return 0;
1101 if (macro->paramc > 0)
1102 replace_args (pfile, node, macro,
1103 (macro_arg *) buff->base,
1104 location);
1105 /* Free the memory used by the arguments of this
1106 function-like macro. This memory has been allocated by
1107 funlike_invocation_p and by replace_args. */
1108 delete_macro_args (buff, num_args);
1111 /* Disable the macro within its expansion. */
1112 node->flags |= NODE_DISABLED;
1114 if (!(node->flags & NODE_USED))
1116 node->flags |= NODE_USED;
1117 if (pfile->cb.used_define)
1118 pfile->cb.used_define (pfile, pfile->directive_line, node);
1121 if (pfile->cb.used)
1122 pfile->cb.used (pfile, location, node);
1124 macro->used = 1;
1126 if (macro->paramc == 0)
1128 unsigned tokens_count = macro_real_token_count (macro);
1129 if (CPP_OPTION (pfile, track_macro_expansion))
1131 unsigned int i;
1132 const cpp_token *src = macro->exp.tokens;
1133 const struct line_map *map;
1134 source_location *virt_locs = NULL;
1135 _cpp_buff *macro_tokens
1136 = tokens_buff_new (pfile, tokens_count, &virt_locs);
1138 /* Create a macro map to record the locations of the
1139 tokens that are involved in the expansion. LOCATION
1140 is the location of the macro expansion point. */
1141 map = linemap_enter_macro (pfile->line_table,
1142 node, location, tokens_count);
1143 for (i = 0; i < tokens_count; ++i)
1145 tokens_buff_add_token (macro_tokens, virt_locs,
1146 src, src->src_loc,
1147 src->src_loc, map, i);
1148 ++src;
1150 push_extended_tokens_context (pfile, node,
1151 macro_tokens,
1152 virt_locs,
1153 (const cpp_token **)
1154 macro_tokens->base,
1155 tokens_count);
1157 else
1158 _cpp_push_token_context (pfile, node, macro->exp.tokens,
1159 tokens_count);
1160 num_macro_tokens_counter += tokens_count;
1163 if (pragma_buff)
1165 if (!pfile->state.in_directive)
1166 _cpp_push_token_context (pfile, NULL,
1167 padding_token (pfile, result), 1);
1170 unsigned tokens_count;
1171 _cpp_buff *tail = pragma_buff->next;
1172 pragma_buff->next = NULL;
1173 tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1174 - (const cpp_token **) pragma_buff->base);
1175 push_ptoken_context (pfile, NULL, pragma_buff,
1176 (const cpp_token **) pragma_buff->base,
1177 tokens_count);
1178 pragma_buff = tail;
1179 if (!CPP_OPTION (pfile, track_macro_expansion))
1180 num_macro_tokens_counter += tokens_count;
1183 while (pragma_buff != NULL);
1184 pfile->about_to_expand_macro_p = false;
1185 return 2;
1188 pfile->about_to_expand_macro_p = false;
1189 return 1;
1192 pfile->about_to_expand_macro_p = false;
1193 /* Handle built-in macros and the _Pragma operator. */
1194 return builtin_macro (pfile, node);
1197 /* De-allocate the memory used by BUFF which is an array of instances
1198 of macro_arg. NUM_ARGS is the number of instances of macro_arg
1199 present in BUFF. */
1200 static void
1201 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1203 macro_arg *macro_args;
1204 unsigned i;
1206 if (buff == NULL)
1207 return;
1209 macro_args = (macro_arg *) buff->base;
1211 /* Walk instances of macro_arg to free their expanded tokens as well
1212 as their macro_arg::virt_locs members. */
1213 for (i = 0; i < num_args; ++i)
1215 if (macro_args[i].expanded)
1217 free (macro_args[i].expanded);
1218 macro_args[i].expanded = NULL;
1220 if (macro_args[i].virt_locs)
1222 free (macro_args[i].virt_locs);
1223 macro_args[i].virt_locs = NULL;
1225 if (macro_args[i].expanded_virt_locs)
1227 free (macro_args[i].expanded_virt_locs);
1228 macro_args[i].expanded_virt_locs = NULL;
1231 _cpp_free_buff (buff);
1234 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1235 to set, LOCATION is its virtual location. "Virtual" location means
1236 the location that encodes loci across macro expansion. Otherwise
1237 it has to be TOKEN->SRC_LOC. KIND is the kind of tokens the
1238 argument ARG is supposed to contain. Note that ARG must be
1239 tailored so that it has enough room to contain INDEX + 1 numbers of
1240 tokens, at least. */
1241 static void
1242 set_arg_token (macro_arg *arg, const cpp_token *token,
1243 source_location location, size_t index,
1244 enum macro_arg_token_kind kind,
1245 bool track_macro_exp_p)
1247 const cpp_token **token_ptr;
1248 source_location *loc = NULL;
1250 token_ptr =
1251 arg_token_ptr_at (arg, index, kind,
1252 track_macro_exp_p ? &loc : NULL);
1253 *token_ptr = token;
1255 if (loc != NULL)
1257 #ifdef ENABLE_CHECKING
1258 if (kind == MACRO_ARG_TOKEN_STRINGIFIED
1259 || !track_macro_exp_p)
1260 /* We can't set the location of a stringified argument
1261 token and we can't set any location if we aren't tracking
1262 macro expansion locations. */
1263 abort ();
1264 #endif
1265 *loc = location;
1269 /* Get the pointer to the location of the argument token of the
1270 function-like macro argument ARG. This function must be called
1271 only when we -ftrack-macro-expansion is on. */
1272 static const source_location *
1273 get_arg_token_location (const macro_arg *arg,
1274 enum macro_arg_token_kind kind)
1276 const source_location *loc = NULL;
1277 const cpp_token **token_ptr =
1278 arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1280 if (token_ptr == NULL)
1281 return NULL;
1283 return loc;
1286 /* Return the pointer to the INDEXth token of the macro argument ARG.
1287 KIND specifies the kind of token the macro argument ARG contains.
1288 If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1289 of the virtual location of the returned token if the
1290 -ftrack-macro-expansion flag is on; otherwise, it's set to the
1291 spelling location of the returned token. */
1292 static const cpp_token **
1293 arg_token_ptr_at (const macro_arg *arg, size_t index,
1294 enum macro_arg_token_kind kind,
1295 source_location **virt_location)
1297 const cpp_token **tokens_ptr = NULL;
1299 switch (kind)
1301 case MACRO_ARG_TOKEN_NORMAL:
1302 tokens_ptr = arg->first;
1303 break;
1304 case MACRO_ARG_TOKEN_STRINGIFIED:
1305 tokens_ptr = (const cpp_token **) &arg->stringified;
1306 break;
1307 case MACRO_ARG_TOKEN_EXPANDED:
1308 tokens_ptr = arg->expanded;
1309 break;
1312 if (tokens_ptr == NULL)
1313 /* This can happen for e.g, an empty token argument to a
1314 funtion-like macro. */
1315 return tokens_ptr;
1317 if (virt_location)
1319 if (kind == MACRO_ARG_TOKEN_NORMAL)
1320 *virt_location = &arg->virt_locs[index];
1321 else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1322 *virt_location = &arg->expanded_virt_locs[index];
1323 else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1324 *virt_location =
1325 (source_location *) &tokens_ptr[index]->src_loc;
1327 return &tokens_ptr[index];
1330 /* Initialize an iterator so that it iterates over the tokens of a
1331 function-like macro argument. KIND is the kind of tokens we want
1332 ITER to iterate over. TOKEN_PTR points the first token ITER will
1333 iterate over. */
1334 static void
1335 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1336 bool track_macro_exp_p,
1337 enum macro_arg_token_kind kind,
1338 const macro_arg *arg,
1339 const cpp_token **token_ptr)
1341 iter->track_macro_exp_p = track_macro_exp_p;
1342 iter->kind = kind;
1343 iter->token_ptr = token_ptr;
1344 /* Unconditionally initialize this so that the compiler doesn't warn
1345 about iter->location_ptr being possibly uninitialized later after
1346 this code has been inlined somewhere. */
1347 iter->location_ptr = NULL;
1348 if (track_macro_exp_p)
1349 iter->location_ptr = get_arg_token_location (arg, kind);
1350 #ifdef ENABLE_CHECKING
1351 iter->num_forwards = 0;
1352 if (track_macro_exp_p
1353 && token_ptr != NULL
1354 && iter->location_ptr == NULL)
1355 abort ();
1356 #endif
1359 /* Move the iterator one token forward. Note that if IT was
1360 initialized on an argument that has a stringified token, moving it
1361 forward doesn't make sense as a stringified token is essentially one
1362 string. */
1363 static void
1364 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1366 switch (it->kind)
1368 case MACRO_ARG_TOKEN_NORMAL:
1369 case MACRO_ARG_TOKEN_EXPANDED:
1370 it->token_ptr++;
1371 if (it->track_macro_exp_p)
1372 it->location_ptr++;
1373 break;
1374 case MACRO_ARG_TOKEN_STRINGIFIED:
1375 #ifdef ENABLE_CHECKING
1376 if (it->num_forwards > 0)
1377 abort ();
1378 #endif
1379 break;
1382 #ifdef ENABLE_CHECKING
1383 it->num_forwards++;
1384 #endif
1387 /* Return the token pointed to by the iterator. */
1388 static const cpp_token *
1389 macro_arg_token_iter_get_token (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->token_ptr == NULL)
1397 return NULL;
1398 return *it->token_ptr;
1401 /* Return the location of the token pointed to by the iterator.*/
1402 static source_location
1403 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1405 #ifdef ENABLE_CHECKING
1406 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1407 && it->num_forwards > 0)
1408 abort ();
1409 #endif
1410 if (it->track_macro_exp_p)
1411 return *it->location_ptr;
1412 else
1413 return (*it->token_ptr)->src_loc;
1416 /* Return the index of a token [resulting from macro expansion] inside
1417 the total list of tokens resulting from a given macro
1418 expansion. The index can be different depending on whether if we
1419 want each tokens resulting from function-like macro arguments
1420 expansion to have a different location or not.
1422 E.g, consider this function-like macro:
1424 #define M(x) x - 3
1426 Then consider us "calling" it (and thus expanding it) like:
1428 M(1+4)
1430 It will be expanded into:
1432 1+4-3
1434 Let's consider the case of the token '4'.
1436 Its index can be 2 (it's the third token of the set of tokens
1437 resulting from the expansion) or it can be 0 if we consider that
1438 all tokens resulting from the expansion of the argument "1+2" have
1439 the same index, which is 0. In this later case, the index of token
1440 '-' would then be 1 and the index of token '3' would be 2.
1442 The later case is useful to use less memory e.g, for the case of
1443 the user using the option -ftrack-macro-expansion=1.
1445 ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1446 are interested in. CUR_REPLACEMENT_TOKEN is the token of the macro
1447 parameter (inside the macro replacement list) that corresponds to
1448 the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1451 If we refer to the example above, for the '4' argument token,
1452 ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1453 would be set to the token 'x', in the replacement list "x - 3" of
1454 macro M.
1456 This is a subroutine of replace_args. */
1457 inline static unsigned
1458 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1459 const cpp_token *cur_replacement_token,
1460 unsigned absolute_token_index)
1462 if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1463 return absolute_token_index;
1464 return cur_replacement_token - macro->exp.tokens;
1467 /* Replace the parameters in a function-like macro of NODE with the
1468 actual ARGS, and place the result in a newly pushed token context.
1469 Expand each argument before replacing, unless it is operated upon
1470 by the # or ## operators. EXPANSION_POINT_LOC is the location of
1471 the expansion point of the macro. E.g, the location of the
1472 function-like macro invocation. */
1473 static void
1474 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1475 macro_arg *args, source_location expansion_point_loc)
1477 unsigned int i, total;
1478 const cpp_token *src, *limit;
1479 const cpp_token **first = NULL;
1480 macro_arg *arg;
1481 _cpp_buff *buff = NULL;
1482 source_location *virt_locs = NULL;
1483 unsigned int exp_count;
1484 const struct line_map *map = NULL;
1485 int track_macro_exp;
1487 /* First, fully macro-expand arguments, calculating the number of
1488 tokens in the final expansion as we go. The ordering of the if
1489 statements below is subtle; we must handle stringification before
1490 pasting. */
1492 /* EXP_COUNT is the number of tokens in the macro replacement
1493 list. TOTAL is the number of tokens /after/ macro parameters
1494 have been replaced by their arguments. */
1495 exp_count = macro_real_token_count (macro);
1496 total = exp_count;
1497 limit = macro->exp.tokens + exp_count;
1499 for (src = macro->exp.tokens; src < limit; src++)
1500 if (src->type == CPP_MACRO_ARG)
1502 /* Leading and trailing padding tokens. */
1503 total += 2;
1504 /* Account for leading and padding tokens in exp_count too.
1505 This is going to be important later down this function,
1506 when we want to handle the case of (track_macro_exp <
1507 2). */
1508 exp_count += 2;
1510 /* We have an argument. If it is not being stringified or
1511 pasted it is macro-replaced before insertion. */
1512 arg = &args[src->val.macro_arg.arg_no - 1];
1514 if (src->flags & STRINGIFY_ARG)
1516 if (!arg->stringified)
1517 arg->stringified = stringify_arg (pfile, arg);
1519 else if ((src->flags & PASTE_LEFT)
1520 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1521 total += arg->count - 1;
1522 else
1524 if (!arg->expanded)
1525 expand_arg (pfile, arg);
1526 total += arg->expanded_count - 1;
1530 /* When the compiler is called with the -ftrack-macro-expansion
1531 flag, we need to keep track of the location of each token that
1532 results from macro expansion.
1534 A token resulting from macro expansion is not a new token. It is
1535 simply the same token as the token coming from the macro
1536 definition. The new things that are allocated are the buffer
1537 that holds the tokens resulting from macro expansion and a new
1538 location that records many things like the locus of the expansion
1539 point as well as the original locus inside the definition of the
1540 macro. This location is called a virtual location.
1542 So the buffer BUFF holds a set of cpp_token*, and the buffer
1543 VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1545 Both of these two buffers are going to be hung off of the macro
1546 context, when the latter is pushed. The memory allocated to
1547 store the tokens and their locations is going to be freed once
1548 the context of macro expansion is popped.
1550 As far as tokens are concerned, the memory overhead of
1551 -ftrack-macro-expansion is proportional to the number of
1552 macros that get expanded multiplied by sizeof (source_location).
1553 The good news is that extra memory gets freed when the macro
1554 context is freed, i.e shortly after the macro got expanded. */
1556 /* Is the -ftrack-macro-expansion flag in effect? */
1557 track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1559 /* Now allocate memory space for tokens and locations resulting from
1560 the macro expansion, copy the tokens and replace the arguments.
1561 This memory must be freed when the context of the macro MACRO is
1562 popped. */
1563 buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1565 first = (const cpp_token **) buff->base;
1567 /* Create a macro map to record the locations of the tokens that are
1568 involved in the expansion. Note that the expansion point is set
1569 to the location of the closing parenthesis. Otherwise, the
1570 subsequent map created for the first token that comes after the
1571 macro map might have a wrong line number. That would lead to
1572 tokens with wrong line numbers after the macro expansion. This
1573 adds up to the memory overhead of the -ftrack-macro-expansion
1574 flag; for every macro that is expanded, a "macro map" is
1575 created. */
1576 if (track_macro_exp)
1578 int num_macro_tokens = total;
1579 if (track_macro_exp < 2)
1580 /* Then the number of macro tokens won't take in account the
1581 fact that function-like macro arguments can expand to
1582 multiple tokens. This is to save memory at the expense of
1583 accuracy.
1585 Suppose we have #define SQARE(A) A * A
1587 And then we do SQARE(2+3)
1589 Then the tokens 2, +, 3, will have the same location,
1590 saying they come from the expansion of the argument A. */
1591 num_macro_tokens = exp_count;
1592 map = linemap_enter_macro (pfile->line_table, node,
1593 expansion_point_loc,
1594 num_macro_tokens);
1596 i = 0;
1597 for (src = macro->exp.tokens; src < limit; src++)
1599 unsigned int arg_tokens_count;
1600 macro_arg_token_iter from;
1601 const cpp_token **paste_flag = NULL;
1602 const cpp_token **tmp_token_ptr;
1604 if (src->type != CPP_MACRO_ARG)
1606 /* Allocate a virtual location for token SRC, and add that
1607 token and its virtual location into the buffers BUFF and
1608 VIRT_LOCS. */
1609 unsigned index = expanded_token_index (pfile, macro, src, i);
1610 tokens_buff_add_token (buff, virt_locs, src,
1611 src->src_loc, src->src_loc,
1612 map, index);
1613 i += 1;
1614 continue;
1617 paste_flag = 0;
1618 arg = &args[src->val.macro_arg.arg_no - 1];
1619 /* SRC is a macro parameter that we need to replace with its
1620 corresponding argument. So at some point we'll need to
1621 iterate over the tokens of the macro argument and copy them
1622 into the "place" now holding the correspondig macro
1623 parameter. We are going to use the iterator type
1624 macro_argo_token_iter to handle that iterating. The 'if'
1625 below is to initialize the iterator depending on the type of
1626 tokens the macro argument has. It also does some adjustment
1627 related to padding tokens and some pasting corner cases. */
1628 if (src->flags & STRINGIFY_ARG)
1630 arg_tokens_count = 1;
1631 macro_arg_token_iter_init (&from,
1632 CPP_OPTION (pfile,
1633 track_macro_expansion),
1634 MACRO_ARG_TOKEN_STRINGIFIED,
1635 arg, &arg->stringified);
1637 else if (src->flags & PASTE_LEFT)
1639 arg_tokens_count = arg->count;
1640 macro_arg_token_iter_init (&from,
1641 CPP_OPTION (pfile,
1642 track_macro_expansion),
1643 MACRO_ARG_TOKEN_NORMAL,
1644 arg, arg->first);
1646 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1648 int num_toks;
1649 arg_tokens_count = arg->count;
1650 macro_arg_token_iter_init (&from,
1651 CPP_OPTION (pfile,
1652 track_macro_expansion),
1653 MACRO_ARG_TOKEN_NORMAL,
1654 arg, arg->first);
1656 num_toks = tokens_buff_count (buff);
1658 if (num_toks != 0)
1660 /* So the current parameter token is pasted to the previous
1661 token in the replacement list. Let's look at what
1662 we have as previous and current arguments. */
1664 /* This is the previous argument's token ... */
1665 tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1667 if ((*tmp_token_ptr)->type == CPP_COMMA
1668 && macro->variadic
1669 && src->val.macro_arg.arg_no == macro->paramc)
1671 /* ... which is a comma; and the current parameter
1672 is the last parameter of a variadic function-like
1673 macro. If the argument to the current last
1674 parameter is NULL, then swallow the comma,
1675 otherwise drop the paste flag. */
1676 if (macro_arg_token_iter_get_token (&from) == NULL)
1677 tokens_buff_remove_last_token (buff);
1678 else
1679 paste_flag = tmp_token_ptr;
1681 /* Remove the paste flag if the RHS is a placemarker. */
1682 else if (arg_tokens_count == 0)
1683 paste_flag = tmp_token_ptr;
1686 else
1688 arg_tokens_count = arg->expanded_count;
1689 macro_arg_token_iter_init (&from,
1690 CPP_OPTION (pfile,
1691 track_macro_expansion),
1692 MACRO_ARG_TOKEN_EXPANDED,
1693 arg, arg->expanded);
1696 /* Padding on the left of an argument (unless RHS of ##). */
1697 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1698 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1700 const cpp_token *t = padding_token (pfile, src);
1701 unsigned index = expanded_token_index (pfile, macro, src, i);
1702 /* Allocate a virtual location for the padding token and
1703 append the token and its location to BUFF and
1704 VIRT_LOCS. */
1705 tokens_buff_add_token (buff, virt_locs, t,
1706 t->src_loc, t->src_loc,
1707 map, index);
1710 if (arg_tokens_count)
1712 /* So now we've got the number of tokens that make up the
1713 argument that is going to replace the current parameter
1714 in the macro's replacement list. */
1715 unsigned int j;
1716 for (j = 0; j < arg_tokens_count; ++j)
1718 /* So if track_macro_exp is < 2, the user wants to
1719 save extra memory while tracking macro expansion
1720 locations. So in that case here is what we do:
1722 Suppose we have #define SQARE(A) A * A
1724 And then we do SQARE(2+3)
1726 Then the tokens 2, +, 3, will have the same location,
1727 saying they come from the expansion of the argument
1730 So that means we are going to ignore the COUNT tokens
1731 resulting from the expansion of the current macro
1732 arugment. In other words all the ARG_TOKENS_COUNT tokens
1733 resulting from the expansion of the macro argument will
1734 have the index I. Normally, each of those token should
1735 have index I+J. */
1736 unsigned token_index = i;
1737 unsigned index;
1738 if (track_macro_exp > 1)
1739 token_index += j;
1741 index = expanded_token_index (pfile, macro, src, token_index);
1742 tokens_buff_add_token (buff, virt_locs,
1743 macro_arg_token_iter_get_token (&from),
1744 macro_arg_token_iter_get_location (&from),
1745 src->src_loc, map, index);
1746 macro_arg_token_iter_forward (&from);
1749 /* With a non-empty argument on the LHS of ##, the last
1750 token should be flagged PASTE_LEFT. */
1751 if (src->flags & PASTE_LEFT)
1752 paste_flag =
1753 (const cpp_token **) tokens_buff_last_token_ptr (buff);
1755 else if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1756 && ! CPP_OPTION (pfile, c99)
1757 && ! cpp_in_system_header (pfile))
1759 if (CPP_OPTION (pfile, cplusplus))
1760 cpp_error (pfile, CPP_DL_PEDWARN,
1761 "invoking macro %s argument %d: "
1762 "empty macro arguments are undefined"
1763 " in ISO C++98",
1764 NODE_NAME (node),
1765 src->val.macro_arg.arg_no);
1766 else
1767 cpp_error (pfile, CPP_DL_PEDWARN,
1768 "invoking macro %s argument %d: "
1769 "empty macro arguments are undefined"
1770 " in ISO C90",
1771 NODE_NAME (node),
1772 src->val.macro_arg.arg_no);
1775 /* Avoid paste on RHS (even case count == 0). */
1776 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
1778 const cpp_token *t = &pfile->avoid_paste;
1779 tokens_buff_add_token (buff, virt_locs,
1780 t, t->src_loc, t->src_loc,
1781 NULL, 0);
1784 /* Add a new paste flag, or remove an unwanted one. */
1785 if (paste_flag)
1787 cpp_token *token = _cpp_temp_token (pfile);
1788 token->type = (*paste_flag)->type;
1789 token->val = (*paste_flag)->val;
1790 if (src->flags & PASTE_LEFT)
1791 token->flags = (*paste_flag)->flags | PASTE_LEFT;
1792 else
1793 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1794 *paste_flag = token;
1797 i += arg_tokens_count;
1800 if (track_macro_exp)
1801 push_extended_tokens_context (pfile, node, buff, virt_locs, first,
1802 tokens_buff_count (buff));
1803 else
1804 push_ptoken_context (pfile, node, buff, first,
1805 tokens_buff_count (buff));
1807 num_macro_tokens_counter += tokens_buff_count (buff);
1810 /* Return a special padding token, with padding inherited from SOURCE. */
1811 static const cpp_token *
1812 padding_token (cpp_reader *pfile, const cpp_token *source)
1814 cpp_token *result = _cpp_temp_token (pfile);
1816 result->type = CPP_PADDING;
1818 /* Data in GCed data structures cannot be made const so far, so we
1819 need a cast here. */
1820 result->val.source = (cpp_token *) source;
1821 result->flags = 0;
1822 return result;
1825 /* Get a new uninitialized context. Create a new one if we cannot
1826 re-use an old one. */
1827 static cpp_context *
1828 next_context (cpp_reader *pfile)
1830 cpp_context *result = pfile->context->next;
1832 if (result == 0)
1834 result = XNEW (cpp_context);
1835 memset (result, 0, sizeof (cpp_context));
1836 result->prev = pfile->context;
1837 result->next = 0;
1838 pfile->context->next = result;
1841 pfile->context = result;
1842 return result;
1845 /* Push a list of pointers to tokens. */
1846 static void
1847 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
1848 const cpp_token **first, unsigned int count)
1850 cpp_context *context = next_context (pfile);
1852 context->tokens_kind = TOKENS_KIND_INDIRECT;
1853 context->c.macro = macro;
1854 context->buff = buff;
1855 FIRST (context).ptoken = first;
1856 LAST (context).ptoken = first + count;
1859 /* Push a list of tokens.
1861 A NULL macro means that we should continue the current macro
1862 expansion, in essence. That means that if we are currently in a
1863 macro expansion context, we'll make the new pfile->context refer to
1864 the current macro. */
1865 void
1866 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
1867 const cpp_token *first, unsigned int count)
1869 cpp_context *context;
1871 if (macro == NULL)
1872 macro = macro_of_context (pfile->context);
1874 context = next_context (pfile);
1875 context->tokens_kind = TOKENS_KIND_DIRECT;
1876 context->c.macro = macro;
1877 context->buff = NULL;
1878 FIRST (context).token = first;
1879 LAST (context).token = first + count;
1882 /* Build a context containing a list of tokens as well as their
1883 virtual locations and push it. TOKENS_BUFF is the buffer that
1884 contains the tokens pointed to by FIRST. If TOKENS_BUFF is
1885 non-NULL, it means that the context owns it, meaning that
1886 _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
1887 contains the virtual locations.
1889 A NULL macro means that we should continue the current macro
1890 expansion, in essence. That means that if we are currently in a
1891 macro expansion context, we'll make the new pfile->context refer to
1892 the current macro. */
1893 static void
1894 push_extended_tokens_context (cpp_reader *pfile,
1895 cpp_hashnode *macro,
1896 _cpp_buff *token_buff,
1897 source_location *virt_locs,
1898 const cpp_token **first,
1899 unsigned int count)
1901 cpp_context *context;
1902 macro_context *m;
1904 if (macro == NULL)
1905 macro = macro_of_context (pfile->context);
1907 context = next_context (pfile);
1908 context->tokens_kind = TOKENS_KIND_EXTENDED;
1909 context->buff = token_buff;
1911 m = XNEW (macro_context);
1912 m->macro_node = macro;
1913 m->virt_locs = virt_locs;
1914 m->cur_virt_loc = virt_locs;
1915 context->c.mc = m;
1916 FIRST (context).ptoken = first;
1917 LAST (context).ptoken = first + count;
1920 /* Push a traditional macro's replacement text. */
1921 void
1922 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
1923 const uchar *start, size_t len)
1925 cpp_context *context = next_context (pfile);
1927 context->tokens_kind = TOKENS_KIND_DIRECT;
1928 context->c.macro = macro;
1929 context->buff = NULL;
1930 CUR (context) = start;
1931 RLIMIT (context) = start + len;
1932 macro->flags |= NODE_DISABLED;
1935 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
1936 for the purpose of storing them on a cpp_context. If VIRT_LOCS is
1937 non-null (which means that -ftrack-macro-expansion is on),
1938 *VIRT_LOCS is set to a newly allocated buffer that is supposed to
1939 hold the virtual locations of the tokens resulting from macro
1940 expansion. */
1941 static _cpp_buff*
1942 tokens_buff_new (cpp_reader *pfile, size_t len,
1943 source_location **virt_locs)
1945 size_t tokens_size = len * sizeof (cpp_token *);
1946 size_t locs_size = len * sizeof (source_location);
1948 if (virt_locs != NULL)
1949 *virt_locs = XNEWVEC (source_location, locs_size);
1950 return _cpp_get_buff (pfile, tokens_size);
1953 /* Returns the number of tokens contained in a token buffer. The
1954 buffer holds a set of cpp_token*. */
1955 static size_t
1956 tokens_buff_count (_cpp_buff *buff)
1958 return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
1961 /* Return a pointer to the last token contained in the token buffer
1962 BUFF. */
1963 static const cpp_token **
1964 tokens_buff_last_token_ptr (_cpp_buff *buff)
1966 return &((const cpp_token **) BUFF_FRONT (buff))[-1];
1969 /* Remove the last token contained in the token buffer TOKENS_BUFF.
1970 If VIRT_LOCS_BUFF is non-NULL, it should point at the buffer
1971 containing the virtual locations of the tokens in TOKENS_BUFF; in
1972 which case the function updates that buffer as well. */
1973 static inline void
1974 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
1977 if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
1978 BUFF_FRONT (tokens_buff) =
1979 (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
1982 /* Insert a token into the token buffer at the position pointed to by
1983 DEST. Note that the buffer is not enlarged so the previous token
1984 that was at *DEST is overwritten. VIRT_LOC_DEST, if non-null,
1985 means -ftrack-macro-expansion is effect; it then points to where to
1986 insert the virtual location of TOKEN. TOKEN is the token to
1987 insert. VIRT_LOC is the virtual location of the token, i.e, the
1988 location possibly encoding its locus across macro expansion. If
1989 TOKEN is an argument of a function-like macro (inside a macro
1990 replacement list), PARM_DEF_LOC is the spelling location of the
1991 macro parameter that TOKEN is replacing, in the replacement list of
1992 the macro. If TOKEN is not an argument of a function-like macro or
1993 if it doesn't come from a macro expansion, then VIRT_LOC can just
1994 be set to the same value as PARM_DEF_LOC. If MAP is non null, it
1995 means TOKEN comes from a macro expansion and MAP is the macro map
1996 associated to the macro. MACRO_TOKEN_INDEX points to the index of
1997 the token in the macro map; it is not considered if MAP is NULL.
1999 Upon successful completion this function returns the a pointer to
2000 the position of the token coming right after the insertion
2001 point. */
2002 static inline const cpp_token **
2003 tokens_buff_put_token_to (const cpp_token **dest,
2004 source_location *virt_loc_dest,
2005 const cpp_token *token,
2006 source_location virt_loc,
2007 source_location parm_def_loc,
2008 const struct line_map *map,
2009 unsigned int macro_token_index)
2011 source_location macro_loc = virt_loc;
2012 const cpp_token **result;
2014 if (virt_loc_dest)
2016 /* -ftrack-macro-expansion is on. */
2017 if (map)
2018 macro_loc = linemap_add_macro_token (map, macro_token_index,
2019 virt_loc, parm_def_loc);
2020 *virt_loc_dest = macro_loc;
2022 *dest = token;
2023 result = &dest[1];
2025 return result;
2028 /* Adds a token at the end of the tokens contained in BUFFER. Note
2029 that this function doesn't enlarge BUFFER when the number of tokens
2030 reaches BUFFER's size; it aborts in that situation.
2032 TOKEN is the token to append. VIRT_LOC is the virtual location of
2033 the token, i.e, the location possibly encoding its locus across
2034 macro expansion. If TOKEN is an argument of a function-like macro
2035 (inside a macro replacement list), PARM_DEF_LOC is the location of
2036 the macro parameter that TOKEN is replacing. If TOKEN doesn't come
2037 from a macro expansion, then VIRT_LOC can just be set to the same
2038 value as PARM_DEF_LOC. If MAP is non null, it means TOKEN comes
2039 from a macro expansion and MAP is the macro map associated to the
2040 macro. MACRO_TOKEN_INDEX points to the index of the token in the
2041 macro map; It is not considered if MAP is NULL. If VIRT_LOCS is
2042 non-null, it means -ftrack-macro-expansion is on; in which case
2043 this function adds the virtual location DEF_LOC to the VIRT_LOCS
2044 array, at the same index as the one of TOKEN in BUFFER. Upon
2045 successful completion this function returns the a pointer to the
2046 position of the token coming right after the insertion point. */
2047 static const cpp_token **
2048 tokens_buff_add_token (_cpp_buff *buffer,
2049 source_location *virt_locs,
2050 const cpp_token *token,
2051 source_location virt_loc,
2052 source_location parm_def_loc,
2053 const struct line_map *map,
2054 unsigned int macro_token_index)
2056 const cpp_token **result;
2057 source_location *virt_loc_dest = NULL;
2058 unsigned token_index =
2059 (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2061 /* Abort if we pass the end the buffer. */
2062 if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2063 abort ();
2065 if (virt_locs != NULL)
2066 virt_loc_dest = &virt_locs[token_index];
2068 result =
2069 tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2070 virt_loc_dest, token, virt_loc, parm_def_loc,
2071 map, macro_token_index);
2073 BUFF_FRONT (buffer) = (unsigned char *) result;
2074 return result;
2077 /* Allocate space for the function-like macro argument ARG to store
2078 the tokens resulting from the macro-expansion of the tokens that
2079 make up ARG itself. That space is allocated in ARG->expanded and
2080 needs to be freed using free. */
2081 static void
2082 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2084 #ifdef ENABLE_CHECKING
2085 if (arg->expanded != NULL
2086 || arg->expanded_virt_locs != NULL)
2087 abort ();
2088 #endif
2089 arg->expanded = XNEWVEC (const cpp_token *, capacity);
2090 if (CPP_OPTION (pfile, track_macro_expansion))
2091 arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2095 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2096 tokens. */
2097 static void
2098 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2099 size_t size, size_t *expanded_capacity)
2101 if (size <= *expanded_capacity)
2102 return;
2104 size *= 2;
2106 arg->expanded =
2107 XRESIZEVEC (const cpp_token *, arg->expanded, size);
2108 *expanded_capacity = size;
2110 if (CPP_OPTION (pfile, track_macro_expansion))
2112 if (arg->expanded_virt_locs == NULL)
2113 arg->expanded_virt_locs = XNEWVEC (source_location, size);
2114 else
2115 arg->expanded_virt_locs = XRESIZEVEC (source_location,
2116 arg->expanded_virt_locs,
2117 size);
2121 /* Expand an argument ARG before replacing parameters in a
2122 function-like macro. This works by pushing a context with the
2123 argument's tokens, and then expanding that into a temporary buffer
2124 as if it were a normal part of the token stream. collect_args()
2125 has terminated the argument's tokens with a CPP_EOF so that we know
2126 when we have fully expanded the argument. */
2127 static void
2128 expand_arg (cpp_reader *pfile, macro_arg *arg)
2130 size_t capacity;
2131 bool saved_warn_trad;
2132 bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2134 if (arg->count == 0
2135 || arg->expanded != NULL)
2136 return;
2138 /* Don't warn about funlike macros when pre-expanding. */
2139 saved_warn_trad = CPP_WTRADITIONAL (pfile);
2140 CPP_WTRADITIONAL (pfile) = 0;
2142 /* Loop, reading in the tokens of the argument. */
2143 capacity = 256;
2144 alloc_expanded_arg_mem (pfile, arg, capacity);
2146 if (track_macro_exp_p)
2147 push_extended_tokens_context (pfile, NULL, NULL,
2148 arg->virt_locs,
2149 arg->first,
2150 arg->count + 1);
2151 else
2152 push_ptoken_context (pfile, NULL, NULL,
2153 arg->first, arg->count + 1);
2155 for (;;)
2157 const cpp_token *token;
2158 source_location location;
2160 ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2161 &capacity);
2163 token = cpp_get_token_1 (pfile, &location);
2165 if (token->type == CPP_EOF)
2166 break;
2168 set_arg_token (arg, token, location,
2169 arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2170 CPP_OPTION (pfile, track_macro_expansion));
2171 arg->expanded_count++;
2174 _cpp_pop_context (pfile);
2176 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2179 /* Returns the macro associated to the current context if we are in
2180 the context a macro expansion, NULL otherwise. */
2181 static cpp_hashnode*
2182 macro_of_context (cpp_context *context)
2184 if (context == NULL)
2185 return NULL;
2187 return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2188 ? context->c.mc->macro_node
2189 : context->c.macro;
2192 /* Return TRUE iff we are expanding a macro or are about to start
2193 expanding one. If we are effectively expanding a macro, the
2194 function macro_of_context returns a pointer to the macro being
2195 expanded. */
2196 static bool
2197 in_macro_expansion_p (cpp_reader *pfile)
2199 if (pfile == NULL)
2200 return false;
2202 return (pfile->about_to_expand_macro_p
2203 || macro_of_context (pfile->context));
2206 /* Pop the current context off the stack, re-enabling the macro if the
2207 context represented a macro's replacement list. Initially the
2208 context structure was not freed so that we can re-use it later, but
2209 now we do free it to reduce peak memory consumption. */
2210 void
2211 _cpp_pop_context (cpp_reader *pfile)
2213 cpp_context *context = pfile->context;
2215 /* We should not be popping the base context. */
2216 if (context == &pfile->base_context)
2217 abort ();
2219 if (context->c.macro)
2221 cpp_hashnode *macro;
2222 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2224 macro_context *mc = context->c.mc;
2225 macro = mc->macro_node;
2226 /* If context->buff is set, it means the life time of tokens
2227 is bound to the life time of this context; so we must
2228 free the tokens; that means we must free the virtual
2229 locations of these tokens too. */
2230 if (context->buff && mc->virt_locs)
2232 free (mc->virt_locs);
2233 mc->virt_locs = NULL;
2235 free (mc);
2236 context->c.mc = NULL;
2238 else
2239 macro = context->c.macro;
2241 /* Beware that MACRO can be NULL in cases like when we are
2242 called from expand_arg. In those cases, a dummy context with
2243 tokens is pushed just for the purpose of walking them using
2244 cpp_get_token_1. In that case, no 'macro' field is set into
2245 the dummy context. */
2246 if (macro != NULL
2247 /* Several contiguous macro expansion contexts can be
2248 associated to the same macro; that means it's the same
2249 macro expansion that spans across all these (sub)
2250 contexts. So we should re-enable an expansion-disabled
2251 macro only when we are sure we are really out of that
2252 macro expansion. */
2253 && macro_of_context (context->prev) != macro)
2254 macro->flags &= ~NODE_DISABLED;
2257 if (context->buff)
2259 /* Decrease memory peak consumption by freeing the memory used
2260 by the context. */
2261 _cpp_free_buff (context->buff);
2264 pfile->context = context->prev;
2265 /* decrease peak memory consumption by feeing the context. */
2266 pfile->context->next = NULL;
2267 free (context);
2270 /* Return TRUE if we reached the end of the set of tokens stored in
2271 CONTEXT, FALSE otherwise. */
2272 static inline bool
2273 reached_end_of_context (cpp_context *context)
2275 if (context->tokens_kind == TOKENS_KIND_DIRECT)
2276 return FIRST (context).token == LAST (context).token;
2277 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2278 || context->tokens_kind == TOKENS_KIND_EXTENDED)
2279 return FIRST (context).ptoken == LAST (context).ptoken;
2280 else
2281 abort ();
2284 /* Consume the next token contained in the current context of PFILE,
2285 and return it in *TOKEN. It's "full location" is returned in
2286 *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2287 means the location encoding the locus of the token across macro
2288 expansion; otherwise it's just is the "normal" location of the
2289 token which (*TOKEN)->src_loc. */
2290 static inline void
2291 consume_next_token_from_context (cpp_reader *pfile,
2292 const cpp_token ** token,
2293 source_location *location)
2295 cpp_context *c = pfile->context;
2297 if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2299 *token = FIRST (c).token;
2300 *location = (*token)->src_loc;
2301 FIRST (c).token++;
2303 else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2305 *token = *FIRST (c).ptoken;
2306 *location = (*token)->src_loc;
2307 FIRST (c).ptoken++;
2309 else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2311 macro_context *m = c->c.mc;
2312 *token = *FIRST (c).ptoken;
2313 if (m->virt_locs)
2315 *location = *m->cur_virt_loc;
2316 m->cur_virt_loc++;
2318 else
2319 *location = (*token)->src_loc;
2320 FIRST (c).ptoken++;
2322 else
2323 abort ();
2326 /* In the traditional mode of the preprocessor, if we are currently in
2327 a directive, the location of a token must be the location of the
2328 start of the directive line. This function returns the proper
2329 location if we are in the traditional mode, and just returns
2330 LOCATION otherwise. */
2332 static inline source_location
2333 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2335 if (CPP_OPTION (pfile, traditional))
2337 if (pfile->state.in_directive)
2338 return pfile->directive_line;
2340 return location;
2343 /* Routine to get a token as well as its location.
2345 Macro expansions and directives are transparently handled,
2346 including entering included files. Thus tokens are post-macro
2347 expansion, and after any intervening directives. External callers
2348 see CPP_EOF only at EOF. Internal callers also see it when meeting
2349 a directive inside a macro call, when at the end of a directive and
2350 state.in_directive is still 1, and at the end of argument
2351 pre-expansion.
2353 LOC is an out parameter; *LOC is set to the location "as expected
2354 by the user". Please read the comment of
2355 cpp_get_token_with_location to learn more about the meaning of this
2356 location. */
2357 static const cpp_token*
2358 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2360 const cpp_token *result;
2361 /* This token is a virtual token that either encodes a location
2362 related to macro expansion or a spelling location. */
2363 source_location virt_loc = 0;
2364 /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2365 to functions that push macro contexts. So let's save it so that
2366 we can restore it when we are about to leave this routine. */
2367 bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2369 for (;;)
2371 cpp_hashnode *node;
2372 cpp_context *context = pfile->context;
2374 /* Context->prev == 0 <=> base context. */
2375 if (!context->prev)
2377 result = _cpp_lex_token (pfile);
2378 virt_loc = result->src_loc;
2380 else if (!reached_end_of_context (context))
2382 consume_next_token_from_context (pfile, &result,
2383 &virt_loc);
2384 if (result->flags & PASTE_LEFT)
2386 paste_all_tokens (pfile, result);
2387 if (pfile->state.in_directive)
2388 continue;
2389 result = padding_token (pfile, result);
2390 goto out;
2393 else
2395 if (pfile->context->c.macro)
2396 ++num_expanded_macros_counter;
2397 _cpp_pop_context (pfile);
2398 if (pfile->state.in_directive)
2399 continue;
2400 result = &pfile->avoid_paste;
2401 goto out;
2404 if (pfile->state.in_directive && result->type == CPP_COMMENT)
2405 continue;
2407 if (result->type != CPP_NAME)
2408 break;
2410 node = result->val.node.node;
2412 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2413 break;
2415 if (!(node->flags & NODE_DISABLED))
2417 int ret = 0;
2418 /* If not in a macro context, and we're going to start an
2419 expansion, record the location. */
2420 if (!in_macro_expansion_p (pfile))
2421 pfile->invocation_location = result->src_loc;
2422 if (pfile->state.prevent_expansion)
2423 break;
2425 /* Conditional macros require that a predicate be evaluated
2426 first. */
2427 if ((node->flags & NODE_CONDITIONAL) != 0)
2429 if (pfile->cb.macro_to_expand)
2431 bool whitespace_after;
2432 const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2434 whitespace_after = (peek_tok->type == CPP_PADDING
2435 || (peek_tok->flags & PREV_WHITE));
2436 node = pfile->cb.macro_to_expand (pfile, result);
2437 if (node)
2438 ret = enter_macro_context (pfile, node, result,
2439 virt_loc);
2440 else if (whitespace_after)
2442 /* If macro_to_expand hook returned NULL and it
2443 ate some tokens, see if we don't need to add
2444 a padding token in between this and the
2445 next token. */
2446 peek_tok = cpp_peek_token (pfile, 0);
2447 if (peek_tok->type != CPP_PADDING
2448 && (peek_tok->flags & PREV_WHITE) == 0)
2449 _cpp_push_token_context (pfile, NULL,
2450 padding_token (pfile,
2451 peek_tok), 1);
2455 else
2456 ret = enter_macro_context (pfile, node, result,
2457 virt_loc);
2458 if (ret)
2460 if (pfile->state.in_directive || ret == 2)
2461 continue;
2462 result = padding_token (pfile, result);
2463 goto out;
2466 else
2468 /* Flag this token as always unexpandable. FIXME: move this
2469 to collect_args()?. */
2470 cpp_token *t = _cpp_temp_token (pfile);
2471 t->type = result->type;
2472 t->flags = result->flags | NO_EXPAND;
2473 t->val = result->val;
2474 result = t;
2477 break;
2480 out:
2481 if (location != NULL)
2483 if (virt_loc == 0)
2484 virt_loc = result->src_loc;
2485 *location = virt_loc;
2487 if (!CPP_OPTION (pfile, track_macro_expansion)
2488 && macro_of_context (pfile->context) != NULL)
2489 /* We are in a macro expansion context, are not tracking
2490 virtual location, but were asked to report the location
2491 of the expansion point of the macro being expanded. */
2492 *location = pfile->invocation_location;
2494 *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2497 pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
2498 return result;
2501 /* External routine to get a token. Also used nearly everywhere
2502 internally, except for places where we know we can safely call
2503 _cpp_lex_token directly, such as lexing a directive name.
2505 Macro expansions and directives are transparently handled,
2506 including entering included files. Thus tokens are post-macro
2507 expansion, and after any intervening directives. External callers
2508 see CPP_EOF only at EOF. Internal callers also see it when meeting
2509 a directive inside a macro call, when at the end of a directive and
2510 state.in_directive is still 1, and at the end of argument
2511 pre-expansion. */
2512 const cpp_token *
2513 cpp_get_token (cpp_reader *pfile)
2515 return cpp_get_token_1 (pfile, NULL);
2518 /* Like cpp_get_token, but also returns a virtual token location
2519 separate from the spelling location carried by the returned token.
2521 LOC is an out parameter; *LOC is set to the location "as expected
2522 by the user". This matters when a token results from macro
2523 expansion; in that case the token's spelling location indicates the
2524 locus of the token in the definition of the macro but *LOC
2525 virtually encodes all the other meaningful locuses associated to
2526 the token.
2528 What? virtual location? Yes, virtual location.
2530 If the token results from macro expansion and if macro expansion
2531 location tracking is enabled its virtual location encodes (at the
2532 same time):
2534 - the spelling location of the token
2536 - the locus of the macro expansion point
2538 - the locus of the point where the token got instantiated as part
2539 of the macro expansion process.
2541 You have to use the linemap API to get the locus you are interested
2542 in from a given virtual location.
2544 Note however that virtual locations are not necessarily ordered for
2545 relations '<' and '>'. One must use the function
2546 linemap_location_before_p instead of using the relational operator
2547 '<'.
2549 If macro expansion tracking is off and if the token results from
2550 macro expansion the virtual location is the expansion point of the
2551 macro that got expanded.
2553 When the token doesn't result from macro expansion, the virtual
2554 location is just the same thing as its spelling location. */
2556 const cpp_token *
2557 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2559 return cpp_get_token_1 (pfile, loc);
2562 /* Returns true if we're expanding an object-like macro that was
2563 defined in a system header. Just checks the macro at the top of
2564 the stack. Used for diagnostic suppression. */
2566 cpp_sys_macro_p (cpp_reader *pfile)
2568 cpp_hashnode *node = NULL;
2570 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2571 node = pfile->context->c.mc->macro_node;
2572 else
2573 node = pfile->context->c.macro;
2575 return node && node->value.macro && node->value.macro->syshdr;
2578 /* Read each token in, until end of the current file. Directives are
2579 transparently processed. */
2580 void
2581 cpp_scan_nooutput (cpp_reader *pfile)
2583 /* Request a CPP_EOF token at the end of this file, rather than
2584 transparently continuing with the including file. */
2585 pfile->buffer->return_at_eof = true;
2587 pfile->state.discarding_output++;
2588 pfile->state.prevent_expansion++;
2590 if (CPP_OPTION (pfile, traditional))
2591 while (_cpp_read_logical_line_trad (pfile))
2593 else
2594 while (cpp_get_token (pfile)->type != CPP_EOF)
2597 pfile->state.discarding_output--;
2598 pfile->state.prevent_expansion--;
2601 /* Step back one or more tokens obtained from the lexer. */
2602 void
2603 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2605 pfile->lookaheads += count;
2606 while (count--)
2608 pfile->cur_token--;
2609 if (pfile->cur_token == pfile->cur_run->base
2610 /* Possible with -fpreprocessed and no leading #line. */
2611 && pfile->cur_run->prev != NULL)
2613 pfile->cur_run = pfile->cur_run->prev;
2614 pfile->cur_token = pfile->cur_run->limit;
2619 /* Step back one (or more) tokens. Can only step back more than 1 if
2620 they are from the lexer, and not from macro expansion. */
2621 void
2622 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2624 if (pfile->context->prev == NULL)
2625 _cpp_backup_tokens_direct (pfile, count);
2626 else
2628 if (count != 1)
2629 abort ();
2630 if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2631 FIRST (pfile->context).token--;
2632 else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2633 FIRST (pfile->context).ptoken--;
2634 else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2636 FIRST (pfile->context).ptoken--;
2637 if (pfile->context->c.macro)
2639 macro_context *m = pfile->context->c.mc;
2640 m->cur_virt_loc--;
2641 #ifdef ENABLE_CHECKING
2642 if (m->cur_virt_loc < m->virt_locs)
2643 abort ();
2644 #endif
2646 else
2647 abort ();
2649 else
2650 abort ();
2654 /* #define directive parsing and handling. */
2656 /* Returns nonzero if a macro redefinition warning is required. */
2657 static bool
2658 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2659 const cpp_macro *macro2)
2661 const cpp_macro *macro1;
2662 unsigned int i;
2664 /* Some redefinitions need to be warned about regardless. */
2665 if (node->flags & NODE_WARN)
2666 return true;
2668 /* Suppress warnings for builtins that lack the NODE_WARN flag. */
2669 if (node->flags & NODE_BUILTIN)
2671 if (!pfile->cb.user_builtin_macro
2672 || !pfile->cb.user_builtin_macro (pfile, node))
2673 return false;
2676 /* Redefinitions of conditional (context-sensitive) macros, on
2677 the other hand, must be allowed silently. */
2678 if (node->flags & NODE_CONDITIONAL)
2679 return false;
2681 /* Redefinition of a macro is allowed if and only if the old and new
2682 definitions are the same. (6.10.3 paragraph 2). */
2683 macro1 = node->value.macro;
2685 /* Don't check count here as it can be different in valid
2686 traditional redefinitions with just whitespace differences. */
2687 if (macro1->paramc != macro2->paramc
2688 || macro1->fun_like != macro2->fun_like
2689 || macro1->variadic != macro2->variadic)
2690 return true;
2692 /* Check parameter spellings. */
2693 for (i = 0; i < macro1->paramc; i++)
2694 if (macro1->params[i] != macro2->params[i])
2695 return true;
2697 /* Check the replacement text or tokens. */
2698 if (CPP_OPTION (pfile, traditional))
2699 return _cpp_expansions_different_trad (macro1, macro2);
2701 if (macro1->count != macro2->count)
2702 return true;
2704 for (i = 0; i < macro1->count; i++)
2705 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2706 return true;
2708 return false;
2711 /* Free the definition of hashnode H. */
2712 void
2713 _cpp_free_definition (cpp_hashnode *h)
2715 /* Macros and assertions no longer have anything to free. */
2716 h->type = NT_VOID;
2717 /* Clear builtin flag in case of redefinition. */
2718 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2721 /* Save parameter NODE to the parameter list of macro MACRO. Returns
2722 zero on success, nonzero if the parameter is a duplicate. */
2723 bool
2724 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
2726 unsigned int len;
2727 /* Constraint 6.10.3.6 - duplicate parameter names. */
2728 if (node->flags & NODE_MACRO_ARG)
2730 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2731 NODE_NAME (node));
2732 return true;
2735 if (BUFF_ROOM (pfile->a_buff)
2736 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2737 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2739 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
2740 node->flags |= NODE_MACRO_ARG;
2741 len = macro->paramc * sizeof (union _cpp_hashnode_value);
2742 if (len > pfile->macro_buffer_len)
2744 pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2745 len);
2746 pfile->macro_buffer_len = len;
2748 ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
2749 = node->value;
2751 node->value.arg_index = macro->paramc;
2752 return false;
2755 /* Check the syntax of the parameters in a MACRO definition. Returns
2756 false if an error occurs. */
2757 static bool
2758 parse_params (cpp_reader *pfile, cpp_macro *macro)
2760 unsigned int prev_ident = 0;
2762 for (;;)
2764 const cpp_token *token = _cpp_lex_token (pfile);
2766 switch (token->type)
2768 default:
2769 /* Allow/ignore comments in parameter lists if we are
2770 preserving comments in macro expansions. */
2771 if (token->type == CPP_COMMENT
2772 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
2773 continue;
2775 cpp_error (pfile, CPP_DL_ERROR,
2776 "\"%s\" may not appear in macro parameter list",
2777 cpp_token_as_text (pfile, token));
2778 return false;
2780 case CPP_NAME:
2781 if (prev_ident)
2783 cpp_error (pfile, CPP_DL_ERROR,
2784 "macro parameters must be comma-separated");
2785 return false;
2787 prev_ident = 1;
2789 if (_cpp_save_parameter (pfile, macro, token->val.node.node))
2790 return false;
2791 continue;
2793 case CPP_CLOSE_PAREN:
2794 if (prev_ident || macro->paramc == 0)
2795 return true;
2797 /* Fall through to pick up the error. */
2798 case CPP_COMMA:
2799 if (!prev_ident)
2801 cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
2802 return false;
2804 prev_ident = 0;
2805 continue;
2807 case CPP_ELLIPSIS:
2808 macro->variadic = 1;
2809 if (!prev_ident)
2811 _cpp_save_parameter (pfile, macro,
2812 pfile->spec_nodes.n__VA_ARGS__);
2813 pfile->state.va_args_ok = 1;
2814 if (! CPP_OPTION (pfile, c99)
2815 && CPP_OPTION (pfile, cpp_pedantic)
2816 && CPP_OPTION (pfile, warn_variadic_macros))
2818 if (CPP_OPTION (pfile, cplusplus))
2819 cpp_pedwarning
2820 (pfile, CPP_W_VARIADIC_MACROS,
2821 "anonymous variadic macros were introduced in C++11");
2822 else
2823 cpp_pedwarning
2824 (pfile, CPP_W_VARIADIC_MACROS,
2825 "anonymous variadic macros were introduced in C99");
2828 else if (CPP_OPTION (pfile, cpp_pedantic)
2829 && CPP_OPTION (pfile, warn_variadic_macros))
2831 if (CPP_OPTION (pfile, cplusplus))
2832 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2833 "ISO C++ does not permit named variadic macros");
2834 else
2835 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2836 "ISO C does not permit named variadic macros");
2839 /* We're at the end, and just expect a closing parenthesis. */
2840 token = _cpp_lex_token (pfile);
2841 if (token->type == CPP_CLOSE_PAREN)
2842 return true;
2843 /* Fall through. */
2845 case CPP_EOF:
2846 cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
2847 return false;
2852 /* Allocate room for a token from a macro's replacement list. */
2853 static cpp_token *
2854 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2856 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
2857 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
2859 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
2862 /* Lex a token from the expansion of MACRO, but mark parameters as we
2863 find them and warn of traditional stringification. */
2864 static cpp_token *
2865 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2867 cpp_token *token, *saved_cur_token;
2869 saved_cur_token = pfile->cur_token;
2870 pfile->cur_token = alloc_expansion_token (pfile, macro);
2871 token = _cpp_lex_direct (pfile);
2872 pfile->cur_token = saved_cur_token;
2874 /* Is this a parameter? */
2875 if (token->type == CPP_NAME
2876 && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
2878 token->type = CPP_MACRO_ARG;
2879 token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
2881 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
2882 && (token->type == CPP_STRING || token->type == CPP_CHAR))
2883 check_trad_stringification (pfile, macro, &token->val.str);
2885 return token;
2888 static bool
2889 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
2891 cpp_token *token;
2892 const cpp_token *ctoken;
2893 bool following_paste_op = false;
2894 const char *paste_op_error_msg =
2895 N_("'##' cannot appear at either end of a macro expansion");
2896 unsigned int num_extra_tokens = 0;
2898 /* Get the first token of the expansion (or the '(' of a
2899 function-like macro). */
2900 ctoken = _cpp_lex_token (pfile);
2902 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
2904 bool ok = parse_params (pfile, macro);
2905 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
2906 if (!ok)
2907 return false;
2909 /* Success. Commit or allocate the parameter array. */
2910 if (pfile->hash_table->alloc_subobject)
2912 cpp_hashnode **params =
2913 (cpp_hashnode **) pfile->hash_table->alloc_subobject
2914 (sizeof (cpp_hashnode *) * macro->paramc);
2915 memcpy (params, macro->params,
2916 sizeof (cpp_hashnode *) * macro->paramc);
2917 macro->params = params;
2919 else
2920 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
2921 macro->fun_like = 1;
2923 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
2925 /* While ISO C99 requires whitespace before replacement text
2926 in a macro definition, ISO C90 with TC1 allows characters
2927 from the basic source character set there. */
2928 if (CPP_OPTION (pfile, c99))
2930 if (CPP_OPTION (pfile, cplusplus))
2931 cpp_error (pfile, CPP_DL_PEDWARN,
2932 "ISO C++11 requires whitespace after the macro name");
2933 else
2934 cpp_error (pfile, CPP_DL_PEDWARN,
2935 "ISO C99 requires whitespace after the macro name");
2937 else
2939 int warntype = CPP_DL_WARNING;
2940 switch (ctoken->type)
2942 case CPP_ATSIGN:
2943 case CPP_AT_NAME:
2944 case CPP_OBJC_STRING:
2945 /* '@' is not in basic character set. */
2946 warntype = CPP_DL_PEDWARN;
2947 break;
2948 case CPP_OTHER:
2949 /* Basic character set sans letters, digits and _. */
2950 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
2951 ctoken->val.str.text[0]) == NULL)
2952 warntype = CPP_DL_PEDWARN;
2953 break;
2954 default:
2955 /* All other tokens start with a character from basic
2956 character set. */
2957 break;
2959 cpp_error (pfile, warntype,
2960 "missing whitespace after the macro name");
2964 if (macro->fun_like)
2965 token = lex_expansion_token (pfile, macro);
2966 else
2968 token = alloc_expansion_token (pfile, macro);
2969 *token = *ctoken;
2972 for (;;)
2974 /* Check the stringifying # constraint 6.10.3.2.1 of
2975 function-like macros when lexing the subsequent token. */
2976 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
2978 if (token->type == CPP_MACRO_ARG)
2980 if (token->flags & PREV_WHITE)
2981 token->flags |= SP_PREV_WHITE;
2982 if (token[-1].flags & DIGRAPH)
2983 token->flags |= SP_DIGRAPH;
2984 token->flags &= ~PREV_WHITE;
2985 token->flags |= STRINGIFY_ARG;
2986 token->flags |= token[-1].flags & PREV_WHITE;
2987 token[-1] = token[0];
2988 macro->count--;
2990 /* Let assembler get away with murder. */
2991 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
2993 cpp_error (pfile, CPP_DL_ERROR,
2994 "'#' is not followed by a macro parameter");
2995 return false;
2999 if (token->type == CPP_EOF)
3001 /* Paste operator constraint 6.10.3.3.1:
3002 Token-paste ##, can appear in both object-like and
3003 function-like macros, but not at the end. */
3004 if (following_paste_op)
3006 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3007 return false;
3009 break;
3012 /* Paste operator constraint 6.10.3.3.1. */
3013 if (token->type == CPP_PASTE)
3015 /* Token-paste ##, can appear in both object-like and
3016 function-like macros, but not at the beginning. */
3017 if (macro->count == 1)
3019 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3020 return false;
3023 if (token[-1].flags & PASTE_LEFT)
3025 macro->extra_tokens = 1;
3026 num_extra_tokens++;
3027 token->val.token_no = macro->count - 1;
3029 else
3031 --macro->count;
3032 token[-1].flags |= PASTE_LEFT;
3033 if (token->flags & DIGRAPH)
3034 token[-1].flags |= SP_DIGRAPH;
3035 if (token->flags & PREV_WHITE)
3036 token[-1].flags |= SP_PREV_WHITE;
3040 following_paste_op = (token->type == CPP_PASTE);
3041 token = lex_expansion_token (pfile, macro);
3044 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
3045 macro->traditional = 0;
3047 /* Don't count the CPP_EOF. */
3048 macro->count--;
3050 /* Clear whitespace on first token for warn_of_redefinition(). */
3051 if (macro->count)
3052 macro->exp.tokens[0].flags &= ~PREV_WHITE;
3054 /* Commit or allocate the memory. */
3055 if (pfile->hash_table->alloc_subobject)
3057 cpp_token *tokns =
3058 (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
3059 * macro->count);
3060 if (num_extra_tokens)
3062 /* Place second and subsequent ## or %:%: tokens in
3063 sequences of consecutive such tokens at the end of the
3064 list to preserve information about where they appear, how
3065 they are spelt and whether they are preceded by
3066 whitespace without otherwise interfering with macro
3067 expansion. */
3068 cpp_token *normal_dest = tokns;
3069 cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
3070 unsigned int i;
3071 for (i = 0; i < macro->count; i++)
3073 if (macro->exp.tokens[i].type == CPP_PASTE)
3074 *extra_dest++ = macro->exp.tokens[i];
3075 else
3076 *normal_dest++ = macro->exp.tokens[i];
3079 else
3080 memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
3081 macro->exp.tokens = tokns;
3083 else
3084 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
3086 return true;
3089 /* Parse a macro and save its expansion. Returns nonzero on success. */
3090 bool
3091 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3093 cpp_macro *macro;
3094 unsigned int i;
3095 bool ok;
3097 if (pfile->hash_table->alloc_subobject)
3098 macro = (cpp_macro *) pfile->hash_table->alloc_subobject
3099 (sizeof (cpp_macro));
3100 else
3101 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
3102 macro->line = pfile->directive_line;
3103 macro->params = 0;
3104 macro->paramc = 0;
3105 macro->variadic = 0;
3106 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3107 macro->count = 0;
3108 macro->fun_like = 0;
3109 macro->extra_tokens = 0;
3110 /* To suppress some diagnostics. */
3111 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3113 if (CPP_OPTION (pfile, traditional))
3114 ok = _cpp_create_trad_definition (pfile, macro);
3115 else
3117 ok = create_iso_definition (pfile, macro);
3119 /* We set the type for SEEN_EOL() in directives.c.
3121 Longer term we should lex the whole line before coming here,
3122 and just copy the expansion. */
3124 /* Stop the lexer accepting __VA_ARGS__. */
3125 pfile->state.va_args_ok = 0;
3128 /* Clear the fast argument lookup indices. */
3129 for (i = macro->paramc; i-- > 0; )
3131 struct cpp_hashnode *node = macro->params[i];
3132 node->flags &= ~ NODE_MACRO_ARG;
3133 node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
3136 if (!ok)
3137 return ok;
3139 if (node->type == NT_MACRO)
3141 if (CPP_OPTION (pfile, warn_unused_macros))
3142 _cpp_warn_if_unused_macro (pfile, node, NULL);
3144 if (warn_of_redefinition (pfile, node, macro))
3146 const int reason = (node->flags & NODE_BUILTIN)
3147 ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3148 bool warned;
3150 warned = cpp_pedwarning_with_line (pfile, reason,
3151 pfile->directive_line, 0,
3152 "\"%s\" redefined",
3153 NODE_NAME (node));
3155 if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3156 cpp_error_with_line (pfile, CPP_DL_NOTE,
3157 node->value.macro->line, 0,
3158 "this is the location of the previous definition");
3162 if (node->type != NT_VOID)
3163 _cpp_free_definition (node);
3165 /* Enter definition in hash table. */
3166 node->type = NT_MACRO;
3167 node->value.macro = macro;
3168 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3169 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3170 /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3171 in the C standard, as something that one must use in C++.
3172 However DR#593 and C++11 indicate that they play no role in C++.
3173 We special-case them anyway. */
3174 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3175 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3176 node->flags |= NODE_WARN;
3178 /* If user defines one of the conditional macros, remove the
3179 conditional flag */
3180 node->flags &= ~NODE_CONDITIONAL;
3182 return ok;
3185 /* Warn if a token in STRING matches one of a function-like MACRO's
3186 parameters. */
3187 static void
3188 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3189 const cpp_string *string)
3191 unsigned int i, len;
3192 const uchar *p, *q, *limit;
3194 /* Loop over the string. */
3195 limit = string->text + string->len - 1;
3196 for (p = string->text + 1; p < limit; p = q)
3198 /* Find the start of an identifier. */
3199 while (p < limit && !is_idstart (*p))
3200 p++;
3202 /* Find the end of the identifier. */
3203 q = p;
3204 while (q < limit && is_idchar (*q))
3205 q++;
3207 len = q - p;
3209 /* Loop over the function macro arguments to see if the
3210 identifier inside the string matches one of them. */
3211 for (i = 0; i < macro->paramc; i++)
3213 const cpp_hashnode *node = macro->params[i];
3215 if (NODE_LEN (node) == len
3216 && !memcmp (p, NODE_NAME (node), len))
3218 cpp_error (pfile, CPP_DL_WARNING,
3219 "macro argument \"%s\" would be stringified in traditional C",
3220 NODE_NAME (node));
3221 break;
3227 /* Returns the name, arguments and expansion of a macro, in a format
3228 suitable to be read back in again, and therefore also for DWARF 2
3229 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3230 Caller is expected to generate the "#define" bit if needed. The
3231 returned text is temporary, and automatically freed later. */
3232 const unsigned char *
3233 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3235 unsigned int i, len;
3236 const cpp_macro *macro;
3237 unsigned char *buffer;
3239 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3241 if (node->type != NT_MACRO
3242 || !pfile->cb.user_builtin_macro
3243 || !pfile->cb.user_builtin_macro (pfile, node))
3245 cpp_error (pfile, CPP_DL_ICE,
3246 "invalid hash type %d in cpp_macro_definition",
3247 node->type);
3248 return 0;
3252 macro = node->value.macro;
3253 /* Calculate length. */
3254 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
3255 if (macro->fun_like)
3257 len += 4; /* "()" plus possible final ".." of named
3258 varargs (we have + 1 below). */
3259 for (i = 0; i < macro->paramc; i++)
3260 len += NODE_LEN (macro->params[i]) + 1; /* "," */
3263 /* This should match below where we fill in the buffer. */
3264 if (CPP_OPTION (pfile, traditional))
3265 len += _cpp_replacement_text_len (macro);
3266 else
3268 unsigned int count = macro_real_token_count (macro);
3269 for (i = 0; i < count; i++)
3271 cpp_token *token = &macro->exp.tokens[i];
3273 if (token->type == CPP_MACRO_ARG)
3274 len += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3275 else
3276 len += cpp_token_len (token);
3278 if (token->flags & STRINGIFY_ARG)
3279 len++; /* "#" */
3280 if (token->flags & PASTE_LEFT)
3281 len += 3; /* " ##" */
3282 if (token->flags & PREV_WHITE)
3283 len++; /* " " */
3287 if (len > pfile->macro_buffer_len)
3289 pfile->macro_buffer = XRESIZEVEC (unsigned char,
3290 pfile->macro_buffer, len);
3291 pfile->macro_buffer_len = len;
3294 /* Fill in the buffer. Start with the macro name. */
3295 buffer = pfile->macro_buffer;
3296 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
3297 buffer += NODE_LEN (node);
3299 /* Parameter names. */
3300 if (macro->fun_like)
3302 *buffer++ = '(';
3303 for (i = 0; i < macro->paramc; i++)
3305 cpp_hashnode *param = macro->params[i];
3307 if (param != pfile->spec_nodes.n__VA_ARGS__)
3309 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3310 buffer += NODE_LEN (param);
3313 if (i + 1 < macro->paramc)
3314 /* Don't emit a space after the comma here; we're trying
3315 to emit a Dwarf-friendly definition, and the Dwarf spec
3316 forbids spaces in the argument list. */
3317 *buffer++ = ',';
3318 else if (macro->variadic)
3319 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3321 *buffer++ = ')';
3324 /* The Dwarf spec requires a space after the macro name, even if the
3325 definition is the empty string. */
3326 *buffer++ = ' ';
3328 if (CPP_OPTION (pfile, traditional))
3329 buffer = _cpp_copy_replacement_text (macro, buffer);
3330 else if (macro->count)
3331 /* Expansion tokens. */
3333 unsigned int count = macro_real_token_count (macro);
3334 for (i = 0; i < count; i++)
3336 cpp_token *token = &macro->exp.tokens[i];
3338 if (token->flags & PREV_WHITE)
3339 *buffer++ = ' ';
3340 if (token->flags & STRINGIFY_ARG)
3341 *buffer++ = '#';
3343 if (token->type == CPP_MACRO_ARG)
3345 memcpy (buffer,
3346 NODE_NAME (macro->params[token->val.macro_arg.arg_no - 1]),
3347 NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]));
3348 buffer += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3350 else
3351 buffer = cpp_spell_token (pfile, token, buffer, false);
3353 if (token->flags & PASTE_LEFT)
3355 *buffer++ = ' ';
3356 *buffer++ = '#';
3357 *buffer++ = '#';
3358 /* Next has PREV_WHITE; see _cpp_create_definition. */
3363 *buffer = '\0';
3364 return pfile->macro_buffer;