* config/mh-ppc-aix (LDFLAGS): Quote $(CC).
[official-gcc.git] / libcpp / macro.c
blobc4e2a23c56bd2d56aed6619f61abf6445c535293
1 /* Part of CPP library. (Macro and #define handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 2006, 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
5 Written by Per Bothner, 1994.
6 Based on CCCP program by Paul Rubin, June 1986
7 Adapted to ANSI C, Richard Stallman, Jan 1987
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 3, or (at your option) any
12 later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>.
23 In other words, you are welcome to use, share and improve this program.
24 You are forbidden to forbid anyone else to use, share and improve
25 what you give them. Help stamp out software-hoarding! */
27 #include "config.h"
28 #include "system.h"
29 #include "cpplib.h"
30 #include "internal.h"
32 typedef struct macro_arg macro_arg;
33 /* This structure represents the tokens of a macro argument. These
34 tokens can be macro themselves, in which case they can be either
35 expanded or unexpanded. When they are expanded, this data
36 structure keeps both the expanded and unexpanded forms. */
37 struct macro_arg
39 const cpp_token **first; /* First token in unexpanded argument. */
40 const cpp_token **expanded; /* Macro-expanded argument. */
41 const cpp_token *stringified; /* Stringified argument. */
42 unsigned int count; /* # of tokens in argument. */
43 unsigned int expanded_count; /* # of tokens in expanded argument. */
44 source_location *virt_locs; /* Where virtual locations for
45 unexpanded tokens are stored. */
46 source_location *expanded_virt_locs; /* Where virtual locations for
47 expanded tokens are
48 stored. */
51 /* The kind of macro tokens which the instance of
52 macro_arg_token_iter is supposed to iterate over. */
53 enum macro_arg_token_kind {
54 MACRO_ARG_TOKEN_NORMAL,
55 /* This is a macro argument token that got transformed into a string
56 litteral, e.g. #foo. */
57 MACRO_ARG_TOKEN_STRINGIFIED,
58 /* This is a token resulting from the expansion of a macro
59 argument that was itself a macro. */
60 MACRO_ARG_TOKEN_EXPANDED
63 /* An iterator over tokens coming from a function-like macro
64 argument. */
65 typedef struct macro_arg_token_iter macro_arg_token_iter;
66 struct macro_arg_token_iter
68 /* Whether or not -ftrack-macro-expansion is used. */
69 bool track_macro_exp_p;
70 /* The kind of token over which we are supposed to iterate. */
71 enum macro_arg_token_kind kind;
72 /* A pointer to the current token pointed to by the iterator. */
73 const cpp_token **token_ptr;
74 /* A pointer to the "full" location of the current token. If
75 -ftrack-macro-expansion is used this location tracks loci accross
76 macro expansion. */
77 const source_location *location_ptr;
78 #ifdef ENABLE_CHECKING
79 /* The number of times the iterator went forward. This useful only
80 when checking is enabled. */
81 size_t num_forwards;
82 #endif
85 /* Macro expansion. */
87 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
88 const cpp_token *, source_location);
89 static int builtin_macro (cpp_reader *, cpp_hashnode *);
90 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
91 const cpp_token **, unsigned int);
92 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
93 _cpp_buff *, source_location *,
94 const cpp_token **, unsigned int);
95 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
96 _cpp_buff **, unsigned *);
97 static cpp_context *next_context (cpp_reader *);
98 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
99 static void expand_arg (cpp_reader *, macro_arg *);
100 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
101 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
102 static void paste_all_tokens (cpp_reader *, const cpp_token *);
103 static bool paste_tokens (cpp_reader *, const cpp_token **, const cpp_token *);
104 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
105 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
106 static void delete_macro_args (_cpp_buff*, unsigned num_args);
107 static void set_arg_token (macro_arg *, const cpp_token *,
108 source_location, size_t,
109 enum macro_arg_token_kind,
110 bool);
111 static const source_location *get_arg_token_location (const macro_arg *,
112 enum macro_arg_token_kind);
113 static const cpp_token **arg_token_ptr_at (const macro_arg *,
114 size_t,
115 enum macro_arg_token_kind,
116 source_location **virt_location);
118 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
119 enum macro_arg_token_kind,
120 const macro_arg *,
121 const cpp_token **);
122 static const cpp_token *macro_arg_token_iter_get_token
123 (const macro_arg_token_iter *it);
124 static source_location macro_arg_token_iter_get_location
125 (const macro_arg_token_iter *);
126 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
127 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
128 source_location **);
129 static size_t tokens_buff_count (_cpp_buff *);
130 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
131 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
132 source_location *,
133 const cpp_token *,
134 source_location,
135 source_location,
136 const struct line_map *,
137 unsigned int);
139 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
140 source_location *,
141 const cpp_token *,
142 source_location,
143 source_location,
144 const struct line_map *,
145 unsigned int);
146 static inline void tokens_buff_remove_last_token (_cpp_buff *);
147 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
148 macro_arg *, source_location);
149 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
150 _cpp_buff **, unsigned *);
151 static bool create_iso_definition (cpp_reader *, cpp_macro *);
153 /* #define directive parsing and handling. */
155 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
156 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
157 static bool warn_of_redefinition (cpp_reader *, cpp_hashnode *,
158 const cpp_macro *);
159 static bool parse_params (cpp_reader *, cpp_macro *);
160 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
161 const cpp_string *);
162 static bool reached_end_of_context (cpp_context *);
163 static void consume_next_token_from_context (cpp_reader *pfile,
164 const cpp_token **,
165 source_location *);
166 static const cpp_token* cpp_get_token_1 (cpp_reader *, source_location *);
168 static cpp_hashnode* macro_of_context (cpp_context *context);
170 /* Statistical counter tracking the number of macros that got
171 expanded. */
172 unsigned num_expanded_macros_counter = 0;
173 /* Statistical counter tracking the total number tokens resulting
174 from macro expansion. */
175 unsigned num_macro_tokens_counter = 0;
177 /* Emits a warning if NODE is a macro defined in the main file that
178 has not been used. */
180 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
181 void *v ATTRIBUTE_UNUSED)
183 if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
185 cpp_macro *macro = node->value.macro;
187 if (!macro->used
188 && MAIN_FILE_P (linemap_lookup (pfile->line_table, macro->line)))
189 cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
190 "macro \"%s\" is not used", NODE_NAME (node));
193 return 1;
196 /* Allocates and returns a CPP_STRING token, containing TEXT of length
197 LEN, after null-terminating it. TEXT must be in permanent storage. */
198 static const cpp_token *
199 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
201 cpp_token *token = _cpp_temp_token (pfile);
203 text[len] = '\0';
204 token->type = CPP_STRING;
205 token->val.str.len = len;
206 token->val.str.text = text;
207 token->flags = 0;
208 return token;
211 static const char * const monthnames[] =
213 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
214 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
217 /* Helper function for builtin_macro. Returns the text generated by
218 a builtin macro. */
219 const uchar *
220 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
222 const uchar *result = NULL;
223 linenum_type number = 1;
225 switch (node->value.builtin)
227 default:
228 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
229 NODE_NAME (node));
230 break;
232 case BT_TIMESTAMP:
234 cpp_buffer *pbuffer = cpp_get_buffer (pfile);
235 if (pbuffer->timestamp == NULL)
237 /* Initialize timestamp value of the assotiated file. */
238 struct _cpp_file *file = cpp_get_file (pbuffer);
239 if (file)
241 /* Generate __TIMESTAMP__ string, that represents
242 the date and time of the last modification
243 of the current source file. The string constant
244 looks like "Sun Sep 16 01:03:52 1973". */
245 struct tm *tb = NULL;
246 struct stat *st = _cpp_get_file_stat (file);
247 if (st)
248 tb = localtime (&st->st_mtime);
249 if (tb)
251 char *str = asctime (tb);
252 size_t len = strlen (str);
253 unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
254 buf[0] = '"';
255 strcpy ((char *) buf + 1, str);
256 buf[len] = '"';
257 pbuffer->timestamp = buf;
259 else
261 cpp_errno (pfile, CPP_DL_WARNING,
262 "could not determine file timestamp");
263 pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
267 result = pbuffer->timestamp;
269 break;
270 case BT_FILE:
271 case BT_BASE_FILE:
273 unsigned int len;
274 const char *name;
275 uchar *buf;
277 if (node->value.builtin == BT_FILE)
278 name = linemap_get_expansion_filename (pfile->line_table,
279 pfile->line_table->highest_line);
280 else
282 name = _cpp_get_file_name (pfile->main_file);
283 if (!name)
284 abort ();
286 len = strlen (name);
287 buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
288 result = buf;
289 *buf = '"';
290 buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
291 *buf++ = '"';
292 *buf = '\0';
294 break;
296 case BT_INCLUDE_LEVEL:
297 /* The line map depth counts the primary source as level 1, but
298 historically __INCLUDE_DEPTH__ has called the primary source
299 level 0. */
300 number = pfile->line_table->depth - 1;
301 break;
303 case BT_SPECLINE:
304 /* If __LINE__ is embedded in a macro, it must expand to the
305 line of the macro's invocation, not its definition.
306 Otherwise things like assert() will not work properly. */
307 number = linemap_get_expansion_line (pfile->line_table,
308 CPP_OPTION (pfile, traditional)
309 ? pfile->line_table->highest_line
310 : pfile->cur_token[-1].src_loc);
311 break;
313 /* __STDC__ has the value 1 under normal circumstances.
314 However, if (a) we are in a system header, (b) the option
315 stdc_0_in_system_headers is true (set by target config), and
316 (c) we are not in strictly conforming mode, then it has the
317 value 0. (b) and (c) are already checked in cpp_init_builtins. */
318 case BT_STDC:
319 if (cpp_in_system_header (pfile))
320 number = 0;
321 else
322 number = 1;
323 break;
325 case BT_DATE:
326 case BT_TIME:
327 if (pfile->date == NULL)
329 /* Allocate __DATE__ and __TIME__ strings from permanent
330 storage. We only do this once, and don't generate them
331 at init time, because time() and localtime() are very
332 slow on some systems. */
333 time_t tt;
334 struct tm *tb = NULL;
336 /* (time_t) -1 is a legitimate value for "number of seconds
337 since the Epoch", so we have to do a little dance to
338 distinguish that from a genuine error. */
339 errno = 0;
340 tt = time(NULL);
341 if (tt != (time_t)-1 || errno == 0)
342 tb = localtime (&tt);
344 if (tb)
346 pfile->date = _cpp_unaligned_alloc (pfile,
347 sizeof ("\"Oct 11 1347\""));
348 sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
349 monthnames[tb->tm_mon], tb->tm_mday,
350 tb->tm_year + 1900);
352 pfile->time = _cpp_unaligned_alloc (pfile,
353 sizeof ("\"12:34:56\""));
354 sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
355 tb->tm_hour, tb->tm_min, tb->tm_sec);
357 else
359 cpp_errno (pfile, CPP_DL_WARNING,
360 "could not determine date and time");
362 pfile->date = UC"\"??? ?? ????\"";
363 pfile->time = UC"\"??:??:??\"";
367 if (node->value.builtin == BT_DATE)
368 result = pfile->date;
369 else
370 result = pfile->time;
371 break;
373 case BT_COUNTER:
374 if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
375 cpp_error (pfile, CPP_DL_ERROR,
376 "__COUNTER__ expanded inside directive with -fdirectives-only");
377 number = pfile->counter++;
378 break;
381 if (result == NULL)
383 /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers. */
384 result = _cpp_unaligned_alloc (pfile, 21);
385 sprintf ((char *) result, "%u", number);
388 return result;
391 /* Convert builtin macros like __FILE__ to a token and push it on the
392 context stack. Also handles _Pragma, for which a new token may not
393 be created. Returns 1 if it generates a new token context, 0 to
394 return the token to the caller. */
395 static int
396 builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
398 const uchar *buf;
399 size_t len;
400 char *nbuf;
402 if (node->value.builtin == BT_PRAGMA)
404 /* Don't interpret _Pragma within directives. The standard is
405 not clear on this, but to me this makes most sense. */
406 if (pfile->state.in_directive)
407 return 0;
409 return _cpp_do__Pragma (pfile);
412 buf = _cpp_builtin_macro_text (pfile, node);
413 len = ustrlen (buf);
414 nbuf = (char *) alloca (len + 1);
415 memcpy (nbuf, buf, len);
416 nbuf[len]='\n';
418 cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
419 _cpp_clean_line (pfile);
421 /* Set pfile->cur_token as required by _cpp_lex_direct. */
422 pfile->cur_token = _cpp_temp_token (pfile);
423 _cpp_push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
424 if (pfile->buffer->cur != pfile->buffer->rlimit)
425 cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
426 NODE_NAME (node));
427 _cpp_pop_buffer (pfile);
429 return 1;
432 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
433 backslashes and double quotes. DEST must be of sufficient size.
434 Returns a pointer to the end of the string. */
435 uchar *
436 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
438 while (len--)
440 uchar c = *src++;
442 if (c == '\\' || c == '"')
444 *dest++ = '\\';
445 *dest++ = c;
447 else
448 *dest++ = c;
451 return dest;
454 /* Convert a token sequence ARG to a single string token according to
455 the rules of the ISO C #-operator. */
456 static const cpp_token *
457 stringify_arg (cpp_reader *pfile, macro_arg *arg)
459 unsigned char *dest;
460 unsigned int i, escape_it, backslash_count = 0;
461 const cpp_token *source = NULL;
462 size_t len;
464 if (BUFF_ROOM (pfile->u_buff) < 3)
465 _cpp_extend_buff (pfile, &pfile->u_buff, 3);
466 dest = BUFF_FRONT (pfile->u_buff);
467 *dest++ = '"';
469 /* Loop, reading in the argument's tokens. */
470 for (i = 0; i < arg->count; i++)
472 const cpp_token *token = arg->first[i];
474 if (token->type == CPP_PADDING)
476 if (source == NULL
477 || (!(source->flags & PREV_WHITE)
478 && token->val.source == NULL))
479 source = token->val.source;
480 continue;
483 escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
484 || token->type == CPP_WSTRING || token->type == CPP_WCHAR
485 || token->type == CPP_STRING32 || token->type == CPP_CHAR32
486 || token->type == CPP_STRING16 || token->type == CPP_CHAR16
487 || token->type == CPP_UTF8STRING);
489 /* Room for each char being written in octal, initial space and
490 final quote and NUL. */
491 len = cpp_token_len (token);
492 if (escape_it)
493 len *= 4;
494 len += 3;
496 if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
498 size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
499 _cpp_extend_buff (pfile, &pfile->u_buff, len);
500 dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
503 /* Leading white space? */
504 if (dest - 1 != BUFF_FRONT (pfile->u_buff))
506 if (source == NULL)
507 source = token;
508 if (source->flags & PREV_WHITE)
509 *dest++ = ' ';
511 source = NULL;
513 if (escape_it)
515 _cpp_buff *buff = _cpp_get_buff (pfile, len);
516 unsigned char *buf = BUFF_FRONT (buff);
517 len = cpp_spell_token (pfile, token, buf, true) - buf;
518 dest = cpp_quote_string (dest, buf, len);
519 _cpp_release_buff (pfile, buff);
521 else
522 dest = cpp_spell_token (pfile, token, dest, true);
524 if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
525 backslash_count++;
526 else
527 backslash_count = 0;
530 /* Ignore the final \ of invalid string literals. */
531 if (backslash_count & 1)
533 cpp_error (pfile, CPP_DL_WARNING,
534 "invalid string literal, ignoring final '\\'");
535 dest--;
538 /* Commit the memory, including NUL, and return the token. */
539 *dest++ = '"';
540 len = dest - BUFF_FRONT (pfile->u_buff);
541 BUFF_FRONT (pfile->u_buff) = dest + 1;
542 return new_string_token (pfile, dest - len, len);
545 /* Try to paste two tokens. On success, return nonzero. In any
546 case, PLHS is updated to point to the pasted token, which is
547 guaranteed to not have the PASTE_LEFT flag set. */
548 static bool
549 paste_tokens (cpp_reader *pfile, const cpp_token **plhs, const cpp_token *rhs)
551 unsigned char *buf, *end, *lhsend;
552 cpp_token *lhs;
553 unsigned int len;
555 len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
556 buf = (unsigned char *) alloca (len);
557 end = lhsend = cpp_spell_token (pfile, *plhs, buf, false);
559 /* Avoid comment headers, since they are still processed in stage 3.
560 It is simpler to insert a space here, rather than modifying the
561 lexer to ignore comments in some circumstances. Simply returning
562 false doesn't work, since we want to clear the PASTE_LEFT flag. */
563 if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
564 *end++ = ' ';
565 /* In one obscure case we might see padding here. */
566 if (rhs->type != CPP_PADDING)
567 end = cpp_spell_token (pfile, rhs, end, false);
568 *end = '\n';
570 cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
571 _cpp_clean_line (pfile);
573 /* Set pfile->cur_token as required by _cpp_lex_direct. */
574 pfile->cur_token = _cpp_temp_token (pfile);
575 lhs = _cpp_lex_direct (pfile);
576 if (pfile->buffer->cur != pfile->buffer->rlimit)
578 source_location saved_loc = lhs->src_loc;
580 _cpp_pop_buffer (pfile);
581 _cpp_backup_tokens (pfile, 1);
582 *lhsend = '\0';
584 /* We have to remove the PASTE_LEFT flag from the old lhs, but
585 we want to keep the new location. */
586 *lhs = **plhs;
587 *plhs = lhs;
588 lhs->src_loc = saved_loc;
589 lhs->flags &= ~PASTE_LEFT;
591 /* Mandatory error for all apart from assembler. */
592 if (CPP_OPTION (pfile, lang) != CLK_ASM)
593 cpp_error (pfile, CPP_DL_ERROR,
594 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
595 buf, cpp_token_as_text (pfile, rhs));
596 return false;
599 *plhs = lhs;
600 _cpp_pop_buffer (pfile);
601 return true;
604 /* Handles an arbitrarily long sequence of ## operators, with initial
605 operand LHS. This implementation is left-associative,
606 non-recursive, and finishes a paste before handling succeeding
607 ones. If a paste fails, we back up to the RHS of the failing ##
608 operator before pushing the context containing the result of prior
609 successful pastes, with the effect that the RHS appears in the
610 output stream after the pasted LHS normally. */
611 static void
612 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
614 const cpp_token *rhs = NULL;
615 cpp_context *context = pfile->context;
616 source_location virt_loc = 0;
618 /* We must have been called on a token that appears at the left
619 hand side of a ## operator. */
620 if (!(lhs->flags & PASTE_LEFT))
621 abort ();
623 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
624 /* The caller must have called consume_next_token_from_context
625 right before calling us. That has incremented the pointer to
626 the current virtual location. So it now points to the location
627 of the token that comes right after *LHS. We want the
628 resulting pasted token to have the location of the current
629 *LHS, though. */
630 virt_loc = context->c.mc->cur_virt_loc[-1];
634 /* Take the token directly from the current context. We can do
635 this, because we are in the replacement list of either an
636 object-like macro, or a function-like macro with arguments
637 inserted. In either case, the constraints to #define
638 guarantee we have at least one more token. */
639 if (context->tokens_kind == TOKENS_KIND_DIRECT)
640 rhs = FIRST (context).token++;
641 else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
642 rhs = *FIRST (context).ptoken++;
643 else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
645 /* So we are in presence of an extended token context, which
646 means that each token in this context has a virtual
647 location attached to it. So let's not forget to update
648 the pointer to the current virtual location of the
649 current token when we update the pointer to the current
650 token */
652 rhs = *FIRST (context).ptoken++;
653 /* context->c.mc must be non-null, as if we were not in a
654 macro context, context->tokens_kind could not be equal to
655 TOKENS_KIND_EXTENDED. */
656 context->c.mc->cur_virt_loc++;
659 if (rhs->type == CPP_PADDING)
661 if (rhs->flags & PASTE_LEFT)
662 abort ();
664 if (!paste_tokens (pfile, &lhs, rhs))
665 break;
667 while (rhs->flags & PASTE_LEFT);
669 /* Put the resulting token in its own context. */
670 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
672 source_location *virt_locs = NULL;
673 _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
674 tokens_buff_add_token (token_buf, virt_locs, lhs,
675 virt_loc, 0, NULL, 0);
676 push_extended_tokens_context (pfile, context->c.mc->macro_node,
677 token_buf, virt_locs,
678 (const cpp_token **)token_buf->base, 1);
680 else
681 _cpp_push_token_context (pfile, NULL, lhs, 1);
684 /* Returns TRUE if the number of arguments ARGC supplied in an
685 invocation of the MACRO referenced by NODE is valid. An empty
686 invocation to a macro with no parameters should pass ARGC as zero.
688 Note that MACRO cannot necessarily be deduced from NODE, in case
689 NODE was redefined whilst collecting arguments. */
690 bool
691 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
693 if (argc == macro->paramc)
694 return true;
696 if (argc < macro->paramc)
698 /* As an extension, a rest argument is allowed to not appear in
699 the invocation at all.
700 e.g. #define debug(format, args...) something
701 debug("string");
703 This is exactly the same as if there had been an empty rest
704 argument - debug("string", ). */
706 if (argc + 1 == macro->paramc && macro->variadic)
708 if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
709 cpp_error (pfile, CPP_DL_PEDWARN,
710 "ISO C99 requires rest arguments to be used");
711 return true;
714 cpp_error (pfile, CPP_DL_ERROR,
715 "macro \"%s\" requires %u arguments, but only %u given",
716 NODE_NAME (node), macro->paramc, argc);
718 else
719 cpp_error (pfile, CPP_DL_ERROR,
720 "macro \"%s\" passed %u arguments, but takes just %u",
721 NODE_NAME (node), argc, macro->paramc);
723 return false;
726 /* Reads and returns the arguments to a function-like macro
727 invocation. Assumes the opening parenthesis has been processed.
728 If there is an error, emits an appropriate diagnostic and returns
729 NULL. Each argument is terminated by a CPP_EOF token, for the
730 future benefit of expand_arg(). If there are any deferred
731 #pragma directives among macro arguments, store pointers to the
732 CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
734 What is returned is the buffer that contains the memory allocated
735 to hold the macro arguments. NODE is the name of the macro this
736 function is dealing with. If NUM_ARGS is non-NULL, *NUM_ARGS is
737 set to the actual number of macro arguments allocated in the
738 returned buffer. */
739 static _cpp_buff *
740 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
741 _cpp_buff **pragma_buff, unsigned *num_args)
743 _cpp_buff *buff, *base_buff;
744 cpp_macro *macro;
745 macro_arg *args, *arg;
746 const cpp_token *token;
747 unsigned int argc;
748 source_location virt_loc;
749 bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
750 unsigned num_args_alloced = 0;
752 macro = node->value.macro;
753 if (macro->paramc)
754 argc = macro->paramc;
755 else
756 argc = 1;
758 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
759 #define ARG_TOKENS_EXTENT 1000
761 buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
762 * sizeof (cpp_token *)
763 + sizeof (macro_arg)));
764 base_buff = buff;
765 args = (macro_arg *) buff->base;
766 memset (args, 0, argc * sizeof (macro_arg));
767 buff->cur = (unsigned char *) &args[argc];
768 arg = args, argc = 0;
770 /* Collect the tokens making up each argument. We don't yet know
771 how many arguments have been supplied, whether too many or too
772 few. Hence the slightly bizarre usage of "argc" and "arg". */
775 unsigned int paren_depth = 0;
776 unsigned int ntokens = 0;
777 unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
778 num_args_alloced++;
780 argc++;
781 arg->first = (const cpp_token **) buff->cur;
782 if (track_macro_expansion_p)
784 virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
785 arg->virt_locs = XNEWVEC (source_location,
786 virt_locs_capacity);
789 for (;;)
791 /* Require space for 2 new tokens (including a CPP_EOF). */
792 if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
794 buff = _cpp_append_extend_buff (pfile, buff,
795 ARG_TOKENS_EXTENT
796 * sizeof (cpp_token *));
797 arg->first = (const cpp_token **) buff->cur;
799 if (track_macro_expansion_p
800 && (ntokens + 2 > virt_locs_capacity))
802 virt_locs_capacity += ARG_TOKENS_EXTENT;
803 arg->virt_locs = XRESIZEVEC (source_location,
804 arg->virt_locs,
805 virt_locs_capacity);
808 token = cpp_get_token_1 (pfile, &virt_loc);
810 if (token->type == CPP_PADDING)
812 /* Drop leading padding. */
813 if (ntokens == 0)
814 continue;
816 else if (token->type == CPP_OPEN_PAREN)
817 paren_depth++;
818 else if (token->type == CPP_CLOSE_PAREN)
820 if (paren_depth-- == 0)
821 break;
823 else if (token->type == CPP_COMMA)
825 /* A comma does not terminate an argument within
826 parentheses or as part of a variable argument. */
827 if (paren_depth == 0
828 && ! (macro->variadic && argc == macro->paramc))
829 break;
831 else if (token->type == CPP_EOF
832 || (token->type == CPP_HASH && token->flags & BOL))
833 break;
834 else if (token->type == CPP_PRAGMA)
836 cpp_token *newtok = _cpp_temp_token (pfile);
838 /* CPP_PRAGMA token lives in directive_result, which will
839 be overwritten on the next directive. */
840 *newtok = *token;
841 token = newtok;
844 if (*pragma_buff == NULL
845 || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
847 _cpp_buff *next;
848 if (*pragma_buff == NULL)
849 *pragma_buff
850 = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
851 else
853 next = *pragma_buff;
854 *pragma_buff
855 = _cpp_get_buff (pfile,
856 (BUFF_FRONT (*pragma_buff)
857 - (*pragma_buff)->base) * 2);
858 (*pragma_buff)->next = next;
861 *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
862 BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
863 if (token->type == CPP_PRAGMA_EOL)
864 break;
865 token = cpp_get_token_1 (pfile, &virt_loc);
867 while (token->type != CPP_EOF);
869 /* In deferred pragmas parsing_args and prevent_expansion
870 had been changed, reset it. */
871 pfile->state.parsing_args = 2;
872 pfile->state.prevent_expansion = 1;
874 if (token->type == CPP_EOF)
875 break;
876 else
877 continue;
879 set_arg_token (arg, token, virt_loc,
880 ntokens, MACRO_ARG_TOKEN_NORMAL,
881 CPP_OPTION (pfile, track_macro_expansion));
882 ntokens++;
885 /* Drop trailing padding. */
886 while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
887 ntokens--;
889 arg->count = ntokens;
890 set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
891 ntokens, MACRO_ARG_TOKEN_NORMAL,
892 CPP_OPTION (pfile, track_macro_expansion));
894 /* Terminate the argument. Excess arguments loop back and
895 overwrite the final legitimate argument, before failing. */
896 if (argc <= macro->paramc)
898 buff->cur = (unsigned char *) &arg->first[ntokens + 1];
899 if (argc != macro->paramc)
900 arg++;
903 while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
905 if (token->type == CPP_EOF)
907 /* We still need the CPP_EOF to end directives, and to end
908 pre-expansion of a macro argument. Step back is not
909 unconditional, since we don't want to return a CPP_EOF to our
910 callers at the end of an -include-d file. */
911 if (pfile->context->prev || pfile->state.in_directive)
912 _cpp_backup_tokens (pfile, 1);
913 cpp_error (pfile, CPP_DL_ERROR,
914 "unterminated argument list invoking macro \"%s\"",
915 NODE_NAME (node));
917 else
919 /* A single empty argument is counted as no argument. */
920 if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
921 argc = 0;
922 if (_cpp_arguments_ok (pfile, macro, node, argc))
924 /* GCC has special semantics for , ## b where b is a varargs
925 parameter: we remove the comma if b was omitted entirely.
926 If b was merely an empty argument, the comma is retained.
927 If the macro takes just one (varargs) parameter, then we
928 retain the comma only if we are standards conforming.
930 If FIRST is NULL replace_args () swallows the comma. */
931 if (macro->variadic && (argc < macro->paramc
932 || (argc == 1 && args[0].count == 0
933 && !CPP_OPTION (pfile, std))))
934 args[macro->paramc - 1].first = NULL;
935 if (num_args)
936 *num_args = num_args_alloced;
937 return base_buff;
941 /* An error occurred. */
942 _cpp_release_buff (pfile, base_buff);
943 return NULL;
946 /* Search for an opening parenthesis to the macro of NODE, in such a
947 way that, if none is found, we don't lose the information in any
948 intervening padding tokens. If we find the parenthesis, collect
949 the arguments and return the buffer containing them. PRAGMA_BUFF
950 argument is the same as in collect_args. If NUM_ARGS is non-NULL,
951 *NUM_ARGS is set to the number of arguments contained in the
952 returned buffer. */
953 static _cpp_buff *
954 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
955 _cpp_buff **pragma_buff, unsigned *num_args)
957 const cpp_token *token, *padding = NULL;
959 for (;;)
961 token = cpp_get_token (pfile);
962 if (token->type != CPP_PADDING)
963 break;
964 if (padding == NULL
965 || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
966 padding = token;
969 if (token->type == CPP_OPEN_PAREN)
971 pfile->state.parsing_args = 2;
972 return collect_args (pfile, node, pragma_buff, num_args);
975 /* CPP_EOF can be the end of macro arguments, or the end of the
976 file. We mustn't back up over the latter. Ugh. */
977 if (token->type != CPP_EOF || token == &pfile->eof)
979 /* Back up. We may have skipped padding, in which case backing
980 up more than one token when expanding macros is in general
981 too difficult. We re-insert it in its own context. */
982 _cpp_backup_tokens (pfile, 1);
983 if (padding)
984 _cpp_push_token_context (pfile, NULL, padding, 1);
987 return NULL;
990 /* Return the real number of tokens in the expansion of MACRO. */
991 static inline unsigned int
992 macro_real_token_count (const cpp_macro *macro)
994 unsigned int i;
995 if (__builtin_expect (!macro->extra_tokens, true))
996 return macro->count;
997 for (i = 0; i < macro->count; i++)
998 if (macro->exp.tokens[i].type == CPP_PASTE)
999 return i;
1000 abort ();
1003 /* Push the context of a macro with hash entry NODE onto the context
1004 stack. If we can successfully expand the macro, we push a context
1005 containing its yet-to-be-rescanned replacement list and return one.
1006 If there were additionally any unexpanded deferred #pragma
1007 directives among macro arguments, push another context containing
1008 the pragma tokens before the yet-to-be-rescanned replacement list
1009 and return two. Otherwise, we don't push a context and return
1010 zero. LOCATION is the location of the expansion point of the
1011 macro. */
1012 static int
1013 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1014 const cpp_token *result, source_location location)
1016 /* The presence of a macro invalidates a file's controlling macro. */
1017 pfile->mi_valid = false;
1019 pfile->state.angled_headers = false;
1021 if ((node->flags & NODE_BUILTIN) && !(node->flags & NODE_USED))
1023 node->flags |= NODE_USED;
1024 if ((!pfile->cb.user_builtin_macro
1025 || !pfile->cb.user_builtin_macro (pfile, node))
1026 && pfile->cb.used_define)
1027 pfile->cb.used_define (pfile, pfile->directive_line, node);
1030 /* Handle standard macros. */
1031 if (! (node->flags & NODE_BUILTIN))
1033 cpp_macro *macro = node->value.macro;
1034 _cpp_buff *pragma_buff = NULL;
1036 if (macro->fun_like)
1038 _cpp_buff *buff;
1039 unsigned num_args = 0;
1041 pfile->state.prevent_expansion++;
1042 pfile->keep_tokens++;
1043 pfile->state.parsing_args = 1;
1044 buff = funlike_invocation_p (pfile, node, &pragma_buff,
1045 &num_args);
1046 pfile->state.parsing_args = 0;
1047 pfile->keep_tokens--;
1048 pfile->state.prevent_expansion--;
1050 if (buff == NULL)
1052 if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1053 cpp_warning (pfile, CPP_W_TRADITIONAL,
1054 "function-like macro \"%s\" must be used with arguments in traditional C",
1055 NODE_NAME (node));
1057 if (pragma_buff)
1058 _cpp_release_buff (pfile, pragma_buff);
1060 return 0;
1063 if (macro->paramc > 0)
1064 replace_args (pfile, node, macro,
1065 (macro_arg *) buff->base,
1066 location);
1067 /* Free the memory used by the arguments of this
1068 function-like macro. This memory has been allocated by
1069 funlike_invocation_p and by replace_args. */
1070 delete_macro_args (buff, num_args);
1073 /* Disable the macro within its expansion. */
1074 node->flags |= NODE_DISABLED;
1076 if (!(node->flags & NODE_USED))
1078 node->flags |= NODE_USED;
1079 if (pfile->cb.used_define)
1080 pfile->cb.used_define (pfile, pfile->directive_line, node);
1083 if (pfile->cb.used)
1084 pfile->cb.used (pfile, location, node);
1086 macro->used = 1;
1088 if (macro->paramc == 0)
1090 if (CPP_OPTION (pfile, track_macro_expansion))
1092 unsigned int i, count = macro->count;
1093 const cpp_token *src = macro->exp.tokens;
1094 const struct line_map *map;
1095 source_location *virt_locs = NULL;
1096 _cpp_buff *macro_tokens =
1097 tokens_buff_new (pfile, count, &virt_locs);
1099 /* Create a macro map to record the locations of the
1100 tokens that are involved in the expansion. LOCATION
1101 is the location of the macro expansion point. */
1102 map = linemap_enter_macro (pfile->line_table,
1103 node, location, count);
1104 for (i = 0; i < count; ++i)
1106 tokens_buff_add_token (macro_tokens, virt_locs,
1107 src, src->src_loc,
1108 src->src_loc, map, i);
1109 ++src;
1111 push_extended_tokens_context (pfile, node,
1112 macro_tokens,
1113 virt_locs,
1114 (const cpp_token **)
1115 macro_tokens->base,
1116 count);
1117 num_macro_tokens_counter += count;
1119 else
1121 unsigned tokens_count = macro_real_token_count (macro);
1122 _cpp_push_token_context (pfile, node, macro->exp.tokens,
1123 tokens_count);
1124 num_macro_tokens_counter += tokens_count;
1128 if (pragma_buff)
1130 if (!pfile->state.in_directive)
1131 _cpp_push_token_context (pfile, NULL,
1132 padding_token (pfile, result), 1);
1135 unsigned tokens_count;
1136 _cpp_buff *tail = pragma_buff->next;
1137 pragma_buff->next = NULL;
1138 tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1139 - (const cpp_token **) pragma_buff->base);
1140 push_ptoken_context (pfile, NULL, pragma_buff,
1141 (const cpp_token **) pragma_buff->base,
1142 tokens_count);
1143 pragma_buff = tail;
1144 if (!CPP_OPTION (pfile, track_macro_expansion))
1145 num_macro_tokens_counter += tokens_count;
1148 while (pragma_buff != NULL);
1149 return 2;
1152 return 1;
1155 /* Handle built-in macros and the _Pragma operator. */
1156 return builtin_macro (pfile, node);
1159 /* De-allocate the memory used by BUFF which is an array of instances
1160 of macro_arg. NUM_ARGS is the number of instances of macro_arg
1161 present in BUFF. */
1162 static void
1163 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1165 macro_arg *macro_args;
1166 unsigned i;
1168 if (buff == NULL)
1169 return;
1171 macro_args = (macro_arg *) buff->base;
1173 /* Walk instances of macro_arg to free their expanded tokens as well
1174 as their macro_arg::virt_locs members. */
1175 for (i = 0; i < num_args; ++i)
1177 if (macro_args[i].expanded)
1179 free (macro_args[i].expanded);
1180 macro_args[i].expanded = NULL;
1182 if (macro_args[i].virt_locs)
1184 free (macro_args[i].virt_locs);
1185 macro_args[i].virt_locs = NULL;
1187 if (macro_args[i].expanded_virt_locs)
1189 free (macro_args[i].expanded_virt_locs);
1190 macro_args[i].expanded_virt_locs = NULL;
1193 _cpp_free_buff (buff);
1196 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1197 to set, LOCATION is its virtual location. "Virtual" location means
1198 the location that encodes loci accross macro expansion. Otherwise
1199 it has to be TOKEN->SRC_LOC. KIND is the kind of tokens the
1200 argument ARG is supposed to contain. Note that ARG must be
1201 tailored so that it has enough room to contain INDEX + 1 numbers of
1202 tokens, at least. */
1203 static void
1204 set_arg_token (macro_arg *arg, const cpp_token *token,
1205 source_location location, size_t index,
1206 enum macro_arg_token_kind kind,
1207 bool track_macro_exp_p)
1209 const cpp_token **token_ptr;
1210 source_location *loc = NULL;
1212 token_ptr =
1213 arg_token_ptr_at (arg, index, kind,
1214 track_macro_exp_p ? &loc : NULL);
1215 *token_ptr = token;
1217 if (loc != NULL)
1219 #ifdef ENABLE_CHECKING
1220 if (kind == MACRO_ARG_TOKEN_STRINGIFIED
1221 || !track_macro_exp_p)
1222 /* We can't set the location of a stringified argument
1223 token and we can't set any location if we aren't tracking
1224 macro expansion locations. */
1225 abort ();
1226 #endif
1227 *loc = location;
1231 /* Get the pointer to the location of the argument token of the
1232 function-like macro argument ARG. This function must be called
1233 only when we -ftrack-macro-expansion is on. */
1234 static const source_location *
1235 get_arg_token_location (const macro_arg *arg,
1236 enum macro_arg_token_kind kind)
1238 const source_location *loc = NULL;
1239 const cpp_token **token_ptr =
1240 arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1242 if (token_ptr == NULL)
1243 return NULL;
1245 return loc;
1248 /* Return the pointer to the INDEXth token of the macro argument ARG.
1249 KIND specifies the kind of token the macro argument ARG contains.
1250 If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1251 of the virtual location of the returned token if the
1252 -ftrack-macro-expansion flag is on; otherwise, it's set to the
1253 spelling location of the returned token. */
1254 static const cpp_token **
1255 arg_token_ptr_at (const macro_arg *arg, size_t index,
1256 enum macro_arg_token_kind kind,
1257 source_location **virt_location)
1259 const cpp_token **tokens_ptr = NULL;
1261 switch (kind)
1263 case MACRO_ARG_TOKEN_NORMAL:
1264 tokens_ptr = arg->first;
1265 break;
1266 case MACRO_ARG_TOKEN_STRINGIFIED:
1267 tokens_ptr = (const cpp_token **) &arg->stringified;
1268 break;
1269 case MACRO_ARG_TOKEN_EXPANDED:
1270 tokens_ptr = arg->expanded;
1271 break;
1274 if (tokens_ptr == NULL)
1275 /* This can happen for e.g, an empty token argument to a
1276 funtion-like macro. */
1277 return tokens_ptr;
1279 if (virt_location)
1281 if (kind == MACRO_ARG_TOKEN_NORMAL)
1282 *virt_location = &arg->virt_locs[index];
1283 else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1284 *virt_location = &arg->expanded_virt_locs[index];
1285 else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1286 *virt_location =
1287 (source_location *) &tokens_ptr[index]->src_loc;
1289 return &tokens_ptr[index];
1292 /* Initialize an iterator so that it iterates over the tokens of a
1293 function-like macro argument. KIND is the kind of tokens we want
1294 ITER to iterate over. TOKEN_PTR points the first token ITER will
1295 iterate over. */
1296 static void
1297 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1298 bool track_macro_exp_p,
1299 enum macro_arg_token_kind kind,
1300 const macro_arg *arg,
1301 const cpp_token **token_ptr)
1303 iter->track_macro_exp_p = track_macro_exp_p;
1304 iter->kind = kind;
1305 iter->token_ptr = token_ptr;
1306 /* Unconditionally initialize this so that the compiler doesn't warn
1307 about iter->location_ptr being possibly uninitialized later after
1308 this code has been inlined somewhere. */
1309 iter->location_ptr = NULL;
1310 if (track_macro_exp_p)
1311 iter->location_ptr = get_arg_token_location (arg, kind);
1312 #ifdef ENABLE_CHECKING
1313 iter->num_forwards = 0;
1314 if (track_macro_exp_p
1315 && token_ptr != NULL
1316 && iter->location_ptr == NULL)
1317 abort ();
1318 #endif
1321 /* Move the iterator one token forward. Note that if IT was
1322 initialized on an argument that has a stringified token, moving it
1323 foward doesn't make sense as a stringified token is essentially one
1324 string. */
1325 static void
1326 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1328 switch (it->kind)
1330 case MACRO_ARG_TOKEN_NORMAL:
1331 case MACRO_ARG_TOKEN_EXPANDED:
1332 it->token_ptr++;
1333 if (it->track_macro_exp_p)
1334 it->location_ptr++;
1335 break;
1336 case MACRO_ARG_TOKEN_STRINGIFIED:
1337 #ifdef ENABLE_CHECKING
1338 if (it->num_forwards > 0)
1339 abort ();
1340 #endif
1341 break;
1344 #ifdef ENABLE_CHECKING
1345 it->num_forwards++;
1346 #endif
1349 /* Return the token pointed to by the iterator. */
1350 static const cpp_token *
1351 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1353 #ifdef ENABLE_CHECKING
1354 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1355 && it->num_forwards > 0)
1356 abort ();
1357 #endif
1358 if (it->token_ptr == NULL)
1359 return NULL;
1360 return *it->token_ptr;
1363 /* Return the location of the token pointed to by the iterator.*/
1364 static source_location
1365 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1367 #ifdef ENABLE_CHECKING
1368 if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1369 && it->num_forwards > 0)
1370 abort ();
1371 #endif
1372 if (it->track_macro_exp_p)
1373 return *it->location_ptr;
1374 else
1375 return (*it->token_ptr)->src_loc;
1378 /* Return the index of a token [resulting from macro expansion] inside
1379 the total list of tokens resulting from a given macro
1380 expansion. The index can be different depending on whether if we
1381 want each tokens resulting from function-like macro arguments
1382 expansion to have a different location or not.
1384 E.g, consider this function-like macro:
1386 #define M(x) x - 3
1388 Then consider us "calling" it (and thus expanding it) like:
1390 M(1+4)
1392 It will be expanded into:
1394 1+4-3
1396 Let's consider the case of the token '4'.
1398 Its index can be 2 (it's the third token of the set of tokens
1399 resulting from the expansion) or it can be 0 if we consider that
1400 all tokens resulting from the expansion of the argument "1+2" have
1401 the same index, which is 0. In this later case, the index of token
1402 '-' would then be 1 and the index of token '3' would be 2.
1404 The later case is useful to use less memory e.g, for the case of
1405 the user using the option -ftrack-macro-expansion=1.
1407 ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1408 are interested in. CUR_REPLACEMENT_TOKEN is the token of the macro
1409 parameter (inside the macro replacement list) that corresponds to
1410 the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1413 If we refer to the example above, for the '4' argument token,
1414 ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1415 would be set to the token 'x', in the replacement list "x - 3" of
1416 macro M.
1418 This is a subroutine of replace_args. */
1419 inline static unsigned
1420 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1421 const cpp_token *cur_replacement_token,
1422 unsigned absolute_token_index)
1424 if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1425 return absolute_token_index;
1426 return cur_replacement_token - macro->exp.tokens;
1429 /* Replace the parameters in a function-like macro of NODE with the
1430 actual ARGS, and place the result in a newly pushed token context.
1431 Expand each argument before replacing, unless it is operated upon
1432 by the # or ## operators. EXPANSION_POINT_LOC is the location of
1433 the expansion point of the macro. E.g, the location of the
1434 function-like macro invocation. */
1435 static void
1436 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1437 macro_arg *args, source_location expansion_point_loc)
1439 unsigned int i, total;
1440 const cpp_token *src, *limit;
1441 const cpp_token **first = NULL;
1442 macro_arg *arg;
1443 _cpp_buff *buff = NULL;
1444 source_location *virt_locs = NULL;
1445 unsigned int exp_count;
1446 const struct line_map *map = NULL;
1447 int track_macro_exp;
1449 /* First, fully macro-expand arguments, calculating the number of
1450 tokens in the final expansion as we go. The ordering of the if
1451 statements below is subtle; we must handle stringification before
1452 pasting. */
1454 /* EXP_COUNT is the number of tokens in the macro replacement
1455 list. TOTAL is the number of tokens /after/ macro parameters
1456 have been replaced by their arguments. */
1457 exp_count = macro_real_token_count (macro);
1458 total = exp_count;
1459 limit = macro->exp.tokens + exp_count;
1461 for (src = macro->exp.tokens; src < limit; src++)
1462 if (src->type == CPP_MACRO_ARG)
1464 /* Leading and trailing padding tokens. */
1465 total += 2;
1466 /* Account for leading and padding tokens in exp_count too.
1467 This is going to be important later down this function,
1468 when we want to handle the case of (track_macro_exp <
1469 2). */
1470 exp_count += 2;
1472 /* We have an argument. If it is not being stringified or
1473 pasted it is macro-replaced before insertion. */
1474 arg = &args[src->val.macro_arg.arg_no - 1];
1476 if (src->flags & STRINGIFY_ARG)
1478 if (!arg->stringified)
1479 arg->stringified = stringify_arg (pfile, arg);
1481 else if ((src->flags & PASTE_LEFT)
1482 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1483 total += arg->count - 1;
1484 else
1486 if (!arg->expanded)
1487 expand_arg (pfile, arg);
1488 total += arg->expanded_count - 1;
1492 /* When the compiler is called with the -ftrack-macro-expansion
1493 flag, we need to keep track of the location of each token that
1494 results from macro expansion.
1496 A token resulting from macro expansion is not a new token. It is
1497 simply the same token as the token coming from the macro
1498 definition. The new things that are allocated are the buffer
1499 that holds the tokens resulting from macro expansion and a new
1500 location that records many things like the locus of the expansion
1501 point as well as the original locus inside the definition of the
1502 macro. This location is called a virtual location.
1504 So the buffer BUFF holds a set of cpp_token*, and the buffer
1505 VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1507 Both of these two buffers are going to be hung off of the macro
1508 context, when the latter is pushed. The memory allocated to
1509 store the tokens and their locations is going to be freed once
1510 the context of macro expansion is popped.
1512 As far as tokens are concerned, the memory overhead of
1513 -ftrack-macro-expansion is proportional to the number of
1514 macros that get expanded multiplied by sizeof (source_location).
1515 The good news is that extra memory gets freed when the macro
1516 context is freed, i.e shortly after the macro got expanded. */
1518 /* Is the -ftrack-macro-expansion flag in effect? */
1519 track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1521 /* Now allocate memory space for tokens and locations resulting from
1522 the macro expansion, copy the tokens and replace the arguments.
1523 This memory must be freed when the context of the macro MACRO is
1524 popped. */
1525 buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1527 first = (const cpp_token **) buff->base;
1529 /* Create a macro map to record the locations of the tokens that are
1530 involved in the expansion. Note that the expansion point is set
1531 to the location of the closing parenthesis. Otherwise, the
1532 subsequent map created for the first token that comes after the
1533 macro map might have a wrong line number. That would lead to
1534 tokens with wrong line numbers after the macro expansion. This
1535 adds up to the memory overhead of the -ftrack-macro-expansion
1536 flag; for every macro that is expanded, a "macro map" is
1537 created. */
1538 if (track_macro_exp)
1540 int num_macro_tokens = total;
1541 if (track_macro_exp < 2)
1542 /* Then the number of macro tokens won't take in account the
1543 fact that function-like macro arguments can expand to
1544 multiple tokens. This is to save memory at the expense of
1545 accuracy.
1547 Suppose we have #define SQARE(A) A * A
1549 And then we do SQARE(2+3)
1551 Then the tokens 2, +, 3, will have the same location,
1552 saying they come from the expansion of the argument A. */
1553 num_macro_tokens = exp_count;
1554 map = linemap_enter_macro (pfile->line_table, node,
1555 expansion_point_loc,
1556 num_macro_tokens);
1558 i = 0;
1559 for (src = macro->exp.tokens; src < limit; src++)
1561 unsigned int arg_tokens_count;
1562 macro_arg_token_iter from;
1563 const cpp_token **paste_flag = NULL;
1564 const cpp_token **tmp_token_ptr;
1566 if (src->type != CPP_MACRO_ARG)
1568 /* Allocate a virtual location for token SRC, and add that
1569 token and its virtual location into the buffers BUFF and
1570 VIRT_LOCS. */
1571 unsigned index = expanded_token_index (pfile, macro, src, i);
1572 tokens_buff_add_token (buff, virt_locs, src,
1573 src->src_loc, src->src_loc,
1574 map, index);
1575 i += 1;
1576 continue;
1579 paste_flag = 0;
1580 arg = &args[src->val.macro_arg.arg_no - 1];
1581 /* SRC is a macro parameter that we need to replace with its
1582 corresponding argument. So at some point we'll need to
1583 iterate over the tokens of the macro argument and copy them
1584 into the "place" now holding the correspondig macro
1585 parameter. We are going to use the iterator type
1586 macro_argo_token_iter to handle that iterating. The 'if'
1587 below is to initialize the iterator depending on the type of
1588 tokens the macro argument has. It also does some adjustment
1589 related to padding tokens and some pasting corner cases. */
1590 if (src->flags & STRINGIFY_ARG)
1592 arg_tokens_count = 1;
1593 macro_arg_token_iter_init (&from,
1594 CPP_OPTION (pfile,
1595 track_macro_expansion),
1596 MACRO_ARG_TOKEN_STRINGIFIED,
1597 arg, &arg->stringified);
1599 else if (src->flags & PASTE_LEFT)
1601 arg_tokens_count = arg->count;
1602 macro_arg_token_iter_init (&from,
1603 CPP_OPTION (pfile,
1604 track_macro_expansion),
1605 MACRO_ARG_TOKEN_NORMAL,
1606 arg, arg->first);
1608 else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1610 int num_toks;
1611 arg_tokens_count = arg->count;
1612 macro_arg_token_iter_init (&from,
1613 CPP_OPTION (pfile,
1614 track_macro_expansion),
1615 MACRO_ARG_TOKEN_NORMAL,
1616 arg, arg->first);
1618 num_toks = tokens_buff_count (buff);
1620 if (num_toks != 0)
1622 /* So the current parameter token is pasted to the previous
1623 token in the replacement list. Let's look at what
1624 we have as previous and current arguments. */
1626 /* This is the previous argument's token ... */
1627 tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1629 if ((*tmp_token_ptr)->type == CPP_COMMA
1630 && macro->variadic
1631 && src->val.macro_arg.arg_no == macro->paramc)
1633 /* ... which is a comma; and the current parameter
1634 is the last parameter of a variadic function-like
1635 macro. If the argument to the current last
1636 parameter is NULL, then swallow the comma,
1637 otherwise drop the paste flag. */
1638 if (macro_arg_token_iter_get_token (&from) == NULL)
1639 tokens_buff_remove_last_token (buff);
1640 else
1641 paste_flag = tmp_token_ptr;
1643 /* Remove the paste flag if the RHS is a placemarker. */
1644 else if (arg_tokens_count == 0)
1645 paste_flag = tmp_token_ptr;
1648 else
1650 arg_tokens_count = arg->expanded_count;
1651 macro_arg_token_iter_init (&from,
1652 CPP_OPTION (pfile,
1653 track_macro_expansion),
1654 MACRO_ARG_TOKEN_EXPANDED,
1655 arg, arg->expanded);
1658 /* Padding on the left of an argument (unless RHS of ##). */
1659 if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1660 && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1662 const cpp_token *t = padding_token (pfile, src);
1663 unsigned index = expanded_token_index (pfile, macro, src, i);
1664 /* Allocate a virtual location for the padding token and
1665 append the token and its location to BUFF and
1666 VIRT_LOCS. */
1667 tokens_buff_add_token (buff, virt_locs, t,
1668 t->src_loc, t->src_loc,
1669 map, index);
1672 if (arg_tokens_count)
1674 /* So now we've got the number of tokens that make up the
1675 argument that is going to replace the current parameter
1676 in the macro's replacement list. */
1677 unsigned int j;
1678 for (j = 0; j < arg_tokens_count; ++j)
1680 /* So if track_macro_exp is < 2, the user wants to
1681 save extra memory while tracking macro expansion
1682 locations. So in that case here is what we do:
1684 Suppose we have #define SQARE(A) A * A
1686 And then we do SQARE(2+3)
1688 Then the tokens 2, +, 3, will have the same location,
1689 saying they come from the expansion of the argument
1692 So that means we are going to ignore the COUNT tokens
1693 resulting from the expansion of the current macro
1694 arugment. In other words all the ARG_TOKENS_COUNT tokens
1695 resulting from the expansion of the macro argument will
1696 have the index I. Normally, each of those token should
1697 have index I+J. */
1698 unsigned token_index = i;
1699 unsigned index;
1700 if (track_macro_exp > 1)
1701 token_index += j;
1703 index = expanded_token_index (pfile, macro, src, token_index);
1704 tokens_buff_add_token (buff, virt_locs,
1705 macro_arg_token_iter_get_token (&from),
1706 macro_arg_token_iter_get_location (&from),
1707 src->src_loc, map, index);
1708 macro_arg_token_iter_forward (&from);
1711 /* With a non-empty argument on the LHS of ##, the last
1712 token should be flagged PASTE_LEFT. */
1713 if (src->flags & PASTE_LEFT)
1714 paste_flag =
1715 (const cpp_token **) tokens_buff_last_token_ptr (buff);
1717 else if (CPP_PEDANTIC (pfile) && ! macro->syshdr
1718 && ! CPP_OPTION (pfile, c99)
1719 && ! cpp_in_system_header (pfile))
1721 cpp_error (pfile, CPP_DL_PEDWARN,
1722 "invoking macro %s argument %d: "
1723 "empty macro arguments are undefined"
1724 " in ISO C90 and ISO C++98",
1725 NODE_NAME (node),
1726 src->val.macro_arg.arg_no);
1729 /* Avoid paste on RHS (even case count == 0). */
1730 if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
1732 const cpp_token *t = &pfile->avoid_paste;
1733 tokens_buff_add_token (buff, virt_locs,
1734 t, t->src_loc, t->src_loc,
1735 NULL, 0);
1738 /* Add a new paste flag, or remove an unwanted one. */
1739 if (paste_flag)
1741 cpp_token *token = _cpp_temp_token (pfile);
1742 token->type = (*paste_flag)->type;
1743 token->val = (*paste_flag)->val;
1744 if (src->flags & PASTE_LEFT)
1745 token->flags = (*paste_flag)->flags | PASTE_LEFT;
1746 else
1747 token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1748 *paste_flag = token;
1751 i += arg_tokens_count;
1754 if (track_macro_exp)
1755 push_extended_tokens_context (pfile, node, buff, virt_locs, first,
1756 tokens_buff_count (buff));
1757 else
1758 push_ptoken_context (pfile, node, buff, first,
1759 tokens_buff_count (buff));
1761 num_macro_tokens_counter += tokens_buff_count (buff);
1764 /* Return a special padding token, with padding inherited from SOURCE. */
1765 static const cpp_token *
1766 padding_token (cpp_reader *pfile, const cpp_token *source)
1768 cpp_token *result = _cpp_temp_token (pfile);
1770 result->type = CPP_PADDING;
1772 /* Data in GCed data structures cannot be made const so far, so we
1773 need a cast here. */
1774 result->val.source = (cpp_token *) source;
1775 result->flags = 0;
1776 return result;
1779 /* Get a new uninitialized context. Create a new one if we cannot
1780 re-use an old one. */
1781 static cpp_context *
1782 next_context (cpp_reader *pfile)
1784 cpp_context *result = pfile->context->next;
1786 if (result == 0)
1788 result = XNEW (cpp_context);
1789 memset (result, 0, sizeof (cpp_context));
1790 result->prev = pfile->context;
1791 result->next = 0;
1792 pfile->context->next = result;
1795 pfile->context = result;
1796 return result;
1799 /* Push a list of pointers to tokens. */
1800 static void
1801 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
1802 const cpp_token **first, unsigned int count)
1804 cpp_context *context = next_context (pfile);
1806 context->tokens_kind = TOKENS_KIND_INDIRECT;
1807 context->c.macro = macro;
1808 context->buff = buff;
1809 FIRST (context).ptoken = first;
1810 LAST (context).ptoken = first + count;
1813 /* Push a list of tokens.
1815 A NULL macro means that we should continue the current macro
1816 expansion, in essence. That means that if we are currently in a
1817 macro expansion context, we'll make the new pfile->context refer to
1818 the current macro. */
1819 void
1820 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
1821 const cpp_token *first, unsigned int count)
1823 cpp_context *context;
1825 if (macro == NULL)
1826 macro = macro_of_context (pfile->context);
1828 context = next_context (pfile);
1829 context->tokens_kind = TOKENS_KIND_DIRECT;
1830 context->c.macro = macro;
1831 context->buff = NULL;
1832 FIRST (context).token = first;
1833 LAST (context).token = first + count;
1836 /* Build a context containing a list of tokens as well as their
1837 virtual locations and push it. TOKENS_BUFF is the buffer that
1838 contains the tokens pointed to by FIRST. If TOKENS_BUFF is
1839 non-NULL, it means that the context owns it, meaning that
1840 _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
1841 contains the virtual locations.
1843 A NULL macro means that we should continue the current macro
1844 expansion, in essence. That means that if we are currently in a
1845 macro expansion context, we'll make the new pfile->context refer to
1846 the current macro. */
1847 static void
1848 push_extended_tokens_context (cpp_reader *pfile,
1849 cpp_hashnode *macro,
1850 _cpp_buff *token_buff,
1851 source_location *virt_locs,
1852 const cpp_token **first,
1853 unsigned int count)
1855 cpp_context *context;
1856 macro_context *m;
1858 if (macro == NULL)
1859 macro = macro_of_context (pfile->context);
1861 context = next_context (pfile);
1862 context->tokens_kind = TOKENS_KIND_EXTENDED;
1863 context->buff = token_buff;
1865 m = XNEW (macro_context);
1866 m->macro_node = macro;
1867 m->virt_locs = virt_locs;
1868 m->cur_virt_loc = virt_locs;
1869 context->c.mc = m;
1870 FIRST (context).ptoken = first;
1871 LAST (context).ptoken = first + count;
1874 /* Push a traditional macro's replacement text. */
1875 void
1876 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
1877 const uchar *start, size_t len)
1879 cpp_context *context = next_context (pfile);
1881 context->tokens_kind = TOKENS_KIND_DIRECT;
1882 context->c.macro = macro;
1883 context->buff = NULL;
1884 CUR (context) = start;
1885 RLIMIT (context) = start + len;
1886 macro->flags |= NODE_DISABLED;
1889 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
1890 for the purpose of storing them on a cpp_context. If VIRT_LOCS is
1891 non-null (which means that -ftrack-macro-expansion is on),
1892 *VIRT_LOCS is set to a newly allocated buffer that is supposed to
1893 hold the virtual locations of the tokens resulting from macro
1894 expansion. */
1895 static _cpp_buff*
1896 tokens_buff_new (cpp_reader *pfile, size_t len,
1897 source_location **virt_locs)
1899 size_t tokens_size = len * sizeof (cpp_token *);
1900 size_t locs_size = len * sizeof (source_location);
1902 if (virt_locs != NULL)
1903 *virt_locs = XNEWVEC (source_location, locs_size);
1904 return _cpp_get_buff (pfile, tokens_size);
1907 /* Returns the number of tokens contained in a token buffer. The
1908 buffer holds a set of cpp_token*. */
1909 static size_t
1910 tokens_buff_count (_cpp_buff *buff)
1912 return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
1915 /* Return a pointer to the last token contained in the token buffer
1916 BUFF. */
1917 static const cpp_token **
1918 tokens_buff_last_token_ptr (_cpp_buff *buff)
1920 return &((const cpp_token **) BUFF_FRONT (buff))[-1];
1923 /* Remove the last token contained in the token buffer TOKENS_BUFF.
1924 If VIRT_LOCS_BUFF is non-NULL, it should point at the buffer
1925 containing the virtual locations of the tokens in TOKENS_BUFF; in
1926 which case the function updates that buffer as well. */
1927 static inline void
1928 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
1931 if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
1932 BUFF_FRONT (tokens_buff) =
1933 (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
1936 /* Insert a token into the token buffer at the position pointed to by
1937 DEST. Note that the buffer is not enlarged so the previous token
1938 that was at *DEST is overwritten. VIRT_LOC_DEST, if non-null,
1939 means -ftrack-macro-expansion is effect; it then points to where to
1940 insert the virtual location of TOKEN. TOKEN is the token to
1941 insert. VIRT_LOC is the virtual location of the token, i.e, the
1942 location possibly encoding its locus accross macro expansion. If
1943 TOKEN is an argument of a function-like macro (inside a macro
1944 replacement list), PARM_DEF_LOC is the spelling location of the
1945 macro parameter that TOKEN is replacing, in the replacement list of
1946 the macro. If TOKEN is not an argument of a function-like macro or
1947 if it doesn't come from a macro expansion, then VIRT_LOC can just
1948 be set to the same value as PARM_DEF_LOC. If MAP is non null, it
1949 means TOKEN comes from a macro expansion and MAP is the macro map
1950 associated to the macro. MACRO_TOKEN_INDEX points to the index of
1951 the token in the macro map; it is not considered if MAP is NULL.
1953 Upon successful completion this function returns the a pointer to
1954 the position of the token coming right after the insertion
1955 point. */
1956 static inline const cpp_token **
1957 tokens_buff_put_token_to (const cpp_token **dest,
1958 source_location *virt_loc_dest,
1959 const cpp_token *token,
1960 source_location virt_loc,
1961 source_location parm_def_loc,
1962 const struct line_map *map,
1963 unsigned int macro_token_index)
1965 source_location macro_loc = virt_loc;
1966 const cpp_token **result;
1968 if (virt_loc_dest)
1970 /* -ftrack-macro-expansion is on. */
1971 if (map)
1972 macro_loc = linemap_add_macro_token (map, macro_token_index,
1973 virt_loc, parm_def_loc);
1974 *virt_loc_dest = macro_loc;
1976 *dest = token;
1977 result = &dest[1];
1979 return result;
1982 /* Adds a token at the end of the tokens contained in BUFFER. Note
1983 that this function doesn't enlarge BUFFER when the number of tokens
1984 reaches BUFFER's size; it aborts in that situation.
1986 TOKEN is the token to append. VIRT_LOC is the virtual location of
1987 the token, i.e, the location possibly encoding its locus accross
1988 macro expansion. If TOKEN is an argument of a function-like macro
1989 (inside a macro replacement list), PARM_DEF_LOC is the location of
1990 the macro parameter that TOKEN is replacing. If TOKEN doesn't come
1991 from a macro expansion, then VIRT_LOC can just be set to the same
1992 value as PARM_DEF_LOC. If MAP is non null, it means TOKEN comes
1993 from a macro expansion and MAP is the macro map associated to the
1994 macro. MACRO_TOKEN_INDEX points to the index of the token in the
1995 macro map; It is not considered if MAP is NULL. If VIRT_LOCS is
1996 non-null, it means -ftrack-macro-expansion is on; in which case
1997 this function adds the virtual location DEF_LOC to the VIRT_LOCS
1998 array, at the same index as the one of TOKEN in BUFFER. Upon
1999 successful completion this function returns the a pointer to the
2000 position of the token coming right after the insertion point. */
2001 static const cpp_token **
2002 tokens_buff_add_token (_cpp_buff *buffer,
2003 source_location *virt_locs,
2004 const cpp_token *token,
2005 source_location virt_loc,
2006 source_location parm_def_loc,
2007 const struct line_map *map,
2008 unsigned int macro_token_index)
2010 const cpp_token **result;
2011 source_location *virt_loc_dest = NULL;
2012 unsigned token_index =
2013 (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2015 /* Abort if we pass the end the buffer. */
2016 if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2017 abort ();
2019 if (virt_locs != NULL)
2020 virt_loc_dest = &virt_locs[token_index];
2022 result =
2023 tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2024 virt_loc_dest, token, virt_loc, parm_def_loc,
2025 map, macro_token_index);
2027 BUFF_FRONT (buffer) = (unsigned char *) result;
2028 return result;
2031 /* Allocate space for the function-like macro argument ARG to store
2032 the tokens resulting from the macro-expansion of the tokens that
2033 make up ARG itself. That space is allocated in ARG->expanded and
2034 needs to be freed using free. */
2035 static void
2036 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2038 #ifdef ENABLE_CHECKING
2039 if (arg->expanded != NULL
2040 || arg->expanded_virt_locs != NULL)
2041 abort ();
2042 #endif
2043 arg->expanded = XNEWVEC (const cpp_token *, capacity);
2044 if (CPP_OPTION (pfile, track_macro_expansion))
2045 arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2049 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2050 tokens. */
2051 static void
2052 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2053 size_t size, size_t *expanded_capacity)
2055 if (size <= *expanded_capacity)
2056 return;
2058 size *= 2;
2060 arg->expanded =
2061 XRESIZEVEC (const cpp_token *, arg->expanded, size);
2062 *expanded_capacity = size;
2064 if (CPP_OPTION (pfile, track_macro_expansion))
2066 if (arg->expanded_virt_locs == NULL)
2067 arg->expanded_virt_locs = XNEWVEC (source_location, size);
2068 else
2069 arg->expanded_virt_locs = XRESIZEVEC (source_location,
2070 arg->expanded_virt_locs,
2071 size);
2075 /* Expand an argument ARG before replacing parameters in a
2076 function-like macro. This works by pushing a context with the
2077 argument's tokens, and then expanding that into a temporary buffer
2078 as if it were a normal part of the token stream. collect_args()
2079 has terminated the argument's tokens with a CPP_EOF so that we know
2080 when we have fully expanded the argument. */
2081 static void
2082 expand_arg (cpp_reader *pfile, macro_arg *arg)
2084 size_t capacity;
2085 bool saved_warn_trad;
2086 bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2088 if (arg->count == 0
2089 || arg->expanded != NULL)
2090 return;
2092 /* Don't warn about funlike macros when pre-expanding. */
2093 saved_warn_trad = CPP_WTRADITIONAL (pfile);
2094 CPP_WTRADITIONAL (pfile) = 0;
2096 /* Loop, reading in the tokens of the argument. */
2097 capacity = 256;
2098 alloc_expanded_arg_mem (pfile, arg, capacity);
2100 if (track_macro_exp_p)
2101 push_extended_tokens_context (pfile, NULL, NULL,
2102 arg->virt_locs,
2103 arg->first,
2104 arg->count + 1);
2105 else
2106 push_ptoken_context (pfile, NULL, NULL,
2107 arg->first, arg->count + 1);
2109 for (;;)
2111 const cpp_token *token;
2112 source_location location;
2114 ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2115 &capacity);
2117 token = cpp_get_token_1 (pfile, &location);
2119 if (token->type == CPP_EOF)
2120 break;
2122 set_arg_token (arg, token, location,
2123 arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2124 CPP_OPTION (pfile, track_macro_expansion));
2125 arg->expanded_count++;
2128 _cpp_pop_context (pfile);
2130 CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2133 /* Returns the macro associated to the current context if we are in
2134 the context a macro expansion, NULL otherwise. */
2135 static cpp_hashnode*
2136 macro_of_context (cpp_context *context)
2138 if (context == NULL)
2139 return NULL;
2141 return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2142 ? context->c.mc->macro_node
2143 : context->c.macro;
2146 /* Pop the current context off the stack, re-enabling the macro if the
2147 context represented a macro's replacement list. Initially the
2148 context structure was not freed so that we can re-use it later, but
2149 now we do free it to reduce peak memory consumption. */
2150 void
2151 _cpp_pop_context (cpp_reader *pfile)
2153 cpp_context *context = pfile->context;
2155 /* We should not be popping the base context. */
2156 if (context == &pfile->base_context)
2157 abort ();
2159 if (context->c.macro)
2161 cpp_hashnode *macro;
2162 if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2164 macro_context *mc = context->c.mc;
2165 macro = mc->macro_node;
2166 /* If context->buff is set, it means the life time of tokens
2167 is bound to the life time of this context; so we must
2168 free the tokens; that means we must free the virtual
2169 locations of these tokens too. */
2170 if (context->buff && mc->virt_locs)
2172 free (mc->virt_locs);
2173 mc->virt_locs = NULL;
2175 free (mc);
2176 context->c.mc = NULL;
2178 else
2179 macro = context->c.macro;
2181 /* Beware that MACRO can be NULL in cases like when we are
2182 called from expand_arg. In those cases, a dummy context with
2183 tokens is pushed just for the purpose of walking them using
2184 cpp_get_token_1. In that case, no 'macro' field is set into
2185 the dummy context. */
2186 if (macro != NULL
2187 /* Several contiguous macro expansion contexts can be
2188 associated to the same macro; that means it's the same
2189 macro expansion that spans accross all these (sub)
2190 contexts. So we should re-enable an expansion-disabled
2191 macro only when we are sure we are really out of that
2192 macro expansion. */
2193 && macro_of_context (context->prev) != macro)
2194 macro->flags &= ~NODE_DISABLED;
2197 if (context->buff)
2199 /* Decrease memory peak consumption by freeing the memory used
2200 by the context. */
2201 _cpp_free_buff (context->buff);
2204 pfile->context = context->prev;
2205 /* decrease peak memory consumption by feeing the context. */
2206 pfile->context->next = NULL;
2207 free (context);
2210 /* Return TRUE if we reached the end of the set of tokens stored in
2211 CONTEXT, FALSE otherwise. */
2212 static inline bool
2213 reached_end_of_context (cpp_context *context)
2215 if (context->tokens_kind == TOKENS_KIND_DIRECT)
2216 return FIRST (context).token == LAST (context).token;
2217 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2218 || context->tokens_kind == TOKENS_KIND_EXTENDED)
2219 return FIRST (context).ptoken == LAST (context).ptoken;
2220 else
2221 abort ();
2224 /* Consume the next token contained in the current context of PFILE,
2225 and return it in *TOKEN. It's "full location" is returned in
2226 *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2227 means the location encoding the locus of the token accross macro
2228 expansion; otherwise it's just is the "normal" location of the
2229 token which (*TOKEN)->src_loc. */
2230 static inline void
2231 consume_next_token_from_context (cpp_reader *pfile,
2232 const cpp_token ** token,
2233 source_location *location)
2235 cpp_context *c = pfile->context;
2237 if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2239 *token = FIRST (c).token;
2240 *location = (*token)->src_loc;
2241 FIRST (c).token++;
2243 else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2245 *token = *FIRST (c).ptoken;
2246 *location = (*token)->src_loc;
2247 FIRST (c).ptoken++;
2249 else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2251 macro_context *m = c->c.mc;
2252 *token = *FIRST (c).ptoken;
2253 if (m->virt_locs)
2255 *location = *m->cur_virt_loc;
2256 m->cur_virt_loc++;
2258 else
2259 *location = (*token)->src_loc;
2260 FIRST (c).ptoken++;
2262 else
2263 abort ();
2266 /* In the traditional mode of the preprocessor, if we are currently in
2267 a directive, the location of a token must be the location of the
2268 start of the directive line. This function returns the proper
2269 location if we are in the traditional mode, and just returns
2270 LOCATION otherwise. */
2272 static inline source_location
2273 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2275 if (CPP_OPTION (pfile, traditional))
2277 if (pfile->state.in_directive)
2278 return pfile->directive_line;
2280 return location;
2283 /* Routine to get a token as well as its location.
2285 Macro expansions and directives are transparently handled,
2286 including entering included files. Thus tokens are post-macro
2287 expansion, and after any intervening directives. External callers
2288 see CPP_EOF only at EOF. Internal callers also see it when meeting
2289 a directive inside a macro call, when at the end of a directive and
2290 state.in_directive is still 1, and at the end of argument
2291 pre-expansion.
2293 LOC is an out parameter; *LOC is set to the location "as expected
2294 by the user". Please read the comment of
2295 cpp_get_token_with_location to learn more about the meaning of this
2296 location. */
2297 static const cpp_token*
2298 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2300 const cpp_token *result;
2301 bool can_set = pfile->set_invocation_location;
2302 /* This token is a virtual token that either encodes a location
2303 related to macro expansion or a spelling location. */
2304 source_location virt_loc = 0;
2305 pfile->set_invocation_location = false;
2307 for (;;)
2309 cpp_hashnode *node;
2310 cpp_context *context = pfile->context;
2312 /* Context->prev == 0 <=> base context. */
2313 if (!context->prev)
2315 result = _cpp_lex_token (pfile);
2316 virt_loc = result->src_loc;
2318 else if (!reached_end_of_context (context))
2320 consume_next_token_from_context (pfile, &result,
2321 &virt_loc);
2322 if (result->flags & PASTE_LEFT)
2324 paste_all_tokens (pfile, result);
2325 if (pfile->state.in_directive)
2326 continue;
2327 result = padding_token (pfile, result);
2328 goto out;
2331 else
2333 if (pfile->context->c.macro)
2334 ++num_expanded_macros_counter;
2335 _cpp_pop_context (pfile);
2336 if (pfile->state.in_directive)
2337 continue;
2338 result = &pfile->avoid_paste;
2339 goto out;
2342 if (pfile->state.in_directive && result->type == CPP_COMMENT)
2343 continue;
2345 if (result->type != CPP_NAME)
2346 break;
2348 node = result->val.node.node;
2350 if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2351 break;
2353 if (!(node->flags & NODE_DISABLED))
2355 int ret = 0;
2356 /* If not in a macro context, and we're going to start an
2357 expansion, record the location. */
2358 if (can_set && !context->c.macro)
2359 pfile->invocation_location = result->src_loc;
2360 if (pfile->state.prevent_expansion)
2361 break;
2363 /* Conditional macros require that a predicate be evaluated
2364 first. */
2365 if ((node->flags & NODE_CONDITIONAL) != 0)
2367 if (pfile->cb.macro_to_expand)
2369 bool whitespace_after;
2370 const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2372 whitespace_after = (peek_tok->type == CPP_PADDING
2373 || (peek_tok->flags & PREV_WHITE));
2374 node = pfile->cb.macro_to_expand (pfile, result);
2375 if (node)
2376 ret = enter_macro_context (pfile, node, result,
2377 virt_loc);
2378 else if (whitespace_after)
2380 /* If macro_to_expand hook returned NULL and it
2381 ate some tokens, see if we don't need to add
2382 a padding token in between this and the
2383 next token. */
2384 peek_tok = cpp_peek_token (pfile, 0);
2385 if (peek_tok->type != CPP_PADDING
2386 && (peek_tok->flags & PREV_WHITE) == 0)
2387 _cpp_push_token_context (pfile, NULL,
2388 padding_token (pfile,
2389 peek_tok), 1);
2393 else
2394 ret = enter_macro_context (pfile, node, result,
2395 virt_loc);
2396 if (ret)
2398 if (pfile->state.in_directive || ret == 2)
2399 continue;
2400 result = padding_token (pfile, result);
2401 goto out;
2404 else
2406 /* Flag this token as always unexpandable. FIXME: move this
2407 to collect_args()?. */
2408 cpp_token *t = _cpp_temp_token (pfile);
2409 t->type = result->type;
2410 t->flags = result->flags | NO_EXPAND;
2411 t->val = result->val;
2412 result = t;
2415 break;
2418 out:
2419 if (location != NULL)
2421 if (virt_loc == 0)
2422 virt_loc = result->src_loc;
2423 *location = virt_loc;
2425 if (!CPP_OPTION (pfile, track_macro_expansion)
2426 && can_set
2427 && pfile->context->c.macro != NULL)
2428 /* We are in a macro expansion context, are not tracking
2429 virtual location, but were asked to report the location
2430 of the expansion point of the macro being expanded. */
2431 *location = pfile->invocation_location;
2433 *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2435 return result;
2438 /* External routine to get a token. Also used nearly everywhere
2439 internally, except for places where we know we can safely call
2440 _cpp_lex_token directly, such as lexing a directive name.
2442 Macro expansions and directives are transparently handled,
2443 including entering included files. Thus tokens are post-macro
2444 expansion, and after any intervening directives. External callers
2445 see CPP_EOF only at EOF. Internal callers also see it when meeting
2446 a directive inside a macro call, when at the end of a directive and
2447 state.in_directive is still 1, and at the end of argument
2448 pre-expansion. */
2449 const cpp_token *
2450 cpp_get_token (cpp_reader *pfile)
2452 return cpp_get_token_1 (pfile, NULL);
2455 /* Like cpp_get_token, but also returns a virtual token location
2456 separate from the spelling location carried by the returned token.
2458 LOC is an out parameter; *LOC is set to the location "as expected
2459 by the user". This matters when a token results from macro
2460 expansion; in that case the token's spelling location indicates the
2461 locus of the token in the definition of the macro but *LOC
2462 virtually encodes all the other meaningful locuses associated to
2463 the token.
2465 What? virtual location? Yes, virtual location.
2467 If the token results from macro expansion and if macro expansion
2468 location tracking is enabled its virtual location encodes (at the
2469 same time):
2471 - the spelling location of the token
2473 - the locus of the macro expansion point
2475 - the locus of the point where the token got instantiated as part
2476 of the macro expansion process.
2478 You have to use the linemap API to get the locus you are interested
2479 in from a given virtual location.
2481 Note however that virtual locations are not necessarily ordered for
2482 relations '<' and '>'. One must use the function
2483 linemap_location_before_p instead of using the relational operator
2484 '<'.
2486 If macro expansion tracking is off and if the token results from
2487 macro expansion the virtual location is the expansion point of the
2488 macro that got expanded.
2490 When the token doesn't result from macro expansion, the virtual
2491 location is just the same thing as its spelling location. */
2493 const cpp_token *
2494 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2496 const cpp_token *result;
2498 pfile->set_invocation_location = true;
2499 result = cpp_get_token_1 (pfile, loc);
2500 return result;
2503 /* Returns true if we're expanding an object-like macro that was
2504 defined in a system header. Just checks the macro at the top of
2505 the stack. Used for diagnostic suppression. */
2507 cpp_sys_macro_p (cpp_reader *pfile)
2509 cpp_hashnode *node = NULL;
2511 if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2512 node = pfile->context->c.mc->macro_node;
2513 else
2514 node = pfile->context->c.macro;
2516 return node && node->value.macro && node->value.macro->syshdr;
2519 /* Read each token in, until end of the current file. Directives are
2520 transparently processed. */
2521 void
2522 cpp_scan_nooutput (cpp_reader *pfile)
2524 /* Request a CPP_EOF token at the end of this file, rather than
2525 transparently continuing with the including file. */
2526 pfile->buffer->return_at_eof = true;
2528 pfile->state.discarding_output++;
2529 pfile->state.prevent_expansion++;
2531 if (CPP_OPTION (pfile, traditional))
2532 while (_cpp_read_logical_line_trad (pfile))
2534 else
2535 while (cpp_get_token (pfile)->type != CPP_EOF)
2538 pfile->state.discarding_output--;
2539 pfile->state.prevent_expansion--;
2542 /* Step back one or more tokens obtained from the lexer. */
2543 void
2544 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2546 pfile->lookaheads += count;
2547 while (count--)
2549 pfile->cur_token--;
2550 if (pfile->cur_token == pfile->cur_run->base
2551 /* Possible with -fpreprocessed and no leading #line. */
2552 && pfile->cur_run->prev != NULL)
2554 pfile->cur_run = pfile->cur_run->prev;
2555 pfile->cur_token = pfile->cur_run->limit;
2560 /* Step back one (or more) tokens. Can only step back more than 1 if
2561 they are from the lexer, and not from macro expansion. */
2562 void
2563 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2565 if (pfile->context->prev == NULL)
2566 _cpp_backup_tokens_direct (pfile, count);
2567 else
2569 if (count != 1)
2570 abort ();
2571 if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2572 FIRST (pfile->context).token--;
2573 else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2574 FIRST (pfile->context).ptoken--;
2575 else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2577 FIRST (pfile->context).ptoken--;
2578 if (pfile->context->c.macro)
2580 macro_context *m = pfile->context->c.mc;
2581 m->cur_virt_loc--;
2582 #ifdef ENABLE_CHECKING
2583 if (m->cur_virt_loc < m->virt_locs)
2584 abort ();
2585 #endif
2587 else
2588 abort ();
2590 else
2591 abort ();
2595 /* #define directive parsing and handling. */
2597 /* Returns nonzero if a macro redefinition warning is required. */
2598 static bool
2599 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2600 const cpp_macro *macro2)
2602 const cpp_macro *macro1;
2603 unsigned int i;
2605 /* Some redefinitions need to be warned about regardless. */
2606 if (node->flags & NODE_WARN)
2607 return true;
2609 /* Suppress warnings for builtins that lack the NODE_WARN flag. */
2610 if (node->flags & NODE_BUILTIN)
2612 if (!pfile->cb.user_builtin_macro
2613 || !pfile->cb.user_builtin_macro (pfile, node))
2614 return false;
2617 /* Redefinitions of conditional (context-sensitive) macros, on
2618 the other hand, must be allowed silently. */
2619 if (node->flags & NODE_CONDITIONAL)
2620 return false;
2622 /* Redefinition of a macro is allowed if and only if the old and new
2623 definitions are the same. (6.10.3 paragraph 2). */
2624 macro1 = node->value.macro;
2626 /* Don't check count here as it can be different in valid
2627 traditional redefinitions with just whitespace differences. */
2628 if (macro1->paramc != macro2->paramc
2629 || macro1->fun_like != macro2->fun_like
2630 || macro1->variadic != macro2->variadic)
2631 return true;
2633 /* Check parameter spellings. */
2634 for (i = 0; i < macro1->paramc; i++)
2635 if (macro1->params[i] != macro2->params[i])
2636 return true;
2638 /* Check the replacement text or tokens. */
2639 if (CPP_OPTION (pfile, traditional))
2640 return _cpp_expansions_different_trad (macro1, macro2);
2642 if (macro1->count != macro2->count)
2643 return true;
2645 for (i = 0; i < macro1->count; i++)
2646 if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2647 return true;
2649 return false;
2652 /* Free the definition of hashnode H. */
2653 void
2654 _cpp_free_definition (cpp_hashnode *h)
2656 /* Macros and assertions no longer have anything to free. */
2657 h->type = NT_VOID;
2658 /* Clear builtin flag in case of redefinition. */
2659 h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2662 /* Save parameter NODE to the parameter list of macro MACRO. Returns
2663 zero on success, nonzero if the parameter is a duplicate. */
2664 bool
2665 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
2667 unsigned int len;
2668 /* Constraint 6.10.3.6 - duplicate parameter names. */
2669 if (node->flags & NODE_MACRO_ARG)
2671 cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2672 NODE_NAME (node));
2673 return true;
2676 if (BUFF_ROOM (pfile->a_buff)
2677 < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2678 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2680 ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
2681 node->flags |= NODE_MACRO_ARG;
2682 len = macro->paramc * sizeof (union _cpp_hashnode_value);
2683 if (len > pfile->macro_buffer_len)
2685 pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2686 len);
2687 pfile->macro_buffer_len = len;
2689 ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
2690 = node->value;
2692 node->value.arg_index = macro->paramc;
2693 return false;
2696 /* Check the syntax of the parameters in a MACRO definition. Returns
2697 false if an error occurs. */
2698 static bool
2699 parse_params (cpp_reader *pfile, cpp_macro *macro)
2701 unsigned int prev_ident = 0;
2703 for (;;)
2705 const cpp_token *token = _cpp_lex_token (pfile);
2707 switch (token->type)
2709 default:
2710 /* Allow/ignore comments in parameter lists if we are
2711 preserving comments in macro expansions. */
2712 if (token->type == CPP_COMMENT
2713 && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
2714 continue;
2716 cpp_error (pfile, CPP_DL_ERROR,
2717 "\"%s\" may not appear in macro parameter list",
2718 cpp_token_as_text (pfile, token));
2719 return false;
2721 case CPP_NAME:
2722 if (prev_ident)
2724 cpp_error (pfile, CPP_DL_ERROR,
2725 "macro parameters must be comma-separated");
2726 return false;
2728 prev_ident = 1;
2730 if (_cpp_save_parameter (pfile, macro, token->val.node.node))
2731 return false;
2732 continue;
2734 case CPP_CLOSE_PAREN:
2735 if (prev_ident || macro->paramc == 0)
2736 return true;
2738 /* Fall through to pick up the error. */
2739 case CPP_COMMA:
2740 if (!prev_ident)
2742 cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
2743 return false;
2745 prev_ident = 0;
2746 continue;
2748 case CPP_ELLIPSIS:
2749 macro->variadic = 1;
2750 if (!prev_ident)
2752 _cpp_save_parameter (pfile, macro,
2753 pfile->spec_nodes.n__VA_ARGS__);
2754 pfile->state.va_args_ok = 1;
2755 if (! CPP_OPTION (pfile, c99)
2756 && CPP_OPTION (pfile, cpp_pedantic)
2757 && CPP_OPTION (pfile, warn_variadic_macros))
2758 cpp_pedwarning
2759 (pfile, CPP_W_VARIADIC_MACROS,
2760 "anonymous variadic macros were introduced in C99");
2762 else if (CPP_OPTION (pfile, cpp_pedantic)
2763 && CPP_OPTION (pfile, warn_variadic_macros))
2764 cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2765 "ISO C does not permit named variadic macros");
2767 /* We're at the end, and just expect a closing parenthesis. */
2768 token = _cpp_lex_token (pfile);
2769 if (token->type == CPP_CLOSE_PAREN)
2770 return true;
2771 /* Fall through. */
2773 case CPP_EOF:
2774 cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
2775 return false;
2780 /* Allocate room for a token from a macro's replacement list. */
2781 static cpp_token *
2782 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2784 if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
2785 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
2787 return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
2790 /* Lex a token from the expansion of MACRO, but mark parameters as we
2791 find them and warn of traditional stringification. */
2792 static cpp_token *
2793 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
2795 cpp_token *token, *saved_cur_token;
2797 saved_cur_token = pfile->cur_token;
2798 pfile->cur_token = alloc_expansion_token (pfile, macro);
2799 token = _cpp_lex_direct (pfile);
2800 pfile->cur_token = saved_cur_token;
2802 /* Is this a parameter? */
2803 if (token->type == CPP_NAME
2804 && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
2806 token->type = CPP_MACRO_ARG;
2807 token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
2809 else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
2810 && (token->type == CPP_STRING || token->type == CPP_CHAR))
2811 check_trad_stringification (pfile, macro, &token->val.str);
2813 return token;
2816 static bool
2817 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
2819 cpp_token *token;
2820 const cpp_token *ctoken;
2821 bool following_paste_op = false;
2822 const char *paste_op_error_msg =
2823 N_("'##' cannot appear at either end of a macro expansion");
2824 unsigned int num_extra_tokens = 0;
2826 /* Get the first token of the expansion (or the '(' of a
2827 function-like macro). */
2828 ctoken = _cpp_lex_token (pfile);
2830 if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
2832 bool ok = parse_params (pfile, macro);
2833 macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
2834 if (!ok)
2835 return false;
2837 /* Success. Commit or allocate the parameter array. */
2838 if (pfile->hash_table->alloc_subobject)
2840 cpp_hashnode **params =
2841 (cpp_hashnode **) pfile->hash_table->alloc_subobject
2842 (sizeof (cpp_hashnode *) * macro->paramc);
2843 memcpy (params, macro->params,
2844 sizeof (cpp_hashnode *) * macro->paramc);
2845 macro->params = params;
2847 else
2848 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
2849 macro->fun_like = 1;
2851 else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
2853 /* While ISO C99 requires whitespace before replacement text
2854 in a macro definition, ISO C90 with TC1 allows there characters
2855 from the basic source character set. */
2856 if (CPP_OPTION (pfile, c99))
2857 cpp_error (pfile, CPP_DL_PEDWARN,
2858 "ISO C99 requires whitespace after the macro name");
2859 else
2861 int warntype = CPP_DL_WARNING;
2862 switch (ctoken->type)
2864 case CPP_ATSIGN:
2865 case CPP_AT_NAME:
2866 case CPP_OBJC_STRING:
2867 /* '@' is not in basic character set. */
2868 warntype = CPP_DL_PEDWARN;
2869 break;
2870 case CPP_OTHER:
2871 /* Basic character set sans letters, digits and _. */
2872 if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
2873 ctoken->val.str.text[0]) == NULL)
2874 warntype = CPP_DL_PEDWARN;
2875 break;
2876 default:
2877 /* All other tokens start with a character from basic
2878 character set. */
2879 break;
2881 cpp_error (pfile, warntype,
2882 "missing whitespace after the macro name");
2886 if (macro->fun_like)
2887 token = lex_expansion_token (pfile, macro);
2888 else
2890 token = alloc_expansion_token (pfile, macro);
2891 *token = *ctoken;
2894 for (;;)
2896 /* Check the stringifying # constraint 6.10.3.2.1 of
2897 function-like macros when lexing the subsequent token. */
2898 if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
2900 if (token->type == CPP_MACRO_ARG)
2902 if (token->flags & PREV_WHITE)
2903 token->flags |= SP_PREV_WHITE;
2904 if (token[-1].flags & DIGRAPH)
2905 token->flags |= SP_DIGRAPH;
2906 token->flags &= ~PREV_WHITE;
2907 token->flags |= STRINGIFY_ARG;
2908 token->flags |= token[-1].flags & PREV_WHITE;
2909 token[-1] = token[0];
2910 macro->count--;
2912 /* Let assembler get away with murder. */
2913 else if (CPP_OPTION (pfile, lang) != CLK_ASM)
2915 cpp_error (pfile, CPP_DL_ERROR,
2916 "'#' is not followed by a macro parameter");
2917 return false;
2921 if (token->type == CPP_EOF)
2923 /* Paste operator constraint 6.10.3.3.1:
2924 Token-paste ##, can appear in both object-like and
2925 function-like macros, but not at the end. */
2926 if (following_paste_op)
2928 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
2929 return false;
2931 break;
2934 /* Paste operator constraint 6.10.3.3.1. */
2935 if (token->type == CPP_PASTE)
2937 /* Token-paste ##, can appear in both object-like and
2938 function-like macros, but not at the beginning. */
2939 if (macro->count == 1)
2941 cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
2942 return false;
2945 if (token[-1].flags & PASTE_LEFT)
2947 macro->extra_tokens = 1;
2948 num_extra_tokens++;
2949 token->val.token_no = macro->count - 1;
2951 else
2953 --macro->count;
2954 token[-1].flags |= PASTE_LEFT;
2955 if (token->flags & DIGRAPH)
2956 token[-1].flags |= SP_DIGRAPH;
2957 if (token->flags & PREV_WHITE)
2958 token[-1].flags |= SP_PREV_WHITE;
2962 following_paste_op = (token->type == CPP_PASTE);
2963 token = lex_expansion_token (pfile, macro);
2966 macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
2967 macro->traditional = 0;
2969 /* Don't count the CPP_EOF. */
2970 macro->count--;
2972 /* Clear whitespace on first token for warn_of_redefinition(). */
2973 if (macro->count)
2974 macro->exp.tokens[0].flags &= ~PREV_WHITE;
2976 /* Commit or allocate the memory. */
2977 if (pfile->hash_table->alloc_subobject)
2979 cpp_token *tokns =
2980 (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
2981 * macro->count);
2982 if (num_extra_tokens)
2984 /* Place second and subsequent ## or %:%: tokens in
2985 sequences of consecutive such tokens at the end of the
2986 list to preserve information about where they appear, how
2987 they are spelt and whether they are preceded by
2988 whitespace without otherwise interfering with macro
2989 expansion. */
2990 cpp_token *normal_dest = tokns;
2991 cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
2992 unsigned int i;
2993 for (i = 0; i < macro->count; i++)
2995 if (macro->exp.tokens[i].type == CPP_PASTE)
2996 *extra_dest++ = macro->exp.tokens[i];
2997 else
2998 *normal_dest++ = macro->exp.tokens[i];
3001 else
3002 memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
3003 macro->exp.tokens = tokns;
3005 else
3006 BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
3008 return true;
3011 /* Parse a macro and save its expansion. Returns nonzero on success. */
3012 bool
3013 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3015 cpp_macro *macro;
3016 unsigned int i;
3017 bool ok;
3019 if (pfile->hash_table->alloc_subobject)
3020 macro = (cpp_macro *) pfile->hash_table->alloc_subobject
3021 (sizeof (cpp_macro));
3022 else
3023 macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
3024 macro->line = pfile->directive_line;
3025 macro->params = 0;
3026 macro->paramc = 0;
3027 macro->variadic = 0;
3028 macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3029 macro->count = 0;
3030 macro->fun_like = 0;
3031 macro->extra_tokens = 0;
3032 /* To suppress some diagnostics. */
3033 macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3035 if (CPP_OPTION (pfile, traditional))
3036 ok = _cpp_create_trad_definition (pfile, macro);
3037 else
3039 ok = create_iso_definition (pfile, macro);
3041 /* We set the type for SEEN_EOL() in directives.c.
3043 Longer term we should lex the whole line before coming here,
3044 and just copy the expansion. */
3046 /* Stop the lexer accepting __VA_ARGS__. */
3047 pfile->state.va_args_ok = 0;
3050 /* Clear the fast argument lookup indices. */
3051 for (i = macro->paramc; i-- > 0; )
3053 struct cpp_hashnode *node = macro->params[i];
3054 node->flags &= ~ NODE_MACRO_ARG;
3055 node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
3058 if (!ok)
3059 return ok;
3061 if (node->type == NT_MACRO)
3063 if (CPP_OPTION (pfile, warn_unused_macros))
3064 _cpp_warn_if_unused_macro (pfile, node, NULL);
3066 if (warn_of_redefinition (pfile, node, macro))
3068 const int reason = (node->flags & NODE_BUILTIN)
3069 ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3070 bool warned;
3072 warned = cpp_pedwarning_with_line (pfile, reason,
3073 pfile->directive_line, 0,
3074 "\"%s\" redefined",
3075 NODE_NAME (node));
3077 if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3078 cpp_error_with_line (pfile, CPP_DL_NOTE,
3079 node->value.macro->line, 0,
3080 "this is the location of the previous definition");
3084 if (node->type != NT_VOID)
3085 _cpp_free_definition (node);
3087 /* Enter definition in hash table. */
3088 node->type = NT_MACRO;
3089 node->value.macro = macro;
3090 if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3091 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3092 /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3093 in the C standard, as something that one must use in C++.
3094 However DR#593 indicates that these aren't actually mentioned
3095 in the C++ standard. We special-case them anyway. */
3096 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3097 && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3098 node->flags |= NODE_WARN;
3100 /* If user defines one of the conditional macros, remove the
3101 conditional flag */
3102 node->flags &= ~NODE_CONDITIONAL;
3104 return ok;
3107 /* Warn if a token in STRING matches one of a function-like MACRO's
3108 parameters. */
3109 static void
3110 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3111 const cpp_string *string)
3113 unsigned int i, len;
3114 const uchar *p, *q, *limit;
3116 /* Loop over the string. */
3117 limit = string->text + string->len - 1;
3118 for (p = string->text + 1; p < limit; p = q)
3120 /* Find the start of an identifier. */
3121 while (p < limit && !is_idstart (*p))
3122 p++;
3124 /* Find the end of the identifier. */
3125 q = p;
3126 while (q < limit && is_idchar (*q))
3127 q++;
3129 len = q - p;
3131 /* Loop over the function macro arguments to see if the
3132 identifier inside the string matches one of them. */
3133 for (i = 0; i < macro->paramc; i++)
3135 const cpp_hashnode *node = macro->params[i];
3137 if (NODE_LEN (node) == len
3138 && !memcmp (p, NODE_NAME (node), len))
3140 cpp_error (pfile, CPP_DL_WARNING,
3141 "macro argument \"%s\" would be stringified in traditional C",
3142 NODE_NAME (node));
3143 break;
3149 /* Returns the name, arguments and expansion of a macro, in a format
3150 suitable to be read back in again, and therefore also for DWARF 2
3151 debugging info. e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3152 Caller is expected to generate the "#define" bit if needed. The
3153 returned text is temporary, and automatically freed later. */
3154 const unsigned char *
3155 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3157 unsigned int i, len;
3158 const cpp_macro *macro;
3159 unsigned char *buffer;
3161 if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3163 if (node->type != NT_MACRO
3164 || !pfile->cb.user_builtin_macro
3165 || !pfile->cb.user_builtin_macro (pfile, node))
3167 cpp_error (pfile, CPP_DL_ICE,
3168 "invalid hash type %d in cpp_macro_definition",
3169 node->type);
3170 return 0;
3174 macro = node->value.macro;
3175 /* Calculate length. */
3176 len = NODE_LEN (node) + 2; /* ' ' and NUL. */
3177 if (macro->fun_like)
3179 len += 4; /* "()" plus possible final ".." of named
3180 varargs (we have + 1 below). */
3181 for (i = 0; i < macro->paramc; i++)
3182 len += NODE_LEN (macro->params[i]) + 1; /* "," */
3185 /* This should match below where we fill in the buffer. */
3186 if (CPP_OPTION (pfile, traditional))
3187 len += _cpp_replacement_text_len (macro);
3188 else
3190 unsigned int count = macro_real_token_count (macro);
3191 for (i = 0; i < count; i++)
3193 cpp_token *token = &macro->exp.tokens[i];
3195 if (token->type == CPP_MACRO_ARG)
3196 len += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3197 else
3198 len += cpp_token_len (token);
3200 if (token->flags & STRINGIFY_ARG)
3201 len++; /* "#" */
3202 if (token->flags & PASTE_LEFT)
3203 len += 3; /* " ##" */
3204 if (token->flags & PREV_WHITE)
3205 len++; /* " " */
3209 if (len > pfile->macro_buffer_len)
3211 pfile->macro_buffer = XRESIZEVEC (unsigned char,
3212 pfile->macro_buffer, len);
3213 pfile->macro_buffer_len = len;
3216 /* Fill in the buffer. Start with the macro name. */
3217 buffer = pfile->macro_buffer;
3218 memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
3219 buffer += NODE_LEN (node);
3221 /* Parameter names. */
3222 if (macro->fun_like)
3224 *buffer++ = '(';
3225 for (i = 0; i < macro->paramc; i++)
3227 cpp_hashnode *param = macro->params[i];
3229 if (param != pfile->spec_nodes.n__VA_ARGS__)
3231 memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3232 buffer += NODE_LEN (param);
3235 if (i + 1 < macro->paramc)
3236 /* Don't emit a space after the comma here; we're trying
3237 to emit a Dwarf-friendly definition, and the Dwarf spec
3238 forbids spaces in the argument list. */
3239 *buffer++ = ',';
3240 else if (macro->variadic)
3241 *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3243 *buffer++ = ')';
3246 /* The Dwarf spec requires a space after the macro name, even if the
3247 definition is the empty string. */
3248 *buffer++ = ' ';
3250 if (CPP_OPTION (pfile, traditional))
3251 buffer = _cpp_copy_replacement_text (macro, buffer);
3252 else if (macro->count)
3253 /* Expansion tokens. */
3255 unsigned int count = macro_real_token_count (macro);
3256 for (i = 0; i < count; i++)
3258 cpp_token *token = &macro->exp.tokens[i];
3260 if (token->flags & PREV_WHITE)
3261 *buffer++ = ' ';
3262 if (token->flags & STRINGIFY_ARG)
3263 *buffer++ = '#';
3265 if (token->type == CPP_MACRO_ARG)
3267 memcpy (buffer,
3268 NODE_NAME (macro->params[token->val.macro_arg.arg_no - 1]),
3269 NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]));
3270 buffer += NODE_LEN (macro->params[token->val.macro_arg.arg_no - 1]);
3272 else
3273 buffer = cpp_spell_token (pfile, token, buffer, false);
3275 if (token->flags & PASTE_LEFT)
3277 *buffer++ = ' ';
3278 *buffer++ = '#';
3279 *buffer++ = '#';
3280 /* Next has PREV_WHITE; see _cpp_create_definition. */
3285 *buffer = '\0';
3286 return pfile->macro_buffer;