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