Fix building Loongarch BFD with a 32-bit compiler
[binutils-gdb.git] / gdb / macroexp.c
blobbcae7ec8daf6793ba45ec269dbcf62eb92a9d145
1 /* C preprocessor macro expansion for GDB.
2 Copyright (C) 2002-2024 Free Software Foundation, Inc.
3 Contributed by Red Hat, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "gdbsupport/gdb_obstack.h"
21 #include "macrotab.h"
22 #include "macroexp.h"
23 #include "macroscope.h"
24 #include "c-lang.h"
29 /* A string type that we can use to refer to substrings of other
30 strings. */
32 struct shared_macro_buffer
34 /* An array of characters. This buffer is a pointer into some
35 larger string and thus we can't assume in that the text is
36 null-terminated. */
37 const char *text;
39 /* The number of characters in the string. */
40 int len;
42 /* For detecting token splicing.
44 This is the index in TEXT of the first character of the token
45 that abuts the end of TEXT. If TEXT contains no tokens, then we
46 set this equal to LEN. If TEXT ends in whitespace, then there is
47 no token abutting the end of TEXT (it's just whitespace), and
48 again, we set this equal to LEN. We set this to -1 if we don't
49 know the nature of TEXT. */
50 int last_token = -1;
52 /* If this buffer is holding the result from get_token, then this
53 is non-zero if it is an identifier token, zero otherwise. */
54 int is_identifier = 0;
56 shared_macro_buffer ()
57 : text (NULL),
58 len (0)
62 /* Set the macro buffer to refer to the LEN bytes at ADDR, as a
63 shared substring. */
64 shared_macro_buffer (const char *addr, int len)
66 set_shared (addr, len);
69 /* Set the macro buffer to refer to the LEN bytes at ADDR, as a
70 shared substring. */
71 void set_shared (const char *addr, int len_)
73 text = addr;
74 len = len_;
78 /* A string type that we can resize and quickly append to. */
80 struct growable_macro_buffer
82 /* An array of characters. The first LEN bytes are the real text,
83 but there are SIZE bytes allocated to the array. */
84 char *text;
86 /* The number of characters in the string. */
87 int len;
89 /* The number of characters allocated to the string. */
90 int size;
92 /* For detecting token splicing.
94 This is the index in TEXT of the first character of the token
95 that abuts the end of TEXT. If TEXT contains no tokens, then we
96 set this equal to LEN. If TEXT ends in whitespace, then there is
97 no token abutting the end of TEXT (it's just whitespace), and
98 again, we set this equal to LEN. We set this to -1 if we don't
99 know the nature of TEXT. */
100 int last_token = -1;
102 /* Set the macro buffer to the empty string, guessing that its
103 final contents will fit in N bytes. (It'll get resized if it
104 doesn't, so the guess doesn't have to be right.) Allocate the
105 initial storage with xmalloc. */
106 explicit growable_macro_buffer (int n)
107 : len (0),
108 size (n)
110 if (n > 0)
111 text = (char *) xmalloc (n);
112 else
113 text = NULL;
116 DISABLE_COPY_AND_ASSIGN (growable_macro_buffer);
118 ~growable_macro_buffer ()
120 xfree (text);
123 /* Release the text of the buffer to the caller. */
124 gdb::unique_xmalloc_ptr<char> release ()
126 gdb_assert (size);
127 char *result = text;
128 text = NULL;
129 return gdb::unique_xmalloc_ptr<char> (result);
132 /* Resize the buffer to be at least N bytes long. */
133 void resize_buffer (int n)
135 if (size == 0)
136 size = n;
137 else
138 while (size <= n)
139 size *= 2;
141 text = (char *) xrealloc (text, size);
144 /* Append the character C to the buffer. */
145 void appendc (int c)
147 int new_len = len + 1;
149 if (new_len > size)
150 resize_buffer (new_len);
152 text[len] = c;
153 len = new_len;
156 /* Append the COUNT bytes at ADDR to the buffer. */
157 void appendmem (const char *addr, int count)
159 int new_len = len + count;
161 if (new_len > size)
162 resize_buffer (new_len);
164 memcpy (text + len, addr, count);
165 len = new_len;
171 /* Recognizing preprocessor tokens. */
175 macro_is_whitespace (int c)
177 return (c == ' '
178 || c == '\t'
179 || c == '\n'
180 || c == '\v'
181 || c == '\f');
186 macro_is_digit (int c)
188 return ('0' <= c && c <= '9');
193 macro_is_identifier_nondigit (int c)
195 return (c == '_'
196 || ('a' <= c && c <= 'z')
197 || ('A' <= c && c <= 'Z'));
201 static void
202 set_token (shared_macro_buffer *tok, const char *start, const char *end)
204 tok->set_shared (start, end - start);
205 tok->last_token = 0;
207 /* Presumed; get_identifier may overwrite this. */
208 tok->is_identifier = 0;
212 static int
213 get_comment (shared_macro_buffer *tok, const char *p, const char *end)
215 if (p + 2 > end)
216 return 0;
217 else if (p[0] == '/'
218 && p[1] == '*')
220 const char *tok_start = p;
222 p += 2;
224 for (; p < end; p++)
225 if (p + 2 <= end
226 && p[0] == '*'
227 && p[1] == '/')
229 p += 2;
230 set_token (tok, tok_start, p);
231 return 1;
234 error (_("Unterminated comment in macro expansion."));
236 else if (p[0] == '/'
237 && p[1] == '/')
239 const char *tok_start = p;
241 p += 2;
242 for (; p < end; p++)
243 if (*p == '\n')
244 break;
246 set_token (tok, tok_start, p);
247 return 1;
249 else
250 return 0;
254 static int
255 get_identifier (shared_macro_buffer *tok, const char *p, const char *end)
257 if (p < end
258 && macro_is_identifier_nondigit (*p))
260 const char *tok_start = p;
262 while (p < end
263 && (macro_is_identifier_nondigit (*p)
264 || macro_is_digit (*p)))
265 p++;
267 set_token (tok, tok_start, p);
268 tok->is_identifier = 1;
269 return 1;
271 else
272 return 0;
276 static int
277 get_pp_number (shared_macro_buffer *tok, const char *p, const char *end)
279 if (p < end
280 && (macro_is_digit (*p)
281 || (*p == '.'
282 && p + 2 <= end
283 && macro_is_digit (p[1]))))
285 const char *tok_start = p;
287 while (p < end)
289 if (p + 2 <= end
290 && strchr ("eEpP", *p)
291 && (p[1] == '+' || p[1] == '-'))
292 p += 2;
293 else if (macro_is_digit (*p)
294 || macro_is_identifier_nondigit (*p)
295 || *p == '.')
296 p++;
297 else
298 break;
301 set_token (tok, tok_start, p);
302 return 1;
304 else
305 return 0;
310 /* If the text starting at P going up to (but not including) END
311 starts with a character constant, set *TOK to point to that
312 character constant, and return 1. Otherwise, return zero.
313 Signal an error if it contains a malformed or incomplete character
314 constant. */
315 static int
316 get_character_constant (shared_macro_buffer *tok,
317 const char *p, const char *end)
319 /* ISO/IEC 9899:1999 (E) Section 6.4.4.4 paragraph 1
320 But of course, what really matters is that we handle it the same
321 way GDB's C/C++ lexer does. So we call parse_escape in utils.c
322 to handle escape sequences. */
323 if ((p + 1 <= end && *p == '\'')
324 || (p + 2 <= end
325 && (p[0] == 'L' || p[0] == 'u' || p[0] == 'U')
326 && p[1] == '\''))
328 const char *tok_start = p;
329 int char_count = 0;
331 if (*p == '\'')
332 p++;
333 else if (*p == 'L' || *p == 'u' || *p == 'U')
334 p += 2;
335 else
336 gdb_assert_not_reached ("unexpected character constant");
338 for (;;)
340 if (p >= end)
341 error (_("Unmatched single quote."));
342 else if (*p == '\'')
344 if (!char_count)
345 error (_("A character constant must contain at least one "
346 "character."));
347 p++;
348 break;
350 else if (*p == '\\')
352 const char *s, *o;
354 s = o = ++p;
355 char_count += c_parse_escape (&s, NULL);
356 p += s - o;
358 else
360 p++;
361 char_count++;
365 set_token (tok, tok_start, p);
366 return 1;
368 else
369 return 0;
373 /* If the text starting at P going up to (but not including) END
374 starts with a string literal, set *TOK to point to that string
375 literal, and return 1. Otherwise, return zero. Signal an error if
376 it contains a malformed or incomplete string literal. */
377 static int
378 get_string_literal (shared_macro_buffer *tok, const char *p, const char *end)
380 if ((p + 1 <= end
381 && *p == '"')
382 || (p + 2 <= end
383 && (p[0] == 'L' || p[0] == 'u' || p[0] == 'U')
384 && p[1] == '"'))
386 const char *tok_start = p;
388 if (*p == '"')
389 p++;
390 else if (*p == 'L' || *p == 'u' || *p == 'U')
391 p += 2;
392 else
393 gdb_assert_not_reached ("unexpected string literal");
395 for (;;)
397 if (p >= end)
398 error (_("Unterminated string in expression."));
399 else if (*p == '"')
401 p++;
402 break;
404 else if (*p == '\n')
405 error (_("Newline characters may not appear in string "
406 "constants."));
407 else if (*p == '\\')
409 const char *s, *o;
411 s = o = ++p;
412 c_parse_escape (&s, NULL);
413 p += s - o;
415 else
416 p++;
419 set_token (tok, tok_start, p);
420 return 1;
422 else
423 return 0;
427 static int
428 get_punctuator (shared_macro_buffer *tok, const char *p, const char *end)
430 /* Here, speed is much less important than correctness and clarity. */
432 /* ISO/IEC 9899:1999 (E) Section 6.4.6 Paragraph 1.
433 Note that this table is ordered in a special way. A punctuator
434 which is a prefix of another punctuator must appear after its
435 "extension". Otherwise, the wrong token will be returned. */
436 static const char * const punctuators[] = {
437 "[", "]", "(", ")", "{", "}", "?", ";", ",", "~",
438 "...", ".",
439 "->", "--", "-=", "-",
440 "++", "+=", "+",
441 "*=", "*",
442 "!=", "!",
443 "&&", "&=", "&",
444 "/=", "/",
445 "%>", "%:%:", "%:", "%=", "%",
446 "^=", "^",
447 "##", "#",
448 ":>", ":",
449 "||", "|=", "|",
450 "<<=", "<<", "<=", "<:", "<%", "<",
451 ">>=", ">>", ">=", ">",
452 "==", "=",
456 int i;
458 if (p + 1 <= end)
460 for (i = 0; punctuators[i]; i++)
462 const char *punctuator = punctuators[i];
464 if (p[0] == punctuator[0])
466 int len = strlen (punctuator);
468 if (p + len <= end
469 && ! memcmp (p, punctuator, len))
471 set_token (tok, p, p + len);
472 return 1;
478 return 0;
482 /* Peel the next preprocessor token off of SRC, and put it in TOK.
483 Mutate TOK to refer to the first token in SRC, and mutate SRC to
484 refer to the text after that token. The resulting TOK will point
485 into the same string SRC does. Initialize TOK's last_token field.
486 Return non-zero if we succeed, or 0 if we didn't find any more
487 tokens in SRC. */
489 static int
490 get_token (shared_macro_buffer *tok, shared_macro_buffer *src)
492 const char *p = src->text;
493 const char *end = p + src->len;
495 /* From the ISO C standard, ISO/IEC 9899:1999 (E), section 6.4:
497 preprocessing-token:
498 header-name
499 identifier
500 pp-number
501 character-constant
502 string-literal
503 punctuator
504 each non-white-space character that cannot be one of the above
506 We don't have to deal with header-name tokens, since those can
507 only occur after a #include, which we will never see. */
509 while (p < end)
510 if (macro_is_whitespace (*p))
511 p++;
512 else if (get_comment (tok, p, end))
513 p += tok->len;
514 else if (get_pp_number (tok, p, end)
515 || get_character_constant (tok, p, end)
516 || get_string_literal (tok, p, end)
517 /* Note: the grammar in the standard seems to be
518 ambiguous: L'x' can be either a wide character
519 constant, or an identifier followed by a normal
520 character constant. By trying `get_identifier' after
521 we try get_character_constant and get_string_literal,
522 we give the wide character syntax precedence. Now,
523 since GDB doesn't handle wide character constants
524 anyway, is this the right thing to do? */
525 || get_identifier (tok, p, end)
526 || get_punctuator (tok, p, end))
528 /* How many characters did we consume, including whitespace? */
529 int consumed = p - src->text + tok->len;
531 src->text += consumed;
532 src->len -= consumed;
533 return 1;
535 else
537 /* We have found a "non-whitespace character that cannot be
538 one of the above." Make a token out of it. */
539 int consumed;
541 set_token (tok, p, p + 1);
542 consumed = p - src->text + tok->len;
543 src->text += consumed;
544 src->len -= consumed;
545 return 1;
548 return 0;
553 /* Appending token strings, with and without splicing */
556 /* Append the macro buffer SRC to the end of DEST, and ensure that
557 doing so doesn't splice the token at the end of SRC with the token
558 at the beginning of DEST. SRC and DEST must have their last_token
559 fields set. Upon return, DEST's last_token field is set correctly.
561 For example:
563 If DEST is "(" and SRC is "y", then we can return with
564 DEST set to "(y" --- we've simply appended the two buffers.
566 However, if DEST is "x" and SRC is "y", then we must not return
567 with DEST set to "xy" --- that would splice the two tokens "x" and
568 "y" together to make a single token "xy". However, it would be
569 fine to return with DEST set to "x y". Similarly, "<" and "<" must
570 yield "< <", not "<<", etc. */
571 static void
572 append_tokens_without_splicing (growable_macro_buffer *dest,
573 shared_macro_buffer *src)
575 int original_dest_len = dest->len;
576 shared_macro_buffer dest_tail, new_token;
578 gdb_assert (src->last_token != -1);
579 gdb_assert (dest->last_token != -1);
581 /* First, just try appending the two, and call get_token to see if
582 we got a splice. */
583 dest->appendmem (src->text, src->len);
585 /* If DEST originally had no token abutting its end, then we can't
586 have spliced anything, so we're done. */
587 if (dest->last_token == original_dest_len)
589 dest->last_token = original_dest_len + src->last_token;
590 return;
593 /* Set DEST_TAIL to point to the last token in DEST, followed by
594 all the stuff we just appended. */
595 dest_tail.set_shared (dest->text + dest->last_token,
596 dest->len - dest->last_token);
598 /* Re-parse DEST's last token. We know that DEST used to contain
599 at least one token, so if it doesn't contain any after the
600 append, then we must have spliced "/" and "*" or "/" and "/" to
601 make a comment start. (Just for the record, I got this right
602 the first time. This is not a bug fix.) */
603 if (get_token (&new_token, &dest_tail)
604 && (new_token.text + new_token.len
605 == dest->text + original_dest_len))
607 /* No splice, so we're done. */
608 dest->last_token = original_dest_len + src->last_token;
609 return;
612 /* Okay, a simple append caused a splice. Let's chop dest back to
613 its original length and try again, but separate the texts with a
614 space. */
615 dest->len = original_dest_len;
616 dest->appendc (' ');
617 dest->appendmem (src->text, src->len);
619 dest_tail.set_shared (dest->text + dest->last_token,
620 dest->len - dest->last_token);
622 /* Try to re-parse DEST's last token, as above. */
623 if (get_token (&new_token, &dest_tail)
624 && (new_token.text + new_token.len
625 == dest->text + original_dest_len))
627 /* No splice, so we're done. */
628 dest->last_token = original_dest_len + 1 + src->last_token;
629 return;
632 /* As far as I know, there's no case where inserting a space isn't
633 enough to prevent a splice. */
634 internal_error (_("unable to avoid splicing tokens during macro expansion"));
637 /* Stringify an argument, and insert it into DEST. ARG is the text to
638 stringify; it is LEN bytes long. */
640 static void
641 stringify (growable_macro_buffer *dest, const char *arg, int len)
643 /* Trim initial whitespace from ARG. */
644 while (len > 0 && macro_is_whitespace (*arg))
646 ++arg;
647 --len;
650 /* Trim trailing whitespace from ARG. */
651 while (len > 0 && macro_is_whitespace (arg[len - 1]))
652 --len;
654 /* Insert the string. */
655 dest->appendc ('"');
656 while (len > 0)
658 /* We could try to handle strange cases here, like control
659 characters, but there doesn't seem to be much point. */
660 if (macro_is_whitespace (*arg))
662 /* Replace a sequence of whitespace with a single space. */
663 dest->appendc (' ');
664 while (len > 1 && macro_is_whitespace (arg[1]))
666 ++arg;
667 --len;
670 else if (*arg == '\\' || *arg == '"')
672 dest->appendc ('\\');
673 dest->appendc (*arg);
675 else
676 dest->appendc (*arg);
677 ++arg;
678 --len;
680 dest->appendc ('"');
681 dest->last_token = dest->len;
684 /* See macroexp.h. */
686 gdb::unique_xmalloc_ptr<char>
687 macro_stringify (const char *str)
689 int len = strlen (str);
690 growable_macro_buffer buffer (len);
692 stringify (&buffer, str, len);
693 buffer.appendc ('\0');
695 return buffer.release ();
699 /* Expanding macros! */
702 /* A singly-linked list of the names of the macros we are currently
703 expanding --- for detecting expansion loops. */
704 struct macro_name_list {
705 const char *name;
706 struct macro_name_list *next;
710 /* Return non-zero if we are currently expanding the macro named NAME,
711 according to LIST; otherwise, return zero.
713 You know, it would be possible to get rid of all the NO_LOOP
714 arguments to these functions by simply generating a new lookup
715 function and baton which refuses to find the definition for a
716 particular macro, and otherwise delegates the decision to another
717 function/baton pair. But that makes the linked list of excluded
718 macros chained through untyped baton pointers, which will make it
719 harder to debug. :( */
720 static int
721 currently_rescanning (struct macro_name_list *list, const char *name)
723 for (; list; list = list->next)
724 if (strcmp (name, list->name) == 0)
725 return 1;
727 return 0;
731 /* Gather the arguments to a macro expansion.
733 NAME is the name of the macro being invoked. (It's only used for
734 printing error messages.)
736 Assume that SRC is the text of the macro invocation immediately
737 following the macro name. For example, if we're processing the
738 text foo(bar, baz), then NAME would be foo and SRC will be (bar,
739 baz).
741 If SRC doesn't start with an open paren ( token at all, return
742 false, leave SRC unchanged, and don't set *ARGS_PTR to anything.
744 If SRC doesn't contain a properly terminated argument list, then
745 raise an error.
747 For a variadic macro, NARGS holds the number of formal arguments to
748 the macro. For a GNU-style variadic macro, this should be the
749 number of named arguments. For a non-variadic macro, NARGS should
750 be -1.
752 Otherwise, return true and set *ARGS_PTR to a vector of macro
753 buffers referring to the argument texts. The macro buffers share
754 their text with SRC, and their last_token fields are initialized.
756 NOTE WELL: if SRC starts with a open paren ( token followed
757 immediately by a close paren ) token (e.g., the invocation looks
758 like "foo()"), we treat that as one argument, which happens to be
759 the empty list of tokens. The caller should keep in mind that such
760 a sequence of tokens is a valid way to invoke one-parameter
761 function-like macros, but also a valid way to invoke zero-parameter
762 function-like macros. Eeew.
764 Consume the tokens from SRC; after this call, SRC contains the text
765 following the invocation. */
767 static bool
768 gather_arguments (const char *name, shared_macro_buffer *src, int nargs,
769 std::vector<shared_macro_buffer> *args_ptr)
771 shared_macro_buffer tok;
772 std::vector<shared_macro_buffer> args;
774 /* Does SRC start with an opening paren token? Read from a copy of
775 SRC, so SRC itself is unaffected if we don't find an opening
776 paren. */
778 shared_macro_buffer temp (src->text, src->len);
780 if (! get_token (&tok, &temp)
781 || tok.len != 1
782 || tok.text[0] != '(')
783 return false;
786 /* Consume SRC's opening paren. */
787 get_token (&tok, src);
789 for (;;)
791 int depth;
793 /* Initialize the next argument. */
794 shared_macro_buffer *arg = &args.emplace_back ();
795 set_token (arg, src->text, src->text);
797 /* Gather the argument's tokens. */
798 depth = 0;
799 for (;;)
801 if (! get_token (&tok, src))
802 error (_("Malformed argument list for macro `%s'."), name);
804 /* Is tok an opening paren? */
805 if (tok.len == 1 && tok.text[0] == '(')
806 depth++;
808 /* Is tok is a closing paren? */
809 else if (tok.len == 1 && tok.text[0] == ')')
811 /* If it's a closing paren at the top level, then that's
812 the end of the argument list. */
813 if (depth == 0)
815 /* In the varargs case, the last argument may be
816 missing. Add an empty argument in this case. */
817 if (nargs != -1 && args.size () == nargs - 1)
819 arg = &args.emplace_back ();
820 set_token (arg, src->text, src->text);
823 *args_ptr = std::move (args);
824 return true;
827 depth--;
830 /* If tok is a comma at top level, then that's the end of
831 the current argument. However, if we are handling a
832 variadic macro and we are computing the last argument, we
833 want to include the comma and remaining tokens. */
834 else if (tok.len == 1 && tok.text[0] == ',' && depth == 0
835 && (nargs == -1 || args.size () < nargs))
836 break;
838 /* Extend the current argument to enclose this token. If
839 this is the current argument's first token, leave out any
840 leading whitespace, just for aesthetics. */
841 if (arg->len == 0)
843 arg->text = tok.text;
844 arg->len = tok.len;
845 arg->last_token = 0;
847 else
849 arg->len = (tok.text + tok.len) - arg->text;
850 arg->last_token = tok.text - arg->text;
857 /* The `expand' and `substitute_args' functions both invoke `scan'
858 recursively, so we need a forward declaration somewhere. */
859 static void scan (growable_macro_buffer *dest,
860 shared_macro_buffer *src,
861 struct macro_name_list *no_loop,
862 const macro_scope &scope);
864 /* A helper function for substitute_args.
866 ARGV is a vector of all the arguments; ARGC is the number of
867 arguments. IS_VARARGS is true if the macro being substituted is a
868 varargs macro; in this case VA_ARG_NAME is the name of the
869 "variable" argument. VA_ARG_NAME is ignored if IS_VARARGS is
870 false.
872 If the token TOK is the name of a parameter, return the parameter's
873 index. If TOK is not an argument, return -1. */
875 static int
876 find_parameter (const shared_macro_buffer *tok,
877 int is_varargs, const shared_macro_buffer *va_arg_name,
878 int argc, const char * const *argv)
880 int i;
882 if (! tok->is_identifier)
883 return -1;
885 for (i = 0; i < argc; ++i)
886 if (tok->len == strlen (argv[i])
887 && !memcmp (tok->text, argv[i], tok->len))
888 return i;
890 if (is_varargs && tok->len == va_arg_name->len
891 && ! memcmp (tok->text, va_arg_name->text, tok->len))
892 return argc - 1;
894 return -1;
897 /* Helper function for substitute_args that gets the next token and
898 updates the passed-in state variables. */
900 static void
901 get_next_token_for_substitution (shared_macro_buffer *replacement_list,
902 shared_macro_buffer *token,
903 const char **start,
904 shared_macro_buffer *lookahead,
905 const char **lookahead_start,
906 int *lookahead_valid,
907 bool *keep_going)
909 if (!*lookahead_valid)
910 *keep_going = false;
911 else
913 *keep_going = true;
914 *token = *lookahead;
915 *start = *lookahead_start;
916 *lookahead_start = replacement_list->text;
917 *lookahead_valid = get_token (lookahead, replacement_list);
921 /* Given the macro definition DEF, being invoked with the actual
922 arguments given by ARGV, substitute the arguments into the
923 replacement list, and store the result in DEST.
925 IS_VARARGS should be true if DEF is a varargs macro. In this case,
926 VA_ARG_NAME should be the name of the "variable" argument -- either
927 __VA_ARGS__ for c99-style varargs, or the final argument name, for
928 GNU-style varargs. If IS_VARARGS is false, this parameter is
929 ignored.
931 If it is necessary to expand macro invocations in one of the
932 arguments, use LOOKUP_FUNC and LOOKUP_BATON to find the macro
933 definitions, and don't expand invocations of the macros listed in
934 NO_LOOP. */
936 static void
937 substitute_args (growable_macro_buffer *dest,
938 struct macro_definition *def,
939 int is_varargs, const shared_macro_buffer *va_arg_name,
940 const std::vector<shared_macro_buffer> &argv,
941 struct macro_name_list *no_loop,
942 const macro_scope &scope)
944 /* The token we are currently considering. */
945 shared_macro_buffer tok;
946 /* The replacement list's pointer from just before TOK was lexed. */
947 const char *original_rl_start;
948 /* We have a single lookahead token to handle token splicing. */
949 shared_macro_buffer lookahead;
950 /* The lookahead token might not be valid. */
951 int lookahead_valid;
952 /* The replacement list's pointer from just before LOOKAHEAD was
953 lexed. */
954 const char *lookahead_rl_start;
956 /* A macro buffer for the macro's replacement list. */
957 shared_macro_buffer replacement_list (def->replacement,
958 strlen (def->replacement));
960 gdb_assert (dest->len == 0);
961 dest->last_token = 0;
963 original_rl_start = replacement_list.text;
964 if (! get_token (&tok, &replacement_list))
965 return;
966 lookahead_rl_start = replacement_list.text;
967 lookahead_valid = get_token (&lookahead, &replacement_list);
969 /* __VA_OPT__ state variable. The states are:
970 0 - nothing happening
971 1 - saw __VA_OPT__
972 >= 2 in __VA_OPT__, the value encodes the parenthesis depth. */
973 unsigned vaopt_state = 0;
975 for (bool keep_going = true;
976 keep_going;
977 get_next_token_for_substitution (&replacement_list,
978 &tok,
979 &original_rl_start,
980 &lookahead,
981 &lookahead_rl_start,
982 &lookahead_valid,
983 &keep_going))
985 bool token_is_vaopt = (tok.len == 10
986 && startswith (tok.text, "__VA_OPT__"));
988 if (vaopt_state > 0)
990 if (token_is_vaopt)
991 error (_("__VA_OPT__ cannot appear inside __VA_OPT__"));
992 else if (tok.len == 1 && tok.text[0] == '(')
994 ++vaopt_state;
995 /* We just entered __VA_OPT__, so don't emit this
996 token. */
997 continue;
999 else if (vaopt_state == 1)
1000 error (_("__VA_OPT__ must be followed by an open parenthesis"));
1001 else if (tok.len == 1 && tok.text[0] == ')')
1003 --vaopt_state;
1004 if (vaopt_state == 1)
1006 /* Done with __VA_OPT__. */
1007 vaopt_state = 0;
1008 /* Don't emit. */
1009 continue;
1013 /* If __VA_ARGS__ is empty, then drop the contents of
1014 __VA_OPT__. */
1015 if (argv.back ().len == 0)
1016 continue;
1018 else if (token_is_vaopt)
1020 if (!is_varargs)
1021 error (_("__VA_OPT__ is only valid in a variadic macro"));
1022 vaopt_state = 1;
1023 /* Don't emit this token. */
1024 continue;
1027 /* Just for aesthetics. If we skipped some whitespace, copy
1028 that to DEST. */
1029 if (tok.text > original_rl_start)
1031 dest->appendmem (original_rl_start, tok.text - original_rl_start);
1032 dest->last_token = dest->len;
1035 /* Is this token the stringification operator? */
1036 if (tok.len == 1
1037 && tok.text[0] == '#')
1039 int arg;
1041 if (!lookahead_valid)
1042 error (_("Stringification operator requires an argument."));
1044 arg = find_parameter (&lookahead, is_varargs, va_arg_name,
1045 def->argc, def->argv);
1046 if (arg == -1)
1047 error (_("Argument to stringification operator must name "
1048 "a macro parameter."));
1050 stringify (dest, argv[arg].text, argv[arg].len);
1052 /* Read one token and let the loop iteration code handle the
1053 rest. */
1054 lookahead_rl_start = replacement_list.text;
1055 lookahead_valid = get_token (&lookahead, &replacement_list);
1057 /* Is this token the splicing operator? */
1058 else if (tok.len == 2
1059 && tok.text[0] == '#'
1060 && tok.text[1] == '#')
1061 error (_("Stray splicing operator"));
1062 /* Is the next token the splicing operator? */
1063 else if (lookahead_valid
1064 && lookahead.len == 2
1065 && lookahead.text[0] == '#'
1066 && lookahead.text[1] == '#')
1068 int finished = 0;
1069 int prev_was_comma = 0;
1071 /* Note that GCC warns if the result of splicing is not a
1072 token. In the debugger there doesn't seem to be much
1073 benefit from doing this. */
1075 /* Insert the first token. */
1076 if (tok.len == 1 && tok.text[0] == ',')
1077 prev_was_comma = 1;
1078 else
1080 int arg = find_parameter (&tok, is_varargs, va_arg_name,
1081 def->argc, def->argv);
1083 if (arg != -1)
1084 dest->appendmem (argv[arg].text, argv[arg].len);
1085 else
1086 dest->appendmem (tok.text, tok.len);
1089 /* Apply a possible sequence of ## operators. */
1090 for (;;)
1092 if (! get_token (&tok, &replacement_list))
1093 error (_("Splicing operator at end of macro"));
1095 /* Handle a comma before a ##. If we are handling
1096 varargs, and the token on the right hand side is the
1097 varargs marker, and the final argument is empty or
1098 missing, then drop the comma. This is a GNU
1099 extension. There is one ambiguous case here,
1100 involving pedantic behavior with an empty argument,
1101 but we settle that in favor of GNU-style (GCC uses an
1102 option). If we aren't dealing with varargs, we
1103 simply insert the comma. */
1104 if (prev_was_comma)
1106 if (! (is_varargs
1107 && tok.len == va_arg_name->len
1108 && !memcmp (tok.text, va_arg_name->text, tok.len)
1109 && argv.back ().len == 0))
1110 dest->appendmem (",", 1);
1111 prev_was_comma = 0;
1114 /* Insert the token. If it is a parameter, insert the
1115 argument. If it is a comma, treat it specially. */
1116 if (tok.len == 1 && tok.text[0] == ',')
1117 prev_was_comma = 1;
1118 else
1120 int arg = find_parameter (&tok, is_varargs, va_arg_name,
1121 def->argc, def->argv);
1123 if (arg != -1)
1124 dest->appendmem (argv[arg].text, argv[arg].len);
1125 else
1126 dest->appendmem (tok.text, tok.len);
1129 /* Now read another token. If it is another splice, we
1130 loop. */
1131 original_rl_start = replacement_list.text;
1132 if (! get_token (&tok, &replacement_list))
1134 finished = 1;
1135 break;
1138 if (! (tok.len == 2
1139 && tok.text[0] == '#'
1140 && tok.text[1] == '#'))
1141 break;
1144 if (prev_was_comma)
1146 /* We saw a comma. Insert it now. */
1147 dest->appendmem (",", 1);
1150 dest->last_token = dest->len;
1151 if (finished)
1152 lookahead_valid = 0;
1153 else
1155 /* Set up for the loop iterator. */
1156 lookahead = tok;
1157 lookahead_rl_start = original_rl_start;
1158 lookahead_valid = 1;
1161 else
1163 /* Is this token an identifier? */
1164 int substituted = 0;
1165 int arg = find_parameter (&tok, is_varargs, va_arg_name,
1166 def->argc, def->argv);
1168 if (arg != -1)
1170 /* Expand any macro invocations in the argument text,
1171 and append the result to dest. Remember that scan
1172 mutates its source, so we need to scan a new buffer
1173 referring to the argument's text, not the argument
1174 itself. */
1175 shared_macro_buffer arg_src (argv[arg].text, argv[arg].len);
1176 scan (dest, &arg_src, no_loop, scope);
1177 substituted = 1;
1180 /* If it wasn't a parameter, then just copy it across. */
1181 if (! substituted)
1182 append_tokens_without_splicing (dest, &tok);
1186 if (vaopt_state > 0)
1187 error (_("Unterminated __VA_OPT__"));
1191 /* Expand a call to a macro named ID, whose definition is DEF. Append
1192 its expansion to DEST. SRC is the input text following the ID
1193 token. We are currently rescanning the expansions of the macros
1194 named in NO_LOOP; don't re-expand them. Use LOOKUP_FUNC and
1195 LOOKUP_BATON to find definitions for any nested macro references.
1197 Return 1 if we decided to expand it, zero otherwise. (If it's a
1198 function-like macro name that isn't followed by an argument list,
1199 we don't expand it.) If we return zero, leave SRC unchanged. */
1200 static int
1201 expand (const char *id,
1202 struct macro_definition *def,
1203 growable_macro_buffer *dest,
1204 shared_macro_buffer *src,
1205 struct macro_name_list *no_loop,
1206 const macro_scope &scope)
1208 struct macro_name_list new_no_loop;
1210 /* Create a new node to be added to the front of the no-expand list.
1211 This list is appropriate for re-scanning replacement lists, but
1212 it is *not* appropriate for scanning macro arguments; invocations
1213 of the macro whose arguments we are gathering *do* get expanded
1214 there. */
1215 new_no_loop.name = id;
1216 new_no_loop.next = no_loop;
1218 /* What kind of macro are we expanding? */
1219 if (def->kind == macro_object_like)
1221 shared_macro_buffer replacement_list (def->replacement,
1222 strlen (def->replacement));
1224 scan (dest, &replacement_list, &new_no_loop, scope);
1225 return 1;
1227 else if (def->kind == macro_function_like)
1229 shared_macro_buffer va_arg_name;
1230 int is_varargs = 0;
1232 if (def->argc >= 1)
1234 if (strcmp (def->argv[def->argc - 1], "...") == 0)
1236 /* In C99-style varargs, substitution is done using
1237 __VA_ARGS__. */
1238 va_arg_name.set_shared ("__VA_ARGS__", strlen ("__VA_ARGS__"));
1239 is_varargs = 1;
1241 else
1243 int len = strlen (def->argv[def->argc - 1]);
1245 if (len > 3
1246 && strcmp (def->argv[def->argc - 1] + len - 3, "...") == 0)
1248 /* In GNU-style varargs, the name of the
1249 substitution parameter is the name of the formal
1250 argument without the "...". */
1251 va_arg_name.set_shared (def->argv[def->argc - 1], len - 3);
1252 is_varargs = 1;
1257 std::vector<shared_macro_buffer> argv;
1258 /* If we couldn't find any argument list, then we don't expand
1259 this macro. */
1260 if (!gather_arguments (id, src, is_varargs ? def->argc : -1,
1261 &argv))
1262 return 0;
1264 /* Check that we're passing an acceptable number of arguments for
1265 this macro. */
1266 if (argv.size () != def->argc)
1268 if (is_varargs && argv.size () >= def->argc - 1)
1270 /* Ok. */
1272 /* Remember that a sequence of tokens like "foo()" is a
1273 valid invocation of a macro expecting either zero or one
1274 arguments. */
1275 else if (! (argv.size () == 1
1276 && argv[0].len == 0
1277 && def->argc == 0))
1278 error (_("Wrong number of arguments to macro `%s' "
1279 "(expected %d, got %d)."),
1280 id, def->argc, int (argv.size ()));
1283 /* Note that we don't expand macro invocations in the arguments
1284 yet --- we let subst_args take care of that. Parameters that
1285 appear as operands of the stringifying operator "#" or the
1286 splicing operator "##" don't get macro references expanded,
1287 so we can't really tell whether it's appropriate to macro-
1288 expand an argument until we see how it's being used. */
1289 growable_macro_buffer substituted (0);
1290 substitute_args (&substituted, def, is_varargs, &va_arg_name,
1291 argv, no_loop, scope);
1293 /* Now `substituted' is the macro's replacement list, with all
1294 argument values substituted into it properly. Re-scan it for
1295 macro references, but don't expand invocations of this macro.
1297 We create a new buffer, `substituted_src', which points into
1298 `substituted', and scan that. We can't scan `substituted'
1299 itself, since the tokenization process moves the buffer's
1300 text pointer around, and we still need to be able to find
1301 `substituted's original text buffer after scanning it so we
1302 can free it. */
1303 shared_macro_buffer substituted_src (substituted.text, substituted.len);
1304 scan (dest, &substituted_src, &new_no_loop, scope);
1306 return 1;
1308 else
1309 internal_error (_("bad macro definition kind"));
1313 /* If the single token in SRC_FIRST followed by the tokens in SRC_REST
1314 constitute a macro invocation not forbidden in NO_LOOP, append its
1315 expansion to DEST and return non-zero. Otherwise, return zero, and
1316 leave DEST unchanged.
1318 SRC_FIRST must be a string built by get_token. */
1319 static int
1320 maybe_expand (growable_macro_buffer *dest,
1321 shared_macro_buffer *src_first,
1322 shared_macro_buffer *src_rest,
1323 struct macro_name_list *no_loop,
1324 const macro_scope &scope)
1326 /* Is this token an identifier? */
1327 if (src_first->is_identifier)
1329 /* Make a null-terminated copy of it, since that's what our
1330 lookup function expects. */
1331 std::string id (src_first->text, src_first->len);
1333 /* If we're currently re-scanning the result of expanding
1334 this macro, don't expand it again. */
1335 if (! currently_rescanning (no_loop, id.c_str ()))
1337 /* Does this identifier have a macro definition in scope? */
1338 macro_definition *def = standard_macro_lookup (id.c_str (), scope);
1340 if (def && expand (id.c_str (), def, dest, src_rest, no_loop, scope))
1341 return 1;
1345 return 0;
1349 /* Expand macro references in SRC, appending the results to DEST.
1350 Assume we are re-scanning the result of expanding the macros named
1351 in NO_LOOP, and don't try to re-expand references to them. */
1353 static void
1354 scan (growable_macro_buffer *dest,
1355 shared_macro_buffer *src,
1356 struct macro_name_list *no_loop,
1357 const macro_scope &scope)
1360 for (;;)
1362 shared_macro_buffer tok;
1363 const char *original_src_start = src->text;
1365 /* Find the next token in SRC. */
1366 if (! get_token (&tok, src))
1367 break;
1369 /* Just for aesthetics. If we skipped some whitespace, copy
1370 that to DEST. */
1371 if (tok.text > original_src_start)
1373 dest->appendmem (original_src_start, tok.text - original_src_start);
1374 dest->last_token = dest->len;
1377 if (! maybe_expand (dest, &tok, src, no_loop, scope))
1378 /* We didn't end up expanding tok as a macro reference, so
1379 simply append it to dest. */
1380 append_tokens_without_splicing (dest, &tok);
1383 /* Just for aesthetics. If there was any trailing whitespace in
1384 src, copy it to dest. */
1385 if (src->len)
1387 dest->appendmem (src->text, src->len);
1388 dest->last_token = dest->len;
1393 gdb::unique_xmalloc_ptr<char>
1394 macro_expand (const char *source, const macro_scope &scope)
1396 shared_macro_buffer src (source, strlen (source));
1398 growable_macro_buffer dest (0);
1399 dest.last_token = 0;
1401 scan (&dest, &src, 0, scope);
1403 dest.appendc ('\0');
1405 return dest.release ();
1409 gdb::unique_xmalloc_ptr<char>
1410 macro_expand_once (const char *source, const macro_scope &scope)
1412 error (_("Expand-once not implemented yet."));
1415 gdb::unique_xmalloc_ptr<char>
1416 macro_expand_next (const char **lexptr, const macro_scope &scope)
1418 shared_macro_buffer tok;
1420 /* Set up SRC to refer to the input text, pointed to by *lexptr. */
1421 shared_macro_buffer src (*lexptr, strlen (*lexptr));
1423 /* Set up DEST to receive the expansion, if there is one. */
1424 growable_macro_buffer dest (0);
1425 dest.last_token = 0;
1427 /* Get the text's first preprocessing token. */
1428 if (! get_token (&tok, &src))
1429 return nullptr;
1431 /* If it's a macro invocation, expand it. */
1432 if (maybe_expand (&dest, &tok, &src, 0, scope))
1434 /* It was a macro invocation! Package up the expansion as a
1435 null-terminated string and return it. Set *lexptr to the
1436 start of the next token in the input. */
1437 dest.appendc ('\0');
1438 *lexptr = src.text;
1439 return dest.release ();
1441 else
1443 /* It wasn't a macro invocation. */
1444 return nullptr;