* macroexp.c (init_buffer): Remove testing code that overrides the
[external/binutils.git] / gdb / macroexp.c
1 /* C preprocessor macro expansion for GDB.
2    Copyright (C) 2002, 2007 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 2 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, write to the Free Software
19    Foundation, Inc., 51 Franklin Street, Fifth Floor,
20    Boston, MA 02110-1301, USA.  */
21
22 #include "defs.h"
23 #include "gdb_obstack.h"
24 #include "bcache.h"
25 #include "macrotab.h"
26 #include "macroexp.h"
27 #include "gdb_assert.h"
28
29
30 \f
31 /* A resizeable, substringable string type.  */
32
33
34 /* A string type that we can resize, quickly append to, and use to
35    refer to substrings of other strings.  */
36 struct macro_buffer
37 {
38   /* An array of characters.  The first LEN bytes are the real text,
39      but there are SIZE bytes allocated to the array.  If SIZE is
40      zero, then this doesn't point to a malloc'ed block.  If SHARED is
41      non-zero, then this buffer is actually a pointer into some larger
42      string, and we shouldn't append characters to it, etc.  Because
43      of sharing, we can't assume in general that the text is
44      null-terminated.  */
45   char *text;
46
47   /* The number of characters in the string.  */
48   int len;
49
50   /* The number of characters allocated to the string.  If SHARED is
51      non-zero, this is meaningless; in this case, we set it to zero so
52      that any "do we have room to append something?" tests will fail,
53      so we don't always have to check SHARED before using this field.  */
54   int size;
55
56   /* Zero if TEXT can be safely realloc'ed (i.e., it's its own malloc
57      block).  Non-zero if TEXT is actually pointing into the middle of
58      some other block, and we shouldn't reallocate it.  */
59   int shared;
60
61   /* For detecting token splicing. 
62
63      This is the index in TEXT of the first character of the token
64      that abuts the end of TEXT.  If TEXT contains no tokens, then we
65      set this equal to LEN.  If TEXT ends in whitespace, then there is
66      no token abutting the end of TEXT (it's just whitespace), and
67      again, we set this equal to LEN.  We set this to -1 if we don't
68      know the nature of TEXT.  */
69   int last_token;
70
71   /* If this buffer is holding the result from get_token, then this 
72      is non-zero if it is an identifier token, zero otherwise.  */
73   int is_identifier;
74 };
75
76
77 /* Set the macro buffer *B to the empty string, guessing that its
78    final contents will fit in N bytes.  (It'll get resized if it
79    doesn't, so the guess doesn't have to be right.)  Allocate the
80    initial storage with xmalloc.  */
81 static void
82 init_buffer (struct macro_buffer *b, int n)
83 {
84   b->size = n;
85   if (n > 0)
86     b->text = (char *) xmalloc (n);
87   else
88     b->text = NULL;
89   b->len = 0;
90   b->shared = 0;
91   b->last_token = -1;
92 }
93
94
95 /* Set the macro buffer *BUF to refer to the LEN bytes at ADDR, as a
96    shared substring.  */
97 static void
98 init_shared_buffer (struct macro_buffer *buf, char *addr, int len)
99 {
100   buf->text = addr;
101   buf->len = len;
102   buf->shared = 1;
103   buf->size = 0;
104   buf->last_token = -1;
105 }
106
107
108 /* Free the text of the buffer B.  Raise an error if B is shared.  */
109 static void
110 free_buffer (struct macro_buffer *b)
111 {
112   gdb_assert (! b->shared);
113   if (b->size)
114     xfree (b->text);
115 }
116
117
118 /* A cleanup function for macro buffers.  */
119 static void
120 cleanup_macro_buffer (void *untyped_buf)
121 {
122   free_buffer ((struct macro_buffer *) untyped_buf);
123 }
124
125
126 /* Resize the buffer B to be at least N bytes long.  Raise an error if
127    B shouldn't be resized.  */
128 static void
129 resize_buffer (struct macro_buffer *b, int n)
130 {
131   /* We shouldn't be trying to resize shared strings.  */
132   gdb_assert (! b->shared);
133   
134   if (b->size == 0)
135     b->size = n;
136   else
137     while (b->size <= n)
138       b->size *= 2;
139
140   b->text = xrealloc (b->text, b->size);
141 }
142
143
144 /* Append the character C to the buffer B.  */
145 static void
146 appendc (struct macro_buffer *b, int c)
147 {
148   int new_len = b->len + 1;
149
150   if (new_len > b->size)
151     resize_buffer (b, new_len);
152
153   b->text[b->len] = c;
154   b->len = new_len;
155 }
156
157
158 /* Append the LEN bytes at ADDR to the buffer B.  */
159 static void
160 appendmem (struct macro_buffer *b, char *addr, int len)
161 {
162   int new_len = b->len + len;
163
164   if (new_len > b->size)
165     resize_buffer (b, new_len);
166
167   memcpy (b->text + b->len, addr, len);
168   b->len = new_len;
169 }
170
171
172 \f
173 /* Recognizing preprocessor tokens.  */
174
175
176 static int
177 is_whitespace (int c)
178 {
179   return (c == ' '
180           || c == '\t'
181           || c == '\n'
182           || c == '\v'
183           || c == '\f');
184 }
185
186
187 static int
188 is_digit (int c)
189 {
190   return ('0' <= c && c <= '9');
191 }
192
193
194 static int
195 is_identifier_nondigit (int c)
196 {
197   return (c == '_'
198           || ('a' <= c && c <= 'z')
199           || ('A' <= c && c <= 'Z'));
200 }
201
202
203 static void
204 set_token (struct macro_buffer *tok, char *start, char *end)
205 {
206   init_shared_buffer (tok, start, end - start);
207   tok->last_token = 0;
208
209   /* Presumed; get_identifier may overwrite this. */
210   tok->is_identifier = 0;
211 }
212
213
214 static int
215 get_comment (struct macro_buffer *tok, char *p, char *end)
216 {
217   if (p + 2 > end)
218     return 0;
219   else if (p[0] == '/'
220            && p[1] == '*')
221     {
222       char *tok_start = p;
223
224       p += 2;
225
226       for (; p < end; p++)
227         if (p + 2 <= end
228             && p[0] == '*'
229             && p[1] == '/')
230           {
231             p += 2;
232             set_token (tok, tok_start, p);
233             return 1;
234           }
235
236       error (_("Unterminated comment in macro expansion."));
237     }
238   else if (p[0] == '/'
239            && p[1] == '/')
240     {
241       char *tok_start = p;
242
243       p += 2;
244       for (; p < end; p++)
245         if (*p == '\n')
246           break;
247
248       set_token (tok, tok_start, p);
249       return 1;
250     }
251   else
252     return 0;
253 }
254
255
256 static int
257 get_identifier (struct macro_buffer *tok, char *p, char *end)
258 {
259   if (p < end
260       && is_identifier_nondigit (*p))
261     {
262       char *tok_start = p;
263
264       while (p < end
265              && (is_identifier_nondigit (*p)
266                  || is_digit (*p)))
267         p++;
268
269       set_token (tok, tok_start, p);
270       tok->is_identifier = 1;
271       return 1;
272     }
273   else
274     return 0;
275 }
276
277
278 static int
279 get_pp_number (struct macro_buffer *tok, char *p, char *end)
280 {
281   if (p < end
282       && (is_digit (*p)
283           || *p == '.'))
284     {
285       char *tok_start = p;
286
287       while (p < end)
288         {
289           if (is_digit (*p)
290               || is_identifier_nondigit (*p)
291               || *p == '.')
292             p++;
293           else if (p + 2 <= end
294                    && strchr ("eEpP.", *p)
295                    && (p[1] == '+' || p[1] == '-'))
296             p += 2;
297           else
298             break;
299         }
300
301       set_token (tok, tok_start, p);
302       return 1;
303     }
304   else
305     return 0;
306 }
307
308
309
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 (struct macro_buffer *tok, char *p, char *end)
317 {
318   /* ISO/IEC 9899:1999 (E)  Section 6.4.4.4  paragraph 1 
319      But of course, what really matters is that we handle it the same
320      way GDB's C/C++ lexer does.  So we call parse_escape in utils.c
321      to handle escape sequences.  */
322   if ((p + 1 <= end && *p == '\'')
323       || (p + 2 <= end && p[0] == 'L' && p[1] == '\''))
324     {
325       char *tok_start = p;
326       char *body_start;
327
328       if (*p == '\'')
329         p++;
330       else if (*p == 'L')
331         p += 2;
332       else
333         gdb_assert (0);
334
335       body_start = p;
336       for (;;)
337         {
338           if (p >= end)
339             error (_("Unmatched single quote."));
340           else if (*p == '\'')
341             {
342               if (p == body_start)
343                 error (_("A character constant must contain at least one "
344                        "character."));
345               p++;
346               break;
347             }
348           else if (*p == '\\')
349             {
350               p++;
351               parse_escape (&p);
352             }
353           else
354             p++;
355         }
356
357       set_token (tok, tok_start, p);
358       return 1;
359     }
360   else
361     return 0;
362 }
363
364
365 /* If the text starting at P going up to (but not including) END
366    starts with a string literal, set *TOK to point to that string
367    literal, and return 1.  Otherwise, return zero.  Signal an error if
368    it contains a malformed or incomplete string literal.  */
369 static int
370 get_string_literal (struct macro_buffer *tok, char *p, char *end)
371 {
372   if ((p + 1 <= end
373        && *p == '\"')
374       || (p + 2 <= end
375           && p[0] == 'L'
376           && p[1] == '\"'))
377     {
378       char *tok_start = p;
379
380       if (*p == '\"')
381         p++;
382       else if (*p == 'L')
383         p += 2;
384       else
385         gdb_assert (0);
386
387       for (;;)
388         {
389           if (p >= end)
390             error (_("Unterminated string in expression."));
391           else if (*p == '\"')
392             {
393               p++;
394               break;
395             }
396           else if (*p == '\n')
397             error (_("Newline characters may not appear in string "
398                    "constants."));
399           else if (*p == '\\')
400             {
401               p++;
402               parse_escape (&p);
403             }
404           else
405             p++;
406         }
407
408       set_token (tok, tok_start, p);
409       return 1;
410     }
411   else
412     return 0;
413 }
414
415
416 static int
417 get_punctuator (struct macro_buffer *tok, char *p, char *end)
418 {
419   /* Here, speed is much less important than correctness and clarity.  */
420
421   /* ISO/IEC 9899:1999 (E)  Section 6.4.6  Paragraph 1  */
422   static const char * const punctuators[] = {
423     "[", "]", "(", ")", "{", "}", ".", "->", 
424     "++", "--", "&", "*", "+", "-", "~", "!",
425     "/", "%", "<<", ">>", "<", ">", "<=", ">=", "==", "!=", 
426     "^", "|", "&&", "||",
427     "?", ":", ";", "...",
428     "=", "*=", "/=", "%=", "+=", "-=", "<<=", ">>=", "&=", "^=", "|=",
429     ",", "#", "##",
430     "<:", ":>", "<%", "%>", "%:", "%:%:",
431     0
432   };
433
434   int i;
435
436   if (p + 1 <= end)
437     {
438       for (i = 0; punctuators[i]; i++)
439         {
440           const char *punctuator = punctuators[i];
441
442           if (p[0] == punctuator[0])
443             {
444               int len = strlen (punctuator);
445
446               if (p + len <= end
447                   && ! memcmp (p, punctuator, len))
448                 {
449                   set_token (tok, p, p + len);
450                   return 1;
451                 }
452             }
453         }
454     }
455
456   return 0;
457 }
458
459
460 /* Peel the next preprocessor token off of SRC, and put it in TOK.
461    Mutate TOK to refer to the first token in SRC, and mutate SRC to
462    refer to the text after that token.  SRC must be a shared buffer;
463    the resulting TOK will be shared, pointing into the same string SRC
464    does.  Initialize TOK's last_token field.  Return non-zero if we
465    succeed, or 0 if we didn't find any more tokens in SRC.  */
466 static int
467 get_token (struct macro_buffer *tok,
468            struct macro_buffer *src)
469 {
470   char *p = src->text;
471   char *end = p + src->len;
472
473   gdb_assert (src->shared);
474
475   /* From the ISO C standard, ISO/IEC 9899:1999 (E), section 6.4:
476
477      preprocessing-token: 
478          header-name
479          identifier
480          pp-number
481          character-constant
482          string-literal
483          punctuator
484          each non-white-space character that cannot be one of the above
485
486      We don't have to deal with header-name tokens, since those can
487      only occur after a #include, which we will never see.  */
488
489   while (p < end)
490     if (is_whitespace (*p))
491       p++;
492     else if (get_comment (tok, p, end))
493       p += tok->len;
494     else if (get_pp_number (tok, p, end)
495              || get_character_constant (tok, p, end)
496              || get_string_literal (tok, p, end)
497              /* Note: the grammar in the standard seems to be
498                 ambiguous: L'x' can be either a wide character
499                 constant, or an identifier followed by a normal
500                 character constant.  By trying `get_identifier' after
501                 we try get_character_constant and get_string_literal,
502                 we give the wide character syntax precedence.  Now,
503                 since GDB doesn't handle wide character constants
504                 anyway, is this the right thing to do?  */
505              || get_identifier (tok, p, end)
506              || get_punctuator (tok, p, end))
507       {
508         /* How many characters did we consume, including whitespace?  */
509         int consumed = p - src->text + tok->len;
510         src->text += consumed;
511         src->len -= consumed;
512         return 1;
513       }
514     else 
515       {
516         /* We have found a "non-whitespace character that cannot be
517            one of the above."  Make a token out of it.  */
518         int consumed;
519
520         set_token (tok, p, p + 1);
521         consumed = p - src->text + tok->len;
522         src->text += consumed;
523         src->len -= consumed;
524         return 1;
525       }
526
527   return 0;
528 }
529
530
531 \f
532 /* Appending token strings, with and without splicing  */
533
534
535 /* Append the macro buffer SRC to the end of DEST, and ensure that
536    doing so doesn't splice the token at the end of SRC with the token
537    at the beginning of DEST.  SRC and DEST must have their last_token
538    fields set.  Upon return, DEST's last_token field is set correctly.
539
540    For example:
541
542    If DEST is "(" and SRC is "y", then we can return with
543    DEST set to "(y" --- we've simply appended the two buffers.
544
545    However, if DEST is "x" and SRC is "y", then we must not return
546    with DEST set to "xy" --- that would splice the two tokens "x" and
547    "y" together to make a single token "xy".  However, it would be
548    fine to return with DEST set to "x y".  Similarly, "<" and "<" must
549    yield "< <", not "<<", etc.  */
550 static void
551 append_tokens_without_splicing (struct macro_buffer *dest,
552                                 struct macro_buffer *src)
553 {
554   int original_dest_len = dest->len;
555   struct macro_buffer dest_tail, new_token;
556
557   gdb_assert (src->last_token != -1);
558   gdb_assert (dest->last_token != -1);
559   
560   /* First, just try appending the two, and call get_token to see if
561      we got a splice.  */
562   appendmem (dest, src->text, src->len);
563
564   /* If DEST originally had no token abutting its end, then we can't
565      have spliced anything, so we're done.  */
566   if (dest->last_token == original_dest_len)
567     {
568       dest->last_token = original_dest_len + src->last_token;
569       return;
570     }
571
572   /* Set DEST_TAIL to point to the last token in DEST, followed by
573      all the stuff we just appended.  */
574   init_shared_buffer (&dest_tail,
575                       dest->text + dest->last_token,
576                       dest->len - dest->last_token);
577
578   /* Re-parse DEST's last token.  We know that DEST used to contain
579      at least one token, so if it doesn't contain any after the
580      append, then we must have spliced "/" and "*" or "/" and "/" to
581      make a comment start.  (Just for the record, I got this right
582      the first time.  This is not a bug fix.)  */
583   if (get_token (&new_token, &dest_tail)
584       && (new_token.text + new_token.len
585           == dest->text + original_dest_len))
586     {
587       /* No splice, so we're done.  */
588       dest->last_token = original_dest_len + src->last_token;
589       return;
590     }
591
592   /* Okay, a simple append caused a splice.  Let's chop dest back to
593      its original length and try again, but separate the texts with a
594      space.  */
595   dest->len = original_dest_len;
596   appendc (dest, ' ');
597   appendmem (dest, src->text, src->len);
598
599   init_shared_buffer (&dest_tail,
600                       dest->text + dest->last_token,
601                       dest->len - dest->last_token);
602
603   /* Try to re-parse DEST's last token, as above.  */
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 + 1 + src->last_token;
610       return;
611     }
612
613   /* As far as I know, there's no case where inserting a space isn't
614      enough to prevent a splice.  */
615   internal_error (__FILE__, __LINE__,
616                   _("unable to avoid splicing tokens during macro expansion"));
617 }
618
619
620 \f
621 /* Expanding macros!  */
622
623
624 /* A singly-linked list of the names of the macros we are currently 
625    expanding --- for detecting expansion loops.  */
626 struct macro_name_list {
627   const char *name;
628   struct macro_name_list *next;
629 };
630
631
632 /* Return non-zero if we are currently expanding the macro named NAME,
633    according to LIST; otherwise, return zero.
634
635    You know, it would be possible to get rid of all the NO_LOOP
636    arguments to these functions by simply generating a new lookup
637    function and baton which refuses to find the definition for a
638    particular macro, and otherwise delegates the decision to another
639    function/baton pair.  But that makes the linked list of excluded
640    macros chained through untyped baton pointers, which will make it
641    harder to debug.  :( */
642 static int
643 currently_rescanning (struct macro_name_list *list, const char *name)
644 {
645   for (; list; list = list->next)
646     if (strcmp (name, list->name) == 0)
647       return 1;
648
649   return 0;
650 }
651
652
653 /* Gather the arguments to a macro expansion.
654
655    NAME is the name of the macro being invoked.  (It's only used for
656    printing error messages.)
657
658    Assume that SRC is the text of the macro invocation immediately
659    following the macro name.  For example, if we're processing the
660    text foo(bar, baz), then NAME would be foo and SRC will be (bar,
661    baz).
662
663    If SRC doesn't start with an open paren ( token at all, return
664    zero, leave SRC unchanged, and don't set *ARGC_P to anything.
665
666    If SRC doesn't contain a properly terminated argument list, then
667    raise an error.
668
669    Otherwise, return a pointer to the first element of an array of
670    macro buffers referring to the argument texts, and set *ARGC_P to
671    the number of arguments we found --- the number of elements in the
672    array.  The macro buffers share their text with SRC, and their
673    last_token fields are initialized.  The array is allocated with
674    xmalloc, and the caller is responsible for freeing it.
675
676    NOTE WELL: if SRC starts with a open paren ( token followed
677    immediately by a close paren ) token (e.g., the invocation looks
678    like "foo()"), we treat that as one argument, which happens to be
679    the empty list of tokens.  The caller should keep in mind that such
680    a sequence of tokens is a valid way to invoke one-parameter
681    function-like macros, but also a valid way to invoke zero-parameter
682    function-like macros.  Eeew.
683
684    Consume the tokens from SRC; after this call, SRC contains the text
685    following the invocation.  */
686
687 static struct macro_buffer *
688 gather_arguments (const char *name, struct macro_buffer *src, int *argc_p)
689 {
690   struct macro_buffer tok;
691   int args_len, args_size;
692   struct macro_buffer *args = NULL;
693   struct cleanup *back_to = make_cleanup (free_current_contents, &args);
694
695   /* Does SRC start with an opening paren token?  Read from a copy of
696      SRC, so SRC itself is unaffected if we don't find an opening
697      paren.  */
698   {
699     struct macro_buffer temp;
700     init_shared_buffer (&temp, src->text, src->len);
701
702     if (! get_token (&tok, &temp)
703         || tok.len != 1
704         || tok.text[0] != '(')
705       {
706         discard_cleanups (back_to);
707         return 0;
708       }
709   }
710
711   /* Consume SRC's opening paren.  */
712   get_token (&tok, src);
713
714   args_len = 0;
715   args_size = 6;
716   args = (struct macro_buffer *) xmalloc (sizeof (*args) * args_size);
717
718   for (;;)
719     {
720       struct macro_buffer *arg;
721       int depth;
722
723       /* Make sure we have room for the next argument.  */
724       if (args_len >= args_size)
725         {
726           args_size *= 2;
727           args = xrealloc (args, sizeof (*args) * args_size);
728         }
729
730       /* Initialize the next argument.  */
731       arg = &args[args_len++];
732       set_token (arg, src->text, src->text);
733
734       /* Gather the argument's tokens.  */
735       depth = 0;
736       for (;;)
737         {
738           char *start = src->text;
739
740           if (! get_token (&tok, src))
741             error (_("Malformed argument list for macro `%s'."), name);
742       
743           /* Is tok an opening paren?  */
744           if (tok.len == 1 && tok.text[0] == '(')
745             depth++;
746
747           /* Is tok is a closing paren?  */
748           else if (tok.len == 1 && tok.text[0] == ')')
749             {
750               /* If it's a closing paren at the top level, then that's
751                  the end of the argument list.  */
752               if (depth == 0)
753                 {
754                   discard_cleanups (back_to);
755                   *argc_p = args_len;
756                   return args;
757                 }
758
759               depth--;
760             }
761
762           /* If tok is a comma at top level, then that's the end of
763              the current argument.  */
764           else if (tok.len == 1 && tok.text[0] == ',' && depth == 0)
765             break;
766
767           /* Extend the current argument to enclose this token.  If
768              this is the current argument's first token, leave out any
769              leading whitespace, just for aesthetics.  */
770           if (arg->len == 0)
771             {
772               arg->text = tok.text;
773               arg->len = tok.len;
774               arg->last_token = 0;
775             }
776           else
777             {
778               arg->len = (tok.text + tok.len) - arg->text;
779               arg->last_token = tok.text - arg->text;
780             }
781         }
782     }
783 }
784
785
786 /* The `expand' and `substitute_args' functions both invoke `scan'
787    recursively, so we need a forward declaration somewhere.  */
788 static void scan (struct macro_buffer *dest,
789                   struct macro_buffer *src,
790                   struct macro_name_list *no_loop,
791                   macro_lookup_ftype *lookup_func,
792                   void *lookup_baton);
793
794
795 /* Given the macro definition DEF, being invoked with the actual
796    arguments given by ARGC and ARGV, substitute the arguments into the
797    replacement list, and store the result in DEST.
798
799    If it is necessary to expand macro invocations in one of the
800    arguments, use LOOKUP_FUNC and LOOKUP_BATON to find the macro
801    definitions, and don't expand invocations of the macros listed in
802    NO_LOOP.  */
803 static void
804 substitute_args (struct macro_buffer *dest, 
805                  struct macro_definition *def,
806                  int argc, struct macro_buffer *argv,
807                  struct macro_name_list *no_loop,
808                  macro_lookup_ftype *lookup_func,
809                  void *lookup_baton)
810 {
811   /* A macro buffer for the macro's replacement list.  */
812   struct macro_buffer replacement_list;
813
814   init_shared_buffer (&replacement_list, (char *) def->replacement,
815                       strlen (def->replacement));
816
817   gdb_assert (dest->len == 0);
818   dest->last_token = 0;
819
820   for (;;)
821     {
822       struct macro_buffer tok;
823       char *original_rl_start = replacement_list.text;
824       int substituted = 0;
825       
826       /* Find the next token in the replacement list.  */
827       if (! get_token (&tok, &replacement_list))
828         break;
829
830       /* Just for aesthetics.  If we skipped some whitespace, copy
831          that to DEST.  */
832       if (tok.text > original_rl_start)
833         {
834           appendmem (dest, original_rl_start, tok.text - original_rl_start);
835           dest->last_token = dest->len;
836         }
837
838       /* Is this token the stringification operator?  */
839       if (tok.len == 1
840           && tok.text[0] == '#')
841         error (_("Stringification is not implemented yet."));
842
843       /* Is this token the splicing operator?  */
844       if (tok.len == 2
845           && tok.text[0] == '#'
846           && tok.text[1] == '#')
847         error (_("Token splicing is not implemented yet."));
848
849       /* Is this token an identifier?  */
850       if (tok.is_identifier)
851         {
852           int i;
853
854           /* Is it the magic varargs parameter?  */
855           if (tok.len == 11
856               && ! memcmp (tok.text, "__VA_ARGS__", 11))
857             error (_("Variable-arity macros not implemented yet."));
858
859           /* Is it one of the parameters?  */
860           for (i = 0; i < def->argc; i++)
861             if (tok.len == strlen (def->argv[i])
862                 && ! memcmp (tok.text, def->argv[i], tok.len))
863               {
864                 struct macro_buffer arg_src;
865
866                 /* Expand any macro invocations in the argument text,
867                    and append the result to dest.  Remember that scan
868                    mutates its source, so we need to scan a new buffer
869                    referring to the argument's text, not the argument
870                    itself.  */
871                 init_shared_buffer (&arg_src, argv[i].text, argv[i].len);
872                 scan (dest, &arg_src, no_loop, lookup_func, lookup_baton);
873                 substituted = 1;
874                 break;
875               }
876         }
877
878       /* If it wasn't a parameter, then just copy it across.  */
879       if (! substituted)
880         append_tokens_without_splicing (dest, &tok);
881     }
882 }
883
884
885 /* Expand a call to a macro named ID, whose definition is DEF.  Append
886    its expansion to DEST.  SRC is the input text following the ID
887    token.  We are currently rescanning the expansions of the macros
888    named in NO_LOOP; don't re-expand them.  Use LOOKUP_FUNC and
889    LOOKUP_BATON to find definitions for any nested macro references.  
890
891    Return 1 if we decided to expand it, zero otherwise.  (If it's a
892    function-like macro name that isn't followed by an argument list,
893    we don't expand it.)  If we return zero, leave SRC unchanged.  */
894 static int
895 expand (const char *id,
896         struct macro_definition *def, 
897         struct macro_buffer *dest,
898         struct macro_buffer *src,
899         struct macro_name_list *no_loop,
900         macro_lookup_ftype *lookup_func,
901         void *lookup_baton)
902 {
903   struct macro_name_list new_no_loop;
904
905   /* Create a new node to be added to the front of the no-expand list.
906      This list is appropriate for re-scanning replacement lists, but
907      it is *not* appropriate for scanning macro arguments; invocations
908      of the macro whose arguments we are gathering *do* get expanded
909      there.  */
910   new_no_loop.name = id;
911   new_no_loop.next = no_loop;
912
913   /* What kind of macro are we expanding?  */
914   if (def->kind == macro_object_like)
915     {
916       struct macro_buffer replacement_list;
917
918       init_shared_buffer (&replacement_list, (char *) def->replacement,
919                           strlen (def->replacement));
920
921       scan (dest, &replacement_list, &new_no_loop, lookup_func, lookup_baton);
922       return 1;
923     }
924   else if (def->kind == macro_function_like)
925     {
926       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
927       int argc = 0;
928       struct macro_buffer *argv = NULL;
929       struct macro_buffer substituted;
930       struct macro_buffer substituted_src;
931
932       if (def->argc >= 1
933           && strcmp (def->argv[def->argc - 1], "...") == 0)
934         error (_("Varargs macros not implemented yet."));
935
936       make_cleanup (free_current_contents, &argv);
937       argv = gather_arguments (id, src, &argc);
938
939       /* If we couldn't find any argument list, then we don't expand
940          this macro.  */
941       if (! argv)
942         {
943           do_cleanups (back_to);
944           return 0;
945         }
946
947       /* Check that we're passing an acceptable number of arguments for
948          this macro.  */
949       if (argc != def->argc)
950         {
951           /* Remember that a sequence of tokens like "foo()" is a
952              valid invocation of a macro expecting either zero or one
953              arguments.  */
954           if (! (argc == 1
955                  && argv[0].len == 0
956                  && def->argc == 0))
957             error (_("Wrong number of arguments to macro `%s' "
958                    "(expected %d, got %d)."),
959                    id, def->argc, argc);
960         }
961
962       /* Note that we don't expand macro invocations in the arguments
963          yet --- we let subst_args take care of that.  Parameters that
964          appear as operands of the stringifying operator "#" or the
965          splicing operator "##" don't get macro references expanded,
966          so we can't really tell whether it's appropriate to macro-
967          expand an argument until we see how it's being used.  */
968       init_buffer (&substituted, 0);
969       make_cleanup (cleanup_macro_buffer, &substituted);
970       substitute_args (&substituted, def, argc, argv, no_loop,
971                        lookup_func, lookup_baton);
972
973       /* Now `substituted' is the macro's replacement list, with all
974          argument values substituted into it properly.  Re-scan it for
975          macro references, but don't expand invocations of this macro.
976
977          We create a new buffer, `substituted_src', which points into
978          `substituted', and scan that.  We can't scan `substituted'
979          itself, since the tokenization process moves the buffer's
980          text pointer around, and we still need to be able to find
981          `substituted's original text buffer after scanning it so we
982          can free it.  */
983       init_shared_buffer (&substituted_src, substituted.text, substituted.len);
984       scan (dest, &substituted_src, &new_no_loop, lookup_func, lookup_baton);
985
986       do_cleanups (back_to);
987
988       return 1;
989     }
990   else
991     internal_error (__FILE__, __LINE__, _("bad macro definition kind"));
992 }
993
994
995 /* If the single token in SRC_FIRST followed by the tokens in SRC_REST
996    constitute a macro invokation not forbidden in NO_LOOP, append its
997    expansion to DEST and return non-zero.  Otherwise, return zero, and
998    leave DEST unchanged.
999
1000    SRC_FIRST and SRC_REST must be shared buffers; DEST must not be one.
1001    SRC_FIRST must be a string built by get_token.  */
1002 static int
1003 maybe_expand (struct macro_buffer *dest,
1004               struct macro_buffer *src_first,
1005               struct macro_buffer *src_rest,
1006               struct macro_name_list *no_loop,
1007               macro_lookup_ftype *lookup_func,
1008               void *lookup_baton)
1009 {
1010   gdb_assert (src_first->shared);
1011   gdb_assert (src_rest->shared);
1012   gdb_assert (! dest->shared);
1013
1014   /* Is this token an identifier?  */
1015   if (src_first->is_identifier)
1016     {
1017       /* Make a null-terminated copy of it, since that's what our
1018          lookup function expects.  */
1019       char *id = xmalloc (src_first->len + 1);
1020       struct cleanup *back_to = make_cleanup (xfree, id);
1021       memcpy (id, src_first->text, src_first->len);
1022       id[src_first->len] = 0;
1023           
1024       /* If we're currently re-scanning the result of expanding
1025          this macro, don't expand it again.  */
1026       if (! currently_rescanning (no_loop, id))
1027         {
1028           /* Does this identifier have a macro definition in scope?  */
1029           struct macro_definition *def = lookup_func (id, lookup_baton);
1030
1031           if (def && expand (id, def, dest, src_rest, no_loop,
1032                              lookup_func, lookup_baton))
1033             {
1034               do_cleanups (back_to);
1035               return 1;
1036             }
1037         }
1038
1039       do_cleanups (back_to);
1040     }
1041
1042   return 0;
1043 }
1044
1045
1046 /* Expand macro references in SRC, appending the results to DEST.
1047    Assume we are re-scanning the result of expanding the macros named
1048    in NO_LOOP, and don't try to re-expand references to them.
1049
1050    SRC must be a shared buffer; DEST must not be one.  */
1051 static void
1052 scan (struct macro_buffer *dest,
1053       struct macro_buffer *src,
1054       struct macro_name_list *no_loop,
1055       macro_lookup_ftype *lookup_func,
1056       void *lookup_baton)
1057 {
1058   gdb_assert (src->shared);
1059   gdb_assert (! dest->shared);
1060
1061   for (;;)
1062     {
1063       struct macro_buffer tok;
1064       char *original_src_start = src->text;
1065
1066       /* Find the next token in SRC.  */
1067       if (! get_token (&tok, src))
1068         break;
1069
1070       /* Just for aesthetics.  If we skipped some whitespace, copy
1071          that to DEST.  */
1072       if (tok.text > original_src_start)
1073         {
1074           appendmem (dest, original_src_start, tok.text - original_src_start);
1075           dest->last_token = dest->len;
1076         }
1077
1078       if (! maybe_expand (dest, &tok, src, no_loop, lookup_func, lookup_baton))
1079         /* We didn't end up expanding tok as a macro reference, so
1080            simply append it to dest.  */
1081         append_tokens_without_splicing (dest, &tok);
1082     }
1083
1084   /* Just for aesthetics.  If there was any trailing whitespace in
1085      src, copy it to dest.  */
1086   if (src->len)
1087     {
1088       appendmem (dest, src->text, src->len);
1089       dest->last_token = dest->len;
1090     }
1091 }
1092
1093
1094 char *
1095 macro_expand (const char *source,
1096               macro_lookup_ftype *lookup_func,
1097               void *lookup_func_baton)
1098 {
1099   struct macro_buffer src, dest;
1100   struct cleanup *back_to;
1101
1102   init_shared_buffer (&src, (char *) source, strlen (source));
1103
1104   init_buffer (&dest, 0);
1105   dest.last_token = 0;
1106   back_to = make_cleanup (cleanup_macro_buffer, &dest);
1107
1108   scan (&dest, &src, 0, lookup_func, lookup_func_baton);
1109
1110   appendc (&dest, '\0');
1111
1112   discard_cleanups (back_to);
1113   return dest.text;
1114 }
1115
1116
1117 char *
1118 macro_expand_once (const char *source,
1119                    macro_lookup_ftype *lookup_func,
1120                    void *lookup_func_baton)
1121 {
1122   error (_("Expand-once not implemented yet."));
1123 }
1124
1125
1126 char *
1127 macro_expand_next (char **lexptr,
1128                    macro_lookup_ftype *lookup_func,
1129                    void *lookup_baton)
1130 {
1131   struct macro_buffer src, dest, tok;
1132   struct cleanup *back_to;
1133
1134   /* Set up SRC to refer to the input text, pointed to by *lexptr.  */
1135   init_shared_buffer (&src, *lexptr, strlen (*lexptr));
1136
1137   /* Set up DEST to receive the expansion, if there is one.  */
1138   init_buffer (&dest, 0);
1139   dest.last_token = 0;
1140   back_to = make_cleanup (cleanup_macro_buffer, &dest);
1141
1142   /* Get the text's first preprocessing token.  */
1143   if (! get_token (&tok, &src))
1144     {
1145       do_cleanups (back_to);
1146       return 0;
1147     }
1148
1149   /* If it's a macro invocation, expand it.  */
1150   if (maybe_expand (&dest, &tok, &src, 0, lookup_func, lookup_baton))
1151     {
1152       /* It was a macro invocation!  Package up the expansion as a
1153          null-terminated string and return it.  Set *lexptr to the
1154          start of the next token in the input.  */
1155       appendc (&dest, '\0');
1156       discard_cleanups (back_to);
1157       *lexptr = src.text;
1158       return dest.text;
1159     }
1160   else
1161     {
1162       /* It wasn't a macro invocation.  */
1163       do_cleanups (back_to);
1164       return 0;
1165     }
1166 }