xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/macroexp.c (revision 32d1c65c71fbdb65a012e8392a62a757dd6853e9)
1 /* C preprocessor macro expansion for GDB.
2    Copyright (C) 2002-2023 Free Software Foundation, Inc.
3    Contributed by Red Hat, Inc.
4 
5    This file is part of GDB.
6 
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.
11 
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.
16 
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/>.  */
19 
20 #include "defs.h"
21 #include "gdbsupport/gdb_obstack.h"
22 #include "macrotab.h"
23 #include "macroexp.h"
24 #include "macroscope.h"
25 #include "c-lang.h"
26 
27 
28 
29 
30 /* A string type that we can use to refer to substrings of other
31    strings.  */
32 
33 struct shared_macro_buffer
34 {
35   /* An array of characters.  This buffer is a pointer into some
36      larger string and thus we can't assume in that the text is
37      null-terminated.  */
38   const char *text;
39 
40   /* The number of characters in the string.  */
41   int len;
42 
43   /* For detecting token splicing.
44 
45      This is the index in TEXT of the first character of the token
46      that abuts the end of TEXT.  If TEXT contains no tokens, then we
47      set this equal to LEN.  If TEXT ends in whitespace, then there is
48      no token abutting the end of TEXT (it's just whitespace), and
49      again, we set this equal to LEN.  We set this to -1 if we don't
50      know the nature of TEXT.  */
51   int last_token = -1;
52 
53   /* If this buffer is holding the result from get_token, then this
54      is non-zero if it is an identifier token, zero otherwise.  */
55   int is_identifier = 0;
56 
57   shared_macro_buffer ()
58     : text (NULL),
59       len (0)
60   {
61   }
62 
63   /* Set the macro buffer to refer to the LEN bytes at ADDR, as a
64      shared substring.  */
65   shared_macro_buffer (const char *addr, int len)
66   {
67     set_shared (addr, len);
68   }
69 
70   /* Set the macro buffer to refer to the LEN bytes at ADDR, as a
71      shared substring.  */
72   void set_shared (const char *addr, int len_)
73   {
74     text = addr;
75     len = len_;
76   }
77 };
78 
79 /* A string type that we can resize and quickly append to.  */
80 
81 struct growable_macro_buffer
82 {
83   /* An array of characters.  The first LEN bytes are the real text,
84      but there are SIZE bytes allocated to the array.  */
85   char *text;
86 
87   /* The number of characters in the string.  */
88   int len;
89 
90   /* The number of characters allocated to the string.  */
91   int size;
92 
93   /* For detecting token splicing.
94 
95      This is the index in TEXT of the first character of the token
96      that abuts the end of TEXT.  If TEXT contains no tokens, then we
97      set this equal to LEN.  If TEXT ends in whitespace, then there is
98      no token abutting the end of TEXT (it's just whitespace), and
99      again, we set this equal to LEN.  We set this to -1 if we don't
100      know the nature of TEXT.  */
101   int last_token = -1;
102 
103   /* Set the macro buffer to the empty string, guessing that its
104      final contents will fit in N bytes.  (It'll get resized if it
105      doesn't, so the guess doesn't have to be right.)  Allocate the
106      initial storage with xmalloc.  */
107   explicit growable_macro_buffer (int n)
108     : len (0),
109       size (n)
110   {
111     if (n > 0)
112       text = (char *) xmalloc (n);
113     else
114       text = NULL;
115   }
116 
117   DISABLE_COPY_AND_ASSIGN (growable_macro_buffer);
118 
119   ~growable_macro_buffer ()
120   {
121     xfree (text);
122   }
123 
124   /* Release the text of the buffer to the caller.  */
125   gdb::unique_xmalloc_ptr<char> release ()
126   {
127     gdb_assert (size);
128     char *result = text;
129     text = NULL;
130     return gdb::unique_xmalloc_ptr<char> (result);
131   }
132 
133   /* Resize the buffer to be at least N bytes long.  */
134   void resize_buffer (int n)
135   {
136     if (size == 0)
137       size = n;
138     else
139       while (size <= n)
140 	size *= 2;
141 
142     text = (char *) xrealloc (text, size);
143   }
144 
145   /* Append the character C to the buffer.  */
146   void appendc (int c)
147   {
148     int new_len = len + 1;
149 
150     if (new_len > size)
151       resize_buffer (new_len);
152 
153     text[len] = c;
154     len = new_len;
155   }
156 
157   /* Append the COUNT bytes at ADDR to the buffer.  */
158   void appendmem (const char *addr, int count)
159   {
160     int new_len = len + count;
161 
162     if (new_len > size)
163       resize_buffer (new_len);
164 
165     memcpy (text + len, addr, count);
166     len = new_len;
167   }
168 };
169 
170 
171 
172 /* Recognizing preprocessor tokens.  */
173 
174 
175 int
176 macro_is_whitespace (int c)
177 {
178   return (c == ' '
179 	  || c == '\t'
180 	  || c == '\n'
181 	  || c == '\v'
182 	  || c == '\f');
183 }
184 
185 
186 int
187 macro_is_digit (int c)
188 {
189   return ('0' <= c && c <= '9');
190 }
191 
192 
193 int
194 macro_is_identifier_nondigit (int c)
195 {
196   return (c == '_'
197 	  || ('a' <= c && c <= 'z')
198 	  || ('A' <= c && c <= 'Z'));
199 }
200 
201 
202 static void
203 set_token (shared_macro_buffer *tok, const char *start, const char *end)
204 {
205   tok->set_shared (start, end - start);
206   tok->last_token = 0;
207 
208   /* Presumed; get_identifier may overwrite this.  */
209   tok->is_identifier = 0;
210 }
211 
212 
213 static int
214 get_comment (shared_macro_buffer *tok, const char *p, const char *end)
215 {
216   if (p + 2 > end)
217     return 0;
218   else if (p[0] == '/'
219 	   && p[1] == '*')
220     {
221       const char *tok_start = p;
222 
223       p += 2;
224 
225       for (; p < end; p++)
226 	if (p + 2 <= end
227 	    && p[0] == '*'
228 	    && p[1] == '/')
229 	  {
230 	    p += 2;
231 	    set_token (tok, tok_start, p);
232 	    return 1;
233 	  }
234 
235       error (_("Unterminated comment in macro expansion."));
236     }
237   else if (p[0] == '/'
238 	   && p[1] == '/')
239     {
240       const char *tok_start = p;
241 
242       p += 2;
243       for (; p < end; p++)
244 	if (*p == '\n')
245 	  break;
246 
247       set_token (tok, tok_start, p);
248       return 1;
249     }
250   else
251     return 0;
252 }
253 
254 
255 static int
256 get_identifier (shared_macro_buffer *tok, const char *p, const char *end)
257 {
258   if (p < end
259       && macro_is_identifier_nondigit (*p))
260     {
261       const char *tok_start = p;
262 
263       while (p < end
264 	     && (macro_is_identifier_nondigit (*p)
265 		 || macro_is_digit (*p)))
266 	p++;
267 
268       set_token (tok, tok_start, p);
269       tok->is_identifier = 1;
270       return 1;
271     }
272   else
273     return 0;
274 }
275 
276 
277 static int
278 get_pp_number (shared_macro_buffer *tok, const char *p, const char *end)
279 {
280   if (p < end
281       && (macro_is_digit (*p)
282 	  || (*p == '.'
283 	      && p + 2 <= end
284 	      && macro_is_digit (p[1]))))
285     {
286       const char *tok_start = p;
287 
288       while (p < end)
289 	{
290 	  if (p + 2 <= end
291 	      && strchr ("eEpP", *p)
292 	      && (p[1] == '+' || p[1] == '-'))
293 	    p += 2;
294 	  else if (macro_is_digit (*p)
295 		   || macro_is_identifier_nondigit (*p)
296 		   || *p == '.')
297 	    p++;
298 	  else
299 	    break;
300 	}
301 
302       set_token (tok, tok_start, p);
303       return 1;
304     }
305   else
306     return 0;
307 }
308 
309 
310 
311 /* If the text starting at P going up to (but not including) END
312    starts with a character constant, set *TOK to point to that
313    character constant, and return 1.  Otherwise, return zero.
314    Signal an error if it contains a malformed or incomplete character
315    constant.  */
316 static int
317 get_character_constant (shared_macro_buffer *tok,
318 			const char *p, const char *end)
319 {
320   /* ISO/IEC 9899:1999 (E)  Section 6.4.4.4  paragraph 1
321      But of course, what really matters is that we handle it the same
322      way GDB's C/C++ lexer does.  So we call parse_escape in utils.c
323      to handle escape sequences.  */
324   if ((p + 1 <= end && *p == '\'')
325       || (p + 2 <= end
326 	  && (p[0] == 'L' || p[0] == 'u' || p[0] == 'U')
327 	  && p[1] == '\''))
328     {
329       const char *tok_start = p;
330       int char_count = 0;
331 
332       if (*p == '\'')
333 	p++;
334       else if (*p == 'L' || *p == 'u' || *p == 'U')
335 	p += 2;
336       else
337 	gdb_assert_not_reached ("unexpected character constant");
338 
339       for (;;)
340 	{
341 	  if (p >= end)
342 	    error (_("Unmatched single quote."));
343 	  else if (*p == '\'')
344 	    {
345 	      if (!char_count)
346 		error (_("A character constant must contain at least one "
347 		       "character."));
348 	      p++;
349 	      break;
350 	    }
351 	  else if (*p == '\\')
352 	    {
353 	      const char *s, *o;
354 
355 	      s = o = ++p;
356 	      char_count += c_parse_escape (&s, NULL);
357 	      p += s - o;
358 	    }
359 	  else
360 	    {
361 	      p++;
362 	      char_count++;
363 	    }
364 	}
365 
366       set_token (tok, tok_start, p);
367       return 1;
368     }
369   else
370     return 0;
371 }
372 
373 
374 /* If the text starting at P going up to (but not including) END
375    starts with a string literal, set *TOK to point to that string
376    literal, and return 1.  Otherwise, return zero.  Signal an error if
377    it contains a malformed or incomplete string literal.  */
378 static int
379 get_string_literal (shared_macro_buffer *tok, const char *p, const char *end)
380 {
381   if ((p + 1 <= end
382        && *p == '"')
383       || (p + 2 <= end
384 	  && (p[0] == 'L' || p[0] == 'u' || p[0] == 'U')
385 	  && p[1] == '"'))
386     {
387       const char *tok_start = p;
388 
389       if (*p == '"')
390 	p++;
391       else if (*p == 'L' || *p == 'u' || *p == 'U')
392 	p += 2;
393       else
394 	gdb_assert_not_reached ("unexpected string literal");
395 
396       for (;;)
397 	{
398 	  if (p >= end)
399 	    error (_("Unterminated string in expression."));
400 	  else if (*p == '"')
401 	    {
402 	      p++;
403 	      break;
404 	    }
405 	  else if (*p == '\n')
406 	    error (_("Newline characters may not appear in string "
407 		   "constants."));
408 	  else if (*p == '\\')
409 	    {
410 	      const char *s, *o;
411 
412 	      s = o = ++p;
413 	      c_parse_escape (&s, NULL);
414 	      p += s - o;
415 	    }
416 	  else
417 	    p++;
418 	}
419 
420       set_token (tok, tok_start, p);
421       return 1;
422     }
423   else
424     return 0;
425 }
426 
427 
428 static int
429 get_punctuator (shared_macro_buffer *tok, const char *p, const char *end)
430 {
431   /* Here, speed is much less important than correctness and clarity.  */
432 
433   /* ISO/IEC 9899:1999 (E)  Section 6.4.6  Paragraph 1.
434      Note that this table is ordered in a special way.  A punctuator
435      which is a prefix of another punctuator must appear after its
436      "extension".  Otherwise, the wrong token will be returned.  */
437   static const char * const punctuators[] = {
438     "[", "]", "(", ")", "{", "}", "?", ";", ",", "~",
439     "...", ".",
440     "->", "--", "-=", "-",
441     "++", "+=", "+",
442     "*=", "*",
443     "!=", "!",
444     "&&", "&=", "&",
445     "/=", "/",
446     "%>", "%:%:", "%:", "%=", "%",
447     "^=", "^",
448     "##", "#",
449     ":>", ":",
450     "||", "|=", "|",
451     "<<=", "<<", "<=", "<:", "<%", "<",
452     ">>=", ">>", ">=", ">",
453     "==", "=",
454     0
455   };
456 
457   int i;
458 
459   if (p + 1 <= end)
460     {
461       for (i = 0; punctuators[i]; i++)
462 	{
463 	  const char *punctuator = punctuators[i];
464 
465 	  if (p[0] == punctuator[0])
466 	    {
467 	      int len = strlen (punctuator);
468 
469 	      if (p + len <= end
470 		  && ! memcmp (p, punctuator, len))
471 		{
472 		  set_token (tok, p, p + len);
473 		  return 1;
474 		}
475 	    }
476 	}
477     }
478 
479   return 0;
480 }
481 
482 
483 /* Peel the next preprocessor token off of SRC, and put it in TOK.
484    Mutate TOK to refer to the first token in SRC, and mutate SRC to
485    refer to the text after that token.  The resulting TOK will point
486    into the same string SRC does.  Initialize TOK's last_token field.
487    Return non-zero if we succeed, or 0 if we didn't find any more
488    tokens in SRC.  */
489 
490 static int
491 get_token (shared_macro_buffer *tok, shared_macro_buffer *src)
492 {
493   const char *p = src->text;
494   const char *end = p + src->len;
495 
496   /* From the ISO C standard, ISO/IEC 9899:1999 (E), section 6.4:
497 
498      preprocessing-token:
499 	 header-name
500 	 identifier
501 	 pp-number
502 	 character-constant
503 	 string-literal
504 	 punctuator
505 	 each non-white-space character that cannot be one of the above
506 
507      We don't have to deal with header-name tokens, since those can
508      only occur after a #include, which we will never see.  */
509 
510   while (p < end)
511     if (macro_is_whitespace (*p))
512       p++;
513     else if (get_comment (tok, p, end))
514       p += tok->len;
515     else if (get_pp_number (tok, p, end)
516 	     || get_character_constant (tok, p, end)
517 	     || get_string_literal (tok, p, end)
518 	     /* Note: the grammar in the standard seems to be
519 		ambiguous: L'x' can be either a wide character
520 		constant, or an identifier followed by a normal
521 		character constant.  By trying `get_identifier' after
522 		we try get_character_constant and get_string_literal,
523 		we give the wide character syntax precedence.  Now,
524 		since GDB doesn't handle wide character constants
525 		anyway, is this the right thing to do?  */
526 	     || get_identifier (tok, p, end)
527 	     || get_punctuator (tok, p, end))
528       {
529 	/* How many characters did we consume, including whitespace?  */
530 	int consumed = p - src->text + tok->len;
531 
532 	src->text += consumed;
533 	src->len -= consumed;
534 	return 1;
535       }
536     else
537       {
538 	/* We have found a "non-whitespace character that cannot be
539 	   one of the above."  Make a token out of it.  */
540 	int consumed;
541 
542 	set_token (tok, p, p + 1);
543 	consumed = p - src->text + tok->len;
544 	src->text += consumed;
545 	src->len -= consumed;
546 	return 1;
547       }
548 
549   return 0;
550 }
551 
552 
553 
554 /* Appending token strings, with and without splicing  */
555 
556 
557 /* Append the macro buffer SRC to the end of DEST, and ensure that
558    doing so doesn't splice the token at the end of SRC with the token
559    at the beginning of DEST.  SRC and DEST must have their last_token
560    fields set.  Upon return, DEST's last_token field is set correctly.
561 
562    For example:
563 
564    If DEST is "(" and SRC is "y", then we can return with
565    DEST set to "(y" --- we've simply appended the two buffers.
566 
567    However, if DEST is "x" and SRC is "y", then we must not return
568    with DEST set to "xy" --- that would splice the two tokens "x" and
569    "y" together to make a single token "xy".  However, it would be
570    fine to return with DEST set to "x y".  Similarly, "<" and "<" must
571    yield "< <", not "<<", etc.  */
572 static void
573 append_tokens_without_splicing (growable_macro_buffer *dest,
574                                 shared_macro_buffer *src)
575 {
576   int original_dest_len = dest->len;
577   shared_macro_buffer dest_tail, new_token;
578 
579   gdb_assert (src->last_token != -1);
580   gdb_assert (dest->last_token != -1);
581 
582   /* First, just try appending the two, and call get_token to see if
583      we got a splice.  */
584   dest->appendmem (src->text, src->len);
585 
586   /* If DEST originally had no token abutting its end, then we can't
587      have spliced anything, so we're done.  */
588   if (dest->last_token == original_dest_len)
589     {
590       dest->last_token = original_dest_len + src->last_token;
591       return;
592     }
593 
594   /* Set DEST_TAIL to point to the last token in DEST, followed by
595      all the stuff we just appended.  */
596   dest_tail.set_shared (dest->text + dest->last_token,
597 			dest->len - dest->last_token);
598 
599   /* Re-parse DEST's last token.  We know that DEST used to contain
600      at least one token, so if it doesn't contain any after the
601      append, then we must have spliced "/" and "*" or "/" and "/" to
602      make a comment start.  (Just for the record, I got this right
603      the first time.  This is not a bug fix.)  */
604   if (get_token (&new_token, &dest_tail)
605       && (new_token.text + new_token.len
606 	  == dest->text + original_dest_len))
607     {
608       /* No splice, so we're done.  */
609       dest->last_token = original_dest_len + src->last_token;
610       return;
611     }
612 
613   /* Okay, a simple append caused a splice.  Let's chop dest back to
614      its original length and try again, but separate the texts with a
615      space.  */
616   dest->len = original_dest_len;
617   dest->appendc (' ');
618   dest->appendmem (src->text, src->len);
619 
620   dest_tail.set_shared (dest->text + dest->last_token,
621 			dest->len - dest->last_token);
622 
623   /* Try to re-parse DEST's last token, as above.  */
624   if (get_token (&new_token, &dest_tail)
625       && (new_token.text + new_token.len
626 	  == dest->text + original_dest_len))
627     {
628       /* No splice, so we're done.  */
629       dest->last_token = original_dest_len + 1 + src->last_token;
630       return;
631     }
632 
633   /* As far as I know, there's no case where inserting a space isn't
634      enough to prevent a splice.  */
635   internal_error (_("unable to avoid splicing tokens during macro expansion"));
636 }
637 
638 /* Stringify an argument, and insert it into DEST.  ARG is the text to
639    stringify; it is LEN bytes long.  */
640 
641 static void
642 stringify (growable_macro_buffer *dest, const char *arg, int len)
643 {
644   /* Trim initial whitespace from ARG.  */
645   while (len > 0 && macro_is_whitespace (*arg))
646     {
647       ++arg;
648       --len;
649     }
650 
651   /* Trim trailing whitespace from ARG.  */
652   while (len > 0 && macro_is_whitespace (arg[len - 1]))
653     --len;
654 
655   /* Insert the string.  */
656   dest->appendc ('"');
657   while (len > 0)
658     {
659       /* We could try to handle strange cases here, like control
660 	 characters, but there doesn't seem to be much point.  */
661       if (macro_is_whitespace (*arg))
662 	{
663 	  /* Replace a sequence of whitespace with a single space.  */
664 	  dest->appendc (' ');
665 	  while (len > 1 && macro_is_whitespace (arg[1]))
666 	    {
667 	      ++arg;
668 	      --len;
669 	    }
670 	}
671       else if (*arg == '\\' || *arg == '"')
672 	{
673 	  dest->appendc ('\\');
674 	  dest->appendc (*arg);
675 	}
676       else
677 	dest->appendc (*arg);
678       ++arg;
679       --len;
680     }
681   dest->appendc ('"');
682   dest->last_token = dest->len;
683 }
684 
685 /* See macroexp.h.  */
686 
687 gdb::unique_xmalloc_ptr<char>
688 macro_stringify (const char *str)
689 {
690   int len = strlen (str);
691   growable_macro_buffer buffer (len);
692 
693   stringify (&buffer, str, len);
694   buffer.appendc ('\0');
695 
696   return buffer.release ();
697 }
698 
699 
700 /* Expanding macros!  */
701 
702 
703 /* A singly-linked list of the names of the macros we are currently
704    expanding --- for detecting expansion loops.  */
705 struct macro_name_list {
706   const char *name;
707   struct macro_name_list *next;
708 };
709 
710 
711 /* Return non-zero if we are currently expanding the macro named NAME,
712    according to LIST; otherwise, return zero.
713 
714    You know, it would be possible to get rid of all the NO_LOOP
715    arguments to these functions by simply generating a new lookup
716    function and baton which refuses to find the definition for a
717    particular macro, and otherwise delegates the decision to another
718    function/baton pair.  But that makes the linked list of excluded
719    macros chained through untyped baton pointers, which will make it
720    harder to debug.  :(  */
721 static int
722 currently_rescanning (struct macro_name_list *list, const char *name)
723 {
724   for (; list; list = list->next)
725     if (strcmp (name, list->name) == 0)
726       return 1;
727 
728   return 0;
729 }
730 
731 
732 /* Gather the arguments to a macro expansion.
733 
734    NAME is the name of the macro being invoked.  (It's only used for
735    printing error messages.)
736 
737    Assume that SRC is the text of the macro invocation immediately
738    following the macro name.  For example, if we're processing the
739    text foo(bar, baz), then NAME would be foo and SRC will be (bar,
740    baz).
741 
742    If SRC doesn't start with an open paren ( token at all, return
743    false, leave SRC unchanged, and don't set *ARGS_PTR to anything.
744 
745    If SRC doesn't contain a properly terminated argument list, then
746    raise an error.
747 
748    For a variadic macro, NARGS holds the number of formal arguments to
749    the macro.  For a GNU-style variadic macro, this should be the
750    number of named arguments.  For a non-variadic macro, NARGS should
751    be -1.
752 
753    Otherwise, return true and set *ARGS_PTR to a vector of macro
754    buffers referring to the argument texts.  The macro buffers share
755    their text with SRC, and their last_token fields are initialized.
756 
757    NOTE WELL: if SRC starts with a open paren ( token followed
758    immediately by a close paren ) token (e.g., the invocation looks
759    like "foo()"), we treat that as one argument, which happens to be
760    the empty list of tokens.  The caller should keep in mind that such
761    a sequence of tokens is a valid way to invoke one-parameter
762    function-like macros, but also a valid way to invoke zero-parameter
763    function-like macros.  Eeew.
764 
765    Consume the tokens from SRC; after this call, SRC contains the text
766    following the invocation.  */
767 
768 static bool
769 gather_arguments (const char *name, shared_macro_buffer *src, int nargs,
770 		  std::vector<shared_macro_buffer> *args_ptr)
771 {
772   shared_macro_buffer tok;
773   std::vector<shared_macro_buffer> args;
774 
775   /* Does SRC start with an opening paren token?  Read from a copy of
776      SRC, so SRC itself is unaffected if we don't find an opening
777      paren.  */
778   {
779     shared_macro_buffer temp (src->text, src->len);
780 
781     if (! get_token (&tok, &temp)
782 	|| tok.len != 1
783 	|| tok.text[0] != '(')
784       return false;
785   }
786 
787   /* Consume SRC's opening paren.  */
788   get_token (&tok, src);
789 
790   for (;;)
791     {
792       shared_macro_buffer *arg;
793       int depth;
794 
795       /* Initialize the next argument.  */
796       args.emplace_back ();
797       arg = &args.back ();
798       set_token (arg, src->text, src->text);
799 
800       /* Gather the argument's tokens.  */
801       depth = 0;
802       for (;;)
803 	{
804 	  if (! get_token (&tok, src))
805 	    error (_("Malformed argument list for macro `%s'."), name);
806 
807 	  /* Is tok an opening paren?  */
808 	  if (tok.len == 1 && tok.text[0] == '(')
809 	    depth++;
810 
811 	  /* Is tok is a closing paren?  */
812 	  else if (tok.len == 1 && tok.text[0] == ')')
813 	    {
814 	      /* If it's a closing paren at the top level, then that's
815 		 the end of the argument list.  */
816 	      if (depth == 0)
817 		{
818 		  /* In the varargs case, the last argument may be
819 		     missing.  Add an empty argument in this case.  */
820 		  if (nargs != -1 && args.size () == nargs - 1)
821 		    {
822 		      args.emplace_back ();
823 		      arg = &args.back ();
824 		      set_token (arg, src->text, src->text);
825 		    }
826 
827 		  *args_ptr = std::move (args);
828 		  return true;
829 		}
830 
831 	      depth--;
832 	    }
833 
834 	  /* If tok is a comma at top level, then that's the end of
835 	     the current argument.  However, if we are handling a
836 	     variadic macro and we are computing the last argument, we
837 	     want to include the comma and remaining tokens.  */
838 	  else if (tok.len == 1 && tok.text[0] == ',' && depth == 0
839 		   && (nargs == -1 || args.size () < nargs))
840 	    break;
841 
842 	  /* Extend the current argument to enclose this token.  If
843 	     this is the current argument's first token, leave out any
844 	     leading whitespace, just for aesthetics.  */
845 	  if (arg->len == 0)
846 	    {
847 	      arg->text = tok.text;
848 	      arg->len = tok.len;
849 	      arg->last_token = 0;
850 	    }
851 	  else
852 	    {
853 	      arg->len = (tok.text + tok.len) - arg->text;
854 	      arg->last_token = tok.text - arg->text;
855 	    }
856 	}
857     }
858 }
859 
860 
861 /* The `expand' and `substitute_args' functions both invoke `scan'
862    recursively, so we need a forward declaration somewhere.  */
863 static void scan (growable_macro_buffer *dest,
864 		  shared_macro_buffer *src,
865 		  struct macro_name_list *no_loop,
866 		  const macro_scope &scope);
867 
868 /* A helper function for substitute_args.
869 
870    ARGV is a vector of all the arguments; ARGC is the number of
871    arguments.  IS_VARARGS is true if the macro being substituted is a
872    varargs macro; in this case VA_ARG_NAME is the name of the
873    "variable" argument.  VA_ARG_NAME is ignored if IS_VARARGS is
874    false.
875 
876    If the token TOK is the name of a parameter, return the parameter's
877    index.  If TOK is not an argument, return -1.  */
878 
879 static int
880 find_parameter (const shared_macro_buffer *tok,
881 		int is_varargs, const shared_macro_buffer *va_arg_name,
882 		int argc, const char * const *argv)
883 {
884   int i;
885 
886   if (! tok->is_identifier)
887     return -1;
888 
889   for (i = 0; i < argc; ++i)
890     if (tok->len == strlen (argv[i])
891 	&& !memcmp (tok->text, argv[i], tok->len))
892       return i;
893 
894   if (is_varargs && tok->len == va_arg_name->len
895       && ! memcmp (tok->text, va_arg_name->text, tok->len))
896     return argc - 1;
897 
898   return -1;
899 }
900 
901 /* Helper function for substitute_args that gets the next token and
902    updates the passed-in state variables.  */
903 
904 static void
905 get_next_token_for_substitution (shared_macro_buffer *replacement_list,
906 				 shared_macro_buffer *token,
907 				 const char **start,
908 				 shared_macro_buffer *lookahead,
909 				 const char **lookahead_start,
910 				 int *lookahead_valid,
911 				 bool *keep_going)
912 {
913   if (!*lookahead_valid)
914     *keep_going = false;
915   else
916     {
917       *keep_going = true;
918       *token = *lookahead;
919       *start = *lookahead_start;
920       *lookahead_start = replacement_list->text;
921       *lookahead_valid = get_token (lookahead, replacement_list);
922     }
923 }
924 
925 /* Given the macro definition DEF, being invoked with the actual
926    arguments given by ARGV, substitute the arguments into the
927    replacement list, and store the result in DEST.
928 
929    IS_VARARGS should be true if DEF is a varargs macro.  In this case,
930    VA_ARG_NAME should be the name of the "variable" argument -- either
931    __VA_ARGS__ for c99-style varargs, or the final argument name, for
932    GNU-style varargs.  If IS_VARARGS is false, this parameter is
933    ignored.
934 
935    If it is necessary to expand macro invocations in one of the
936    arguments, use LOOKUP_FUNC and LOOKUP_BATON to find the macro
937    definitions, and don't expand invocations of the macros listed in
938    NO_LOOP.  */
939 
940 static void
941 substitute_args (growable_macro_buffer *dest,
942 		 struct macro_definition *def,
943 		 int is_varargs, const shared_macro_buffer *va_arg_name,
944 		 const std::vector<shared_macro_buffer> &argv,
945 		 struct macro_name_list *no_loop,
946 		 const macro_scope &scope)
947 {
948   /* The token we are currently considering.  */
949   shared_macro_buffer tok;
950   /* The replacement list's pointer from just before TOK was lexed.  */
951   const char *original_rl_start;
952   /* We have a single lookahead token to handle token splicing.  */
953   shared_macro_buffer lookahead;
954   /* The lookahead token might not be valid.  */
955   int lookahead_valid;
956   /* The replacement list's pointer from just before LOOKAHEAD was
957      lexed.  */
958   const char *lookahead_rl_start;
959 
960   /* A macro buffer for the macro's replacement list.  */
961   shared_macro_buffer replacement_list (def->replacement,
962 					strlen (def->replacement));
963 
964   gdb_assert (dest->len == 0);
965   dest->last_token = 0;
966 
967   original_rl_start = replacement_list.text;
968   if (! get_token (&tok, &replacement_list))
969     return;
970   lookahead_rl_start = replacement_list.text;
971   lookahead_valid = get_token (&lookahead, &replacement_list);
972 
973   /* __VA_OPT__ state variable.  The states are:
974      0 - nothing happening
975      1 - saw __VA_OPT__
976      >= 2 in __VA_OPT__, the value encodes the parenthesis depth.  */
977   unsigned vaopt_state = 0;
978 
979   for (bool keep_going = true;
980        keep_going;
981        get_next_token_for_substitution (&replacement_list,
982 					&tok,
983 					&original_rl_start,
984 					&lookahead,
985 					&lookahead_rl_start,
986 					&lookahead_valid,
987 					&keep_going))
988     {
989       bool token_is_vaopt = (tok.len == 10
990 			     && startswith (tok.text, "__VA_OPT__"));
991 
992       if (vaopt_state > 0)
993 	{
994 	  if (token_is_vaopt)
995 	    error (_("__VA_OPT__ cannot appear inside __VA_OPT__"));
996 	  else if (tok.len == 1 && tok.text[0] == '(')
997 	    {
998 	      ++vaopt_state;
999 	      /* We just entered __VA_OPT__, so don't emit this
1000 		 token.  */
1001 	      continue;
1002 	    }
1003 	  else if (vaopt_state == 1)
1004 	    error (_("__VA_OPT__ must be followed by an open parenthesis"));
1005 	  else if (tok.len == 1 && tok.text[0] == ')')
1006 	    {
1007 	      --vaopt_state;
1008 	      if (vaopt_state == 1)
1009 		{
1010 		  /* Done with __VA_OPT__.  */
1011 		  vaopt_state = 0;
1012 		  /* Don't emit.  */
1013 		  continue;
1014 		}
1015 	    }
1016 
1017 	  /* If __VA_ARGS__ is empty, then drop the contents of
1018 	     __VA_OPT__.  */
1019 	  if (argv.back ().len == 0)
1020 	    continue;
1021 	}
1022       else if (token_is_vaopt)
1023 	{
1024 	  if (!is_varargs)
1025 	    error (_("__VA_OPT__ is only valid in a variadic macro"));
1026 	  vaopt_state = 1;
1027 	  /* Don't emit this token.  */
1028 	  continue;
1029 	}
1030 
1031       /* Just for aesthetics.  If we skipped some whitespace, copy
1032 	 that to DEST.  */
1033       if (tok.text > original_rl_start)
1034 	{
1035 	  dest->appendmem (original_rl_start, tok.text - original_rl_start);
1036 	  dest->last_token = dest->len;
1037 	}
1038 
1039       /* Is this token the stringification operator?  */
1040       if (tok.len == 1
1041 	  && tok.text[0] == '#')
1042 	{
1043 	  int arg;
1044 
1045 	  if (!lookahead_valid)
1046 	    error (_("Stringification operator requires an argument."));
1047 
1048 	  arg = find_parameter (&lookahead, is_varargs, va_arg_name,
1049 				def->argc, def->argv);
1050 	  if (arg == -1)
1051 	    error (_("Argument to stringification operator must name "
1052 		     "a macro parameter."));
1053 
1054 	  stringify (dest, argv[arg].text, argv[arg].len);
1055 
1056 	  /* Read one token and let the loop iteration code handle the
1057 	     rest.  */
1058 	  lookahead_rl_start = replacement_list.text;
1059 	  lookahead_valid = get_token (&lookahead, &replacement_list);
1060 	}
1061       /* Is this token the splicing operator?  */
1062       else if (tok.len == 2
1063 	       && tok.text[0] == '#'
1064 	       && tok.text[1] == '#')
1065 	error (_("Stray splicing operator"));
1066       /* Is the next token the splicing operator?  */
1067       else if (lookahead_valid
1068 	       && lookahead.len == 2
1069 	       && lookahead.text[0] == '#'
1070 	       && lookahead.text[1] == '#')
1071 	{
1072 	  int finished = 0;
1073 	  int prev_was_comma = 0;
1074 
1075 	  /* Note that GCC warns if the result of splicing is not a
1076 	     token.  In the debugger there doesn't seem to be much
1077 	     benefit from doing this.  */
1078 
1079 	  /* Insert the first token.  */
1080 	  if (tok.len == 1 && tok.text[0] == ',')
1081 	    prev_was_comma = 1;
1082 	  else
1083 	    {
1084 	      int arg = find_parameter (&tok, is_varargs, va_arg_name,
1085 					def->argc, def->argv);
1086 
1087 	      if (arg != -1)
1088 		dest->appendmem (argv[arg].text, argv[arg].len);
1089 	      else
1090 		dest->appendmem (tok.text, tok.len);
1091 	    }
1092 
1093 	  /* Apply a possible sequence of ## operators.  */
1094 	  for (;;)
1095 	    {
1096 	      if (! get_token (&tok, &replacement_list))
1097 		error (_("Splicing operator at end of macro"));
1098 
1099 	      /* Handle a comma before a ##.  If we are handling
1100 		 varargs, and the token on the right hand side is the
1101 		 varargs marker, and the final argument is empty or
1102 		 missing, then drop the comma.  This is a GNU
1103 		 extension.  There is one ambiguous case here,
1104 		 involving pedantic behavior with an empty argument,
1105 		 but we settle that in favor of GNU-style (GCC uses an
1106 		 option).  If we aren't dealing with varargs, we
1107 		 simply insert the comma.  */
1108 	      if (prev_was_comma)
1109 		{
1110 		  if (! (is_varargs
1111 			 && tok.len == va_arg_name->len
1112 			 && !memcmp (tok.text, va_arg_name->text, tok.len)
1113 			 && argv.back ().len == 0))
1114 		    dest->appendmem (",", 1);
1115 		  prev_was_comma = 0;
1116 		}
1117 
1118 	      /* Insert the token.  If it is a parameter, insert the
1119 		 argument.  If it is a comma, treat it specially.  */
1120 	      if (tok.len == 1 && tok.text[0] == ',')
1121 		prev_was_comma = 1;
1122 	      else
1123 		{
1124 		  int arg = find_parameter (&tok, is_varargs, va_arg_name,
1125 					    def->argc, def->argv);
1126 
1127 		  if (arg != -1)
1128 		    dest->appendmem (argv[arg].text, argv[arg].len);
1129 		  else
1130 		    dest->appendmem (tok.text, tok.len);
1131 		}
1132 
1133 	      /* Now read another token.  If it is another splice, we
1134 		 loop.  */
1135 	      original_rl_start = replacement_list.text;
1136 	      if (! get_token (&tok, &replacement_list))
1137 		{
1138 		  finished = 1;
1139 		  break;
1140 		}
1141 
1142 	      if (! (tok.len == 2
1143 		     && tok.text[0] == '#'
1144 		     && tok.text[1] == '#'))
1145 		break;
1146 	    }
1147 
1148 	  if (prev_was_comma)
1149 	    {
1150 	      /* We saw a comma.  Insert it now.  */
1151 	      dest->appendmem (",", 1);
1152 	    }
1153 
1154 	  dest->last_token = dest->len;
1155 	  if (finished)
1156 	    lookahead_valid = 0;
1157 	  else
1158 	    {
1159 	      /* Set up for the loop iterator.  */
1160 	      lookahead = tok;
1161 	      lookahead_rl_start = original_rl_start;
1162 	      lookahead_valid = 1;
1163 	    }
1164 	}
1165       else
1166 	{
1167 	  /* Is this token an identifier?  */
1168 	  int substituted = 0;
1169 	  int arg = find_parameter (&tok, is_varargs, va_arg_name,
1170 				    def->argc, def->argv);
1171 
1172 	  if (arg != -1)
1173 	    {
1174 	      /* Expand any macro invocations in the argument text,
1175 		 and append the result to dest.  Remember that scan
1176 		 mutates its source, so we need to scan a new buffer
1177 		 referring to the argument's text, not the argument
1178 		 itself.  */
1179 	      shared_macro_buffer arg_src (argv[arg].text, argv[arg].len);
1180 	      scan (dest, &arg_src, no_loop, scope);
1181 	      substituted = 1;
1182 	    }
1183 
1184 	  /* If it wasn't a parameter, then just copy it across.  */
1185 	  if (! substituted)
1186 	    append_tokens_without_splicing (dest, &tok);
1187 	}
1188     }
1189 
1190   if (vaopt_state > 0)
1191     error (_("Unterminated __VA_OPT__"));
1192 }
1193 
1194 
1195 /* Expand a call to a macro named ID, whose definition is DEF.  Append
1196    its expansion to DEST.  SRC is the input text following the ID
1197    token.  We are currently rescanning the expansions of the macros
1198    named in NO_LOOP; don't re-expand them.  Use LOOKUP_FUNC and
1199    LOOKUP_BATON to find definitions for any nested macro references.
1200 
1201    Return 1 if we decided to expand it, zero otherwise.  (If it's a
1202    function-like macro name that isn't followed by an argument list,
1203    we don't expand it.)  If we return zero, leave SRC unchanged.  */
1204 static int
1205 expand (const char *id,
1206 	struct macro_definition *def,
1207 	growable_macro_buffer *dest,
1208 	shared_macro_buffer *src,
1209 	struct macro_name_list *no_loop,
1210 	const macro_scope &scope)
1211 {
1212   struct macro_name_list new_no_loop;
1213 
1214   /* Create a new node to be added to the front of the no-expand list.
1215      This list is appropriate for re-scanning replacement lists, but
1216      it is *not* appropriate for scanning macro arguments; invocations
1217      of the macro whose arguments we are gathering *do* get expanded
1218      there.  */
1219   new_no_loop.name = id;
1220   new_no_loop.next = no_loop;
1221 
1222   /* What kind of macro are we expanding?  */
1223   if (def->kind == macro_object_like)
1224     {
1225       shared_macro_buffer replacement_list (def->replacement,
1226 					    strlen (def->replacement));
1227 
1228       scan (dest, &replacement_list, &new_no_loop, scope);
1229       return 1;
1230     }
1231   else if (def->kind == macro_function_like)
1232     {
1233       shared_macro_buffer va_arg_name;
1234       int is_varargs = 0;
1235 
1236       if (def->argc >= 1)
1237 	{
1238 	  if (strcmp (def->argv[def->argc - 1], "...") == 0)
1239 	    {
1240 	      /* In C99-style varargs, substitution is done using
1241 		 __VA_ARGS__.  */
1242 	      va_arg_name.set_shared ("__VA_ARGS__", strlen ("__VA_ARGS__"));
1243 	      is_varargs = 1;
1244 	    }
1245 	  else
1246 	    {
1247 	      int len = strlen (def->argv[def->argc - 1]);
1248 
1249 	      if (len > 3
1250 		  && strcmp (def->argv[def->argc - 1] + len - 3, "...") == 0)
1251 		{
1252 		  /* In GNU-style varargs, the name of the
1253 		     substitution parameter is the name of the formal
1254 		     argument without the "...".  */
1255 		  va_arg_name.set_shared (def->argv[def->argc - 1], len - 3);
1256 		  is_varargs = 1;
1257 		}
1258 	    }
1259 	}
1260 
1261       std::vector<shared_macro_buffer> argv;
1262       /* If we couldn't find any argument list, then we don't expand
1263 	 this macro.  */
1264       if (!gather_arguments (id, src, is_varargs ? def->argc : -1,
1265 			     &argv))
1266 	return 0;
1267 
1268       /* Check that we're passing an acceptable number of arguments for
1269 	 this macro.  */
1270       if (argv.size () != def->argc)
1271 	{
1272 	  if (is_varargs && argv.size () >= def->argc - 1)
1273 	    {
1274 	      /* Ok.  */
1275 	    }
1276 	  /* Remember that a sequence of tokens like "foo()" is a
1277 	     valid invocation of a macro expecting either zero or one
1278 	     arguments.  */
1279 	  else if (! (argv.size () == 1
1280 		      && argv[0].len == 0
1281 		      && def->argc == 0))
1282 	    error (_("Wrong number of arguments to macro `%s' "
1283 		   "(expected %d, got %d)."),
1284 		   id, def->argc, int (argv.size ()));
1285 	}
1286 
1287       /* Note that we don't expand macro invocations in the arguments
1288 	 yet --- we let subst_args take care of that.  Parameters that
1289 	 appear as operands of the stringifying operator "#" or the
1290 	 splicing operator "##" don't get macro references expanded,
1291 	 so we can't really tell whether it's appropriate to macro-
1292 	 expand an argument until we see how it's being used.  */
1293       growable_macro_buffer substituted (0);
1294       substitute_args (&substituted, def, is_varargs, &va_arg_name,
1295 		       argv, no_loop, scope);
1296 
1297       /* Now `substituted' is the macro's replacement list, with all
1298 	 argument values substituted into it properly.	Re-scan it for
1299 	 macro references, but don't expand invocations of this macro.
1300 
1301 	 We create a new buffer, `substituted_src', which points into
1302 	 `substituted', and scan that.	We can't scan `substituted'
1303 	 itself, since the tokenization process moves the buffer's
1304 	 text pointer around, and we still need to be able to find
1305 	 `substituted's original text buffer after scanning it so we
1306 	 can free it.  */
1307       shared_macro_buffer substituted_src (substituted.text, substituted.len);
1308       scan (dest, &substituted_src, &new_no_loop, scope);
1309 
1310       return 1;
1311     }
1312   else
1313     internal_error (_("bad macro definition kind"));
1314 }
1315 
1316 
1317 /* If the single token in SRC_FIRST followed by the tokens in SRC_REST
1318    constitute a macro invocation not forbidden in NO_LOOP, append its
1319    expansion to DEST and return non-zero.  Otherwise, return zero, and
1320    leave DEST unchanged.
1321 
1322    SRC_FIRST must be a string built by get_token.  */
1323 static int
1324 maybe_expand (growable_macro_buffer *dest,
1325 	      shared_macro_buffer *src_first,
1326 	      shared_macro_buffer *src_rest,
1327 	      struct macro_name_list *no_loop,
1328 	      const macro_scope &scope)
1329 {
1330   /* Is this token an identifier?  */
1331   if (src_first->is_identifier)
1332     {
1333       /* Make a null-terminated copy of it, since that's what our
1334 	 lookup function expects.  */
1335       std::string id (src_first->text, src_first->len);
1336 
1337       /* If we're currently re-scanning the result of expanding
1338 	 this macro, don't expand it again.  */
1339       if (! currently_rescanning (no_loop, id.c_str ()))
1340 	{
1341 	  /* Does this identifier have a macro definition in scope?  */
1342 	  macro_definition *def = standard_macro_lookup (id.c_str (), scope);
1343 
1344 	  if (def && expand (id.c_str (), def, dest, src_rest, no_loop, scope))
1345 	    return 1;
1346 	}
1347     }
1348 
1349   return 0;
1350 }
1351 
1352 
1353 /* Expand macro references in SRC, appending the results to DEST.
1354    Assume we are re-scanning the result of expanding the macros named
1355    in NO_LOOP, and don't try to re-expand references to them.  */
1356 
1357 static void
1358 scan (growable_macro_buffer *dest,
1359       shared_macro_buffer *src,
1360       struct macro_name_list *no_loop,
1361       const macro_scope &scope)
1362 {
1363 
1364   for (;;)
1365     {
1366       shared_macro_buffer tok;
1367       const char *original_src_start = src->text;
1368 
1369       /* Find the next token in SRC.  */
1370       if (! get_token (&tok, src))
1371 	break;
1372 
1373       /* Just for aesthetics.  If we skipped some whitespace, copy
1374 	 that to DEST.  */
1375       if (tok.text > original_src_start)
1376 	{
1377 	  dest->appendmem (original_src_start, tok.text - original_src_start);
1378 	  dest->last_token = dest->len;
1379 	}
1380 
1381       if (! maybe_expand (dest, &tok, src, no_loop, scope))
1382 	/* We didn't end up expanding tok as a macro reference, so
1383 	   simply append it to dest.  */
1384 	append_tokens_without_splicing (dest, &tok);
1385     }
1386 
1387   /* Just for aesthetics.  If there was any trailing whitespace in
1388      src, copy it to dest.  */
1389   if (src->len)
1390     {
1391       dest->appendmem (src->text, src->len);
1392       dest->last_token = dest->len;
1393     }
1394 }
1395 
1396 
1397 gdb::unique_xmalloc_ptr<char>
1398 macro_expand (const char *source, const macro_scope &scope)
1399 {
1400   shared_macro_buffer src (source, strlen (source));
1401 
1402   growable_macro_buffer dest (0);
1403   dest.last_token = 0;
1404 
1405   scan (&dest, &src, 0, scope);
1406 
1407   dest.appendc ('\0');
1408 
1409   return dest.release ();
1410 }
1411 
1412 
1413 gdb::unique_xmalloc_ptr<char>
1414 macro_expand_once (const char *source, const macro_scope &scope)
1415 {
1416   error (_("Expand-once not implemented yet."));
1417 }
1418 
1419 gdb::unique_xmalloc_ptr<char>
1420 macro_expand_next (const char **lexptr, const macro_scope &scope)
1421 {
1422   shared_macro_buffer tok;
1423 
1424   /* Set up SRC to refer to the input text, pointed to by *lexptr.  */
1425   shared_macro_buffer src (*lexptr, strlen (*lexptr));
1426 
1427   /* Set up DEST to receive the expansion, if there is one.  */
1428   growable_macro_buffer dest (0);
1429   dest.last_token = 0;
1430 
1431   /* Get the text's first preprocessing token.  */
1432   if (! get_token (&tok, &src))
1433     return nullptr;
1434 
1435   /* If it's a macro invocation, expand it.  */
1436   if (maybe_expand (&dest, &tok, &src, 0, scope))
1437     {
1438       /* It was a macro invocation!  Package up the expansion as a
1439 	 null-terminated string and return it.  Set *lexptr to the
1440 	 start of the next token in the input.  */
1441       dest.appendc ('\0');
1442       *lexptr = src.text;
1443       return dest.release ();
1444     }
1445   else
1446     {
1447       /* It wasn't a macro invocation.  */
1448       return nullptr;
1449     }
1450 }
1451