OSDN Git Service

Move directive handling into the lexer itself.
[pf3gnuchains/gcc-fork.git] / gcc / cppmacro.c
1 /* Part of CPP library.  (Macro and #define handling.)
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3    1999, 2000 Free Software Foundation, Inc.
4    Written by Per Bothner, 1994.
5    Based on CCCP program by Paul Rubin, June 1986
6    Adapted to ANSI C, Richard Stallman, Jan 1987
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21
22  In other words, you are welcome to use, share and improve this program.
23  You are forbidden to forbid anyone else to use, share and improve
24  what you give them.   Help stamp out software-hoarding!  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "intl.h"               /* for _("<command line>") below.  */
29 #include "cpplib.h"
30 #include "cpphash.h"
31
32 #ifndef STDC_0_IN_SYSTEM_HEADERS
33 #define STDC_0_IN_SYSTEM_HEADERS 0 /* Boolean macro.  */
34 #endif
35
36 struct cpp_macro
37 {
38   cpp_hashnode **params;        /* Parameters, if any.  */
39   cpp_token *expansion;         /* First token of replacement list.   */
40   const char *file;             /* Defined in file name.  */
41   unsigned int line;            /* Starting line number.  */
42   unsigned int count;           /* Number of tokens in expansion.  */
43   unsigned short paramc;        /* Number of parameters.  */
44   unsigned int fun_like : 1;    /* If a function-like macro.  */
45   unsigned int var_args : 1;    /* If a variable-args macro.  */
46   unsigned int disabled : 1;    /* If macro is disabled.  */
47 };
48
49 typedef struct macro_arg macro_arg;
50 struct macro_arg
51 {
52   cpp_token *first;             /* First token in unexpanded argument.  */
53   cpp_token *expanded;          /* Macro-expanded argument.   */
54   cpp_token *stringified;       /* Stringified argument.  */
55   unsigned int count;           /* # of tokens in argument.  */
56   unsigned int expanded_count;  /* # of tokens in expanded argument.  */
57 };
58
59 /* Macro expansion.  */
60
61 static void lock_pools PARAMS ((cpp_reader *));
62 static void unlock_pools PARAMS ((cpp_reader *));
63 static int enter_macro_context PARAMS ((cpp_reader *, cpp_token *));
64 static void builtin_macro PARAMS ((cpp_reader *, cpp_token *));
65 static cpp_context *push_arg_context PARAMS ((cpp_reader *, macro_arg *));
66 static enum cpp_ttype parse_arg PARAMS ((cpp_reader *, macro_arg *, int));
67 static macro_arg *parse_args PARAMS ((cpp_reader *, const cpp_hashnode *));
68 static cpp_context *next_context PARAMS ((cpp_reader *));
69 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
70 static unsigned char *quote_string PARAMS ((unsigned char *,
71                                             const unsigned char *,
72                                             unsigned int));
73 static void make_string_token PARAMS ((cpp_pool *, cpp_token *,
74                                        const U_CHAR *, unsigned int));
75 static void make_number_token PARAMS ((cpp_reader *, cpp_token *, int));
76 static void stringify_arg PARAMS ((cpp_reader *, macro_arg *));
77 static void paste_all_tokens PARAMS ((cpp_reader *, cpp_token *));
78 static void paste_payloads PARAMS ((cpp_reader *, cpp_token *,
79                                     const cpp_token *));
80 static int funlike_invocation_p PARAMS ((cpp_reader *, const cpp_hashnode *,
81                                           struct toklist *));
82 static void replace_args PARAMS ((cpp_reader *, cpp_macro *, macro_arg *,
83                                   struct toklist *));
84
85 /* Lookaheads.  */
86
87 static void save_lookahead_token PARAMS ((cpp_reader *, const cpp_token *));
88 static void take_lookahead_token PARAMS ((cpp_reader *, cpp_token *));
89 static void release_lookahead PARAMS ((cpp_reader *));
90 static cpp_lookahead *alloc_lookahead PARAMS ((cpp_reader *));
91 static void free_lookahead PARAMS ((cpp_lookahead *));
92
93 /* #define directive parsing and handling.  */
94
95 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
96 static int check_macro_redefinition PARAMS ((cpp_reader *,
97                                              const cpp_hashnode *,
98                                              const cpp_macro *));
99 static int save_parameter PARAMS ((cpp_reader *, cpp_macro *, cpp_hashnode *));
100 static int parse_params PARAMS ((cpp_reader *, cpp_macro *));
101 static void check_trad_stringification PARAMS ((cpp_reader *,
102                                                 const cpp_macro *,
103                                                 const cpp_string *));
104
105 /* Allocates a buffer to hold a token's TEXT, and converts TOKEN to a
106    CPP_STRING token containing TEXT in quoted form.  */
107 static void
108 make_string_token (pool, token, text, len)
109      cpp_pool *pool;
110      cpp_token *token;
111      const U_CHAR *text;
112      unsigned int len;
113 {
114   U_CHAR *buf = _cpp_pool_alloc (pool, len * 4);
115
116   token->type = CPP_STRING;
117   token->val.str.text = buf;
118   token->val.str.len = quote_string (buf, text, len) - buf;
119   token->flags = 0;
120 }
121
122 /* Allocates and converts a temporary token to a CPP_NUMBER token,
123    evaluating to NUMBER.  */
124 static void
125 make_number_token (pfile, token, number)
126      cpp_reader *pfile;
127      cpp_token *token;
128      int number;
129 {
130   unsigned char *buf = _cpp_pool_alloc (pfile->string_pool, 20);
131
132   sprintf ((char *) buf, "%d", number);
133   token->type = CPP_NUMBER;
134   token->val.str.text = buf;
135   token->val.str.len = ustrlen (buf);
136   token->flags = 0;
137 }
138
139 static const char * const monthnames[] =
140 {
141   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
142   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
143 };
144
145 /* Handle builtin macros like __FILE__.  */
146 static void
147 builtin_macro (pfile, token)
148      cpp_reader *pfile;
149      cpp_token *token;
150 {
151   unsigned char flags = token->flags & PREV_WHITE;
152   cpp_hashnode *node = token->val.node;
153   cpp_buffer *ip;
154
155   switch (node->value.builtin)
156     {
157     case BT_FILE:
158     case BT_BASE_FILE:
159       {
160         const char *file;
161
162         ip = CPP_BUFFER (pfile);
163         if (ip == 0)
164           file = "";
165         else
166           {
167             if (node->value.builtin == BT_BASE_FILE)
168               while (CPP_PREV_BUFFER (ip) != NULL)
169                 ip = CPP_PREV_BUFFER (ip);
170
171             file = ip->nominal_fname;
172           }
173         make_string_token (pfile->string_pool, token,
174                            (U_CHAR *) file, strlen (file));
175       }
176       break;
177         
178     case BT_INCLUDE_LEVEL:
179       /* pfile->include_depth counts the primary source as level 1,
180          but historically __INCLUDE_DEPTH__ has called the primary
181          source level 0.  */
182       make_number_token (pfile, token, pfile->include_depth - 1);
183       break;
184
185     case BT_SPECLINE:
186       /* If __LINE__ is embedded in a macro, it must expand to the
187          line of the macro's invocation, not its definition.
188          Otherwise things like assert() will not work properly.  */
189       make_number_token (pfile, token, cpp_get_line (pfile)->line);
190       break;
191
192     case BT_STDC:
193       {
194         int stdc = 1;
195
196         if (STDC_0_IN_SYSTEM_HEADERS && CPP_IN_SYSTEM_HEADER (pfile)
197             && pfile->spec_nodes.n__STRICT_ANSI__->type == NT_VOID)
198           stdc = 0;
199         make_number_token (pfile, token, stdc);
200       }
201       break;
202
203     case BT_DATE:
204     case BT_TIME:
205       if (pfile->date.type == CPP_EOF)
206         {
207           /* Allocate __DATE__ and __TIME__ from permanent storage,
208              and save them in pfile so we don't have to do this again.
209              We don't generate these strings at init time because
210              time() and localtime() are very slow on some systems.  */
211           time_t tt = time (NULL);
212           struct tm *tb = localtime (&tt);
213
214           make_string_token (&pfile->ident_pool, &pfile->date,
215                              DSC("Oct 11 1347"));
216           make_string_token (&pfile->ident_pool, &pfile->time,
217                              DSC("12:34:56"));
218
219           sprintf ((char *) pfile->date.val.str.text, "%s %2d %4d",
220                    monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
221           sprintf ((char *) pfile->time.val.str.text, "%02d:%02d:%02d",
222                    tb->tm_hour, tb->tm_min, tb->tm_sec);
223         }
224       *token = node->value.builtin == BT_DATE ? pfile->date: pfile->time;
225       break;
226
227     default:
228       cpp_ice (pfile, "invalid builtin macro \"%s\"", node->name);
229       break;
230     }
231
232   token->flags = flags;
233 }
234
235 /* Used by cpperror.c to obtain the correct line and column to report
236    in a diagnostic.  */
237 const cpp_lexer_pos *
238 cpp_get_line (pfile)
239      cpp_reader *pfile;
240 {
241   /* Within a macro expansion, return the position of the outermost
242      invocation.  */
243   if (pfile->context->prev)
244     return &pfile->macro_pos;
245   return &pfile->lexer_pos;
246 }
247
248 static void
249 lock_pools (pfile)
250      cpp_reader *pfile;
251 {
252   _cpp_lock_pool (&pfile->temp_string_pool);
253   _cpp_lock_pool (&pfile->argument_pool);
254 }
255
256 static void
257 unlock_pools (pfile)
258      cpp_reader *pfile;
259 {
260   _cpp_unlock_pool (&pfile->temp_string_pool);
261   _cpp_unlock_pool (&pfile->argument_pool);
262 }
263
264 static void
265 paste_payloads (pfile, lhs, rhs)
266      cpp_reader *pfile;
267      cpp_token *lhs;
268      const cpp_token *rhs;
269 {
270   unsigned int total_len = cpp_token_len (lhs) + cpp_token_len (rhs);
271   unsigned char *result, *end;
272   cpp_pool *pool;
273
274   pool = lhs->type == CPP_NAME ? &pfile->ident_pool: pfile->string_pool;
275   result = _cpp_pool_alloc (pool, total_len + 1);
276
277   /* Paste the spellings and null terminate.  */
278   end = cpp_spell_token (pfile, rhs, cpp_spell_token (pfile, lhs, result));
279   *end = '\0';
280   total_len = end - result;
281
282   if (lhs->type == CPP_NAME)
283     {
284       lhs->val.node = cpp_lookup (pfile, result, total_len);
285       if (lhs->val.node->flags & NODE_OPERATOR)
286         {
287           lhs->flags |= NAMED_OP;
288           lhs->type = lhs->val.node->value.operator;
289         }
290     }
291   else
292     {
293       lhs->val.str.text = result;
294       lhs->val.str.len = total_len;
295     }
296 }
297
298 /* Adds backslashes before all backslashes and double quotes appearing
299    in strings.  Non-printable characters are converted to octal.  */
300 static U_CHAR *
301 quote_string (dest, src, len)
302      U_CHAR *dest;
303      const U_CHAR *src;
304      unsigned int len;
305 {
306   while (len--)
307     {
308       U_CHAR c = *src++;
309
310       if (c == '\\' || c == '"')
311         {
312           *dest++ = '\\';
313           *dest++ = c;
314         }
315       else
316         {
317           if (ISPRINT (c))
318             *dest++ = c;
319           else
320             {
321               sprintf ((char *) dest, "\\%03o", c);
322               dest += 4;
323             }
324         }
325     }
326
327   return dest;
328 }
329
330 /* Convert a token sequence to a single string token according to the
331    rules of the ISO C #-operator.  */
332 static void
333 stringify_arg (pfile, arg)
334      cpp_reader *pfile;
335      macro_arg *arg;
336 {
337   cpp_pool *pool = pfile->string_pool;
338   unsigned char *start = POOL_FRONT (pool);
339   unsigned int i, escape_it, total_len = 0, backslash_count = 0;
340   unsigned int prev_white = 0;
341
342   /* Loop, reading in the argument's tokens.  */
343   for (i = 0; i < arg->count; i++)
344     {
345       unsigned char *dest;
346       const cpp_token *token = &arg->first[i];
347       unsigned int len = cpp_token_len (token);
348
349       escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
350                    || token->type == CPP_CHAR || token->type == CPP_WCHAR
351                    || token->type == CPP_OSTRING);
352
353       if (escape_it)
354         /* Worst case is each char is octal.  */
355         len *= 4;
356       len++;                    /* Room for initial space.  */
357
358       dest = &start[total_len];
359       if (dest + len > POOL_LIMIT (pool))
360         {
361           _cpp_next_chunk (pool, len, (unsigned char **) &start);
362           dest = &start[total_len];
363         }
364
365       prev_white |= token->flags & PREV_WHITE;
366       if (token->type == CPP_PLACEMARKER)
367         continue;
368
369       /* No leading white space.  */
370       if (prev_white)
371         {
372           prev_white = 0;
373           if (total_len > 0)
374             *dest++ = ' ';
375         }
376
377       if (escape_it)
378         {
379           unsigned char *buf = (unsigned char *) xmalloc (len);
380
381           len = cpp_spell_token (pfile, token, buf) - buf;
382           dest = quote_string (dest, buf, len);
383           free (buf);
384         }
385       else
386         dest = cpp_spell_token (pfile, token, dest);
387       total_len = dest - start;
388
389       if (token->type == CPP_OTHER && token->val.c == '\\')
390         backslash_count++;
391       else
392         backslash_count = 0;
393     }
394
395   /* Ignore the final \ of invalid string literals.  */
396   if (backslash_count & 1)
397     {
398       cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
399       total_len--;
400     }
401
402   POOL_COMMIT (pool, total_len);
403
404   arg->stringified = xnew (cpp_token);
405   arg->stringified->flags = 0;
406   arg->stringified->type = CPP_STRING;
407   arg->stringified->val.str.text = start;
408   arg->stringified->val.str.len = total_len;
409 }
410
411 /* Handles an arbitrarily long sequence of ## operators.  This
412    implementation is left-associative, non-recursive, and finishes a
413    paste before handling succeeding ones.  If the paste fails, the
414    right hand side of the ## operator is placed in the then-current
415    context's lookahead buffer, with the effect that it appears in the
416    output stream normally.  */
417 static void
418 paste_all_tokens (pfile, lhs)
419      cpp_reader *pfile;
420      cpp_token *lhs;
421 {
422   unsigned char orig_flags = lhs->flags;
423   cpp_token *rhs;
424
425   do
426     {
427       /* Take the token directly from the current context.  We can do
428          this, because we are in the replacement list of either an
429          object-like macro, or a function-like macro with arguments
430          inserted.  In either case, the constraints to #define
431          guarantee we have at least one more token (empty arguments
432          become placemarkers).  */
433       rhs = pfile->context->list.first++;
434
435       if (rhs->type == CPP_PLACEMARKER)
436         {
437           /* GCC has special extended semantics for , ## b where b is
438              a varargs parameter: the comma disappears if b was given
439              no actual arguments (not merely if b is an empty
440              argument).  */
441           if (lhs->type == CPP_COMMA && (rhs->flags & VARARGS_FIRST))
442             lhs->type = CPP_PLACEMARKER;
443         }
444       else if (lhs->type == CPP_PLACEMARKER)
445         *lhs = *rhs;
446       else
447         {
448           int digraph = 0;
449           enum cpp_ttype type = cpp_can_paste (pfile, lhs, rhs, &digraph);
450
451           if (type == CPP_EOF)
452             {
453               /* Do nothing special about , ## <whatever> if
454                  <whatever> came from a variable argument, because the
455                  author probably intended the ## to trigger the
456                  special extended semantics (see above).  */
457               if (lhs->type == CPP_COMMA && (rhs->flags & VARARGS_FIRST))
458                 /* nothing */;
459               else
460                 {
461                   if (CPP_OPTION (pfile, warn_paste))
462                     cpp_warning (pfile,
463                  "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
464                                  cpp_token_as_text (pfile, lhs),
465                                  cpp_token_as_text (pfile, rhs));
466
467                   /* The standard states that behaviour is undefined.
468                      By the principle of least surpise, we step back
469                      before the RHS, and mark it to prevent macro
470                      expansion.  Tests in the testsuite rely on
471                      clearing PREV_WHITE here, though you could argue
472                      we should actually set it.  */
473                   rhs->flags &= ~PREV_WHITE;
474                   rhs->flags |= NO_EXPAND;
475                 }
476
477               /* Step back so we read the RHS in next.  */
478               pfile->context->list.first--;
479               break;
480             }
481
482           lhs->type = type;
483           lhs->flags &= ~DIGRAPH;
484           if (digraph)
485             lhs->flags |= DIGRAPH;
486
487           if (type == CPP_NAME || type == CPP_NUMBER)
488             paste_payloads (pfile, lhs, rhs);
489           else if (type == CPP_WCHAR || type == CPP_WSTRING)
490             lhs->val.str = rhs->val.str;
491         }
492     }
493   while (rhs->flags & PASTE_LEFT);
494
495   /* The pasted token has the PREV_WHITE flag of the LHS, is no longer
496      PASTE_LEFT, and is subject to macro expansion.  */
497   lhs->flags &= ~(PREV_WHITE | PASTE_LEFT | NO_EXPAND);
498   lhs->flags |= orig_flags & PREV_WHITE;
499 }
500
501 /* Reads the unexpanded tokens of a macro argument into ARG.  Empty
502    arguments are saved as a single CPP_PLACEMARKER token.  VAR_ARGS is
503    non-zero if this is a variable argument.  Returns the type of the
504    token that caused reading to finish.  */
505 static enum cpp_ttype
506 parse_arg (pfile, arg, var_args)
507      cpp_reader *pfile;
508      struct macro_arg *arg;
509      int var_args;
510 {
511   enum cpp_ttype result;
512   unsigned int paren = 0;
513
514   arg->first = (cpp_token *) POOL_FRONT (&pfile->argument_pool);
515   for (;; arg->count++)
516     {
517       cpp_token *token = &arg->first[arg->count];
518       if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->argument_pool))
519         {
520           _cpp_next_chunk (&pfile->argument_pool, sizeof (cpp_token),
521                            (unsigned char **) &arg->first);
522           token = &arg->first[arg->count];
523         }
524
525       _cpp_get_token (pfile, token);
526       result = token->type;
527
528       if (result == CPP_OPEN_PAREN)
529         paren++;
530       else if (result == CPP_CLOSE_PAREN && paren-- == 0)
531         break;
532       /* Commas are not terminators within parantheses or var_args.  */
533       else if (result == CPP_COMMA && paren == 0 && !var_args)
534         break;
535       else if (result == CPP_EOF)
536         break;          /* Error reported by caller.  */
537     }
538
539   /* Empty arguments become a single placemarker token.  */
540   if (arg->count == 0)
541     {
542       arg->first->type = CPP_PLACEMARKER;
543       arg->count = 1;
544     }
545
546   /* Commit the memory used to store the arguments.  */
547   POOL_COMMIT (&pfile->argument_pool, arg->count * sizeof (cpp_token));
548
549   return result;
550 }
551
552 /* Parse the arguments making up a macro invocation.  */
553 static macro_arg *
554 parse_args (pfile, node)
555      cpp_reader *pfile;
556      const cpp_hashnode *node;
557 {
558   cpp_macro *macro = node->value.macro;
559   macro_arg *args, *cur;
560   enum cpp_ttype type;
561   int argc, error = 0;
562
563   /* Allocate room for at least one argument, and zero it out.  */
564   argc = macro->paramc ? macro->paramc: 1;
565   args = xcnewvec (macro_arg, argc);
566
567   for (cur = args, argc = 0; ;)
568     {
569       argc++;
570
571       type = parse_arg (pfile, cur, argc == macro->paramc && macro->var_args);
572       if (type == CPP_CLOSE_PAREN || type == CPP_EOF)
573         break;
574
575       /* Re-use the last argument for excess arguments.  */
576       if (argc < macro->paramc)
577         cur++;
578     }
579
580   if (type == CPP_EOF)
581     {
582       cpp_error (pfile, "unterminated argument list invoking macro \"%s\"",
583                  node->name);
584       error = 1;
585     }
586   else if (argc < macro->paramc)
587     {
588       /* As an extension, a rest argument is allowed to not appear in
589          the invocation at all.
590          e.g. #define debug(format, args...) something
591          debug("string");
592          
593          This is exactly the same as if there had been an empty rest
594          argument - debug("string", ).  */
595
596       if (argc + 1 == macro->paramc && macro->var_args)
597         {
598           /* parse_arg ensured there was space for the closing
599              parenthesis.  Use this space to store a placemarker.  */
600           args[argc].first = (cpp_token *) POOL_FRONT (&pfile->argument_pool);
601           args[argc].first->type = CPP_PLACEMARKER;
602           args[argc].count = 1;
603           POOL_COMMIT (&pfile->argument_pool, sizeof (cpp_token));
604
605           if (CPP_OPTION (pfile, c99) && CPP_PEDANTIC (pfile))
606             cpp_pedwarn (pfile, "ISO C99 requires rest arguments to be used");
607         }
608       else
609         {
610           cpp_error (pfile,
611                      "macro \"%s\" requires %u arguments, but only %u given",
612                      node->name, macro->paramc, argc);
613           error = 1;
614         }
615     }
616   else if (argc > macro->paramc)
617     {
618       /* An empty argument to an empty function-like macro is fine.  */
619       if (argc != 1 || args[0].first->type != CPP_PLACEMARKER)
620         {
621           cpp_error (pfile,
622                      "macro \"%s\" passed %u arguments, but takes just %u",
623                      node->name, argc, macro->paramc);
624           error = 1;
625         }
626     }
627
628   if (error)
629     {
630       free (args);
631       args = 0;
632     }
633
634   return args;
635 }
636
637 static int
638 funlike_invocation_p (pfile, node, list)
639      cpp_reader *pfile;
640      const cpp_hashnode *node;
641      struct toklist *list;
642 {
643   cpp_context *orig_context;
644   cpp_token maybe_paren;
645   macro_arg *args = 0;
646
647   pfile->state.parsing_args = 1;
648   pfile->state.prevent_expansion++;
649   orig_context = pfile->context;
650
651   cpp_start_lookahead (pfile);
652   cpp_get_token (pfile, &maybe_paren);
653   cpp_stop_lookahead (pfile, maybe_paren.type == CPP_OPEN_PAREN);
654
655   if (maybe_paren.type == CPP_OPEN_PAREN)
656     args = parse_args (pfile, node);
657   else if (CPP_WTRADITIONAL (pfile))
658     cpp_warning (pfile,
659          "function-like macro \"%s\" must be used with arguments in traditional C",
660                  node->name);
661
662   /* Restore original context.  */
663   pfile->context = orig_context;
664   pfile->state.prevent_expansion--;
665   pfile->state.parsing_args = 0;
666
667   if (args)
668     {
669       if (node->value.macro->paramc > 0)
670         replace_args (pfile, node->value.macro, args, list);
671       free (args);
672     }
673
674   return args != 0;
675 }
676
677 /* Push the context of a macro onto the context stack.  TOKEN is the
678    macro name.  If we can successfully start expanding the macro,
679    TOKEN is replaced with the first token of the expansion, and we
680    return non-zero.  */
681 static int
682 enter_macro_context (pfile, token)
683      cpp_reader *pfile;
684      cpp_token *token;
685 {
686   cpp_context *context;
687   cpp_macro *macro;
688   unsigned char flags;
689   struct toklist list;
690
691   macro = token->val.node->value.macro;
692   if (macro->disabled)
693     {
694       token->flags |= NO_EXPAND;
695       return 0;
696     }
697
698   /* Save the position of the outermost macro invocation.  */
699   if (!pfile->context->prev)
700     {
701       pfile->macro_pos = pfile->lexer_pos;
702       lock_pools (pfile);
703     }
704
705   if (macro->fun_like && !funlike_invocation_p (pfile, token->val.node, &list))
706     {
707       if (!pfile->context->prev)
708         unlock_pools (pfile);
709       return 0;
710     }
711
712   /* Now push its context.  */
713   context = next_context (pfile);
714   if (macro->paramc == 0)
715     {
716       context->list.first = macro->expansion;
717       context->list.limit = macro->expansion + macro->count;
718     }
719   else
720     context->list = list;
721   context->macro = macro;
722
723   /* The first expansion token inherits the PREV_WHITE of TOKEN.  */
724   flags = token->flags & PREV_WHITE;
725   *token = *context->list.first++;
726   token->flags |= flags;
727
728   /* Disable the macro within its expansion.  */
729   macro->disabled = 1;
730
731   return 1;
732 }
733
734 /* Move to the next context.  Create one if there is none.  */
735 static cpp_context *
736 next_context (pfile)
737      cpp_reader *pfile;
738 {
739   cpp_context *prev = pfile->context;
740   cpp_context *result = prev->next;
741
742   if (result == 0)
743     {
744       result = xnew (cpp_context);
745       prev->next = result;
746       result->prev = prev;
747       result->next = 0;
748     }
749
750   pfile->context = result;
751   return result;
752 }
753
754 static void
755 replace_args (pfile, macro, args, list)
756      cpp_reader *pfile;
757      cpp_macro *macro;
758      macro_arg *args;
759      struct toklist *list;
760 {
761   unsigned int i, total;
762   const cpp_token *src, *limit;
763   cpp_token *dest;
764   macro_arg *arg;
765
766   src = macro->expansion;
767   limit = src + macro->count;
768
769   /* First, fully macro-expand arguments, calculating the number of
770      tokens in the final expansion as we go.  This ensures that the
771      possible recursive use of argument_pool is fine.  */
772   total = limit - src;
773   for (; src < limit; src++)
774     if (src->type == CPP_MACRO_ARG)
775       {
776         /* We have an argument.  If it is not being stringified or
777            pasted it is macro-replaced before insertion.  */
778         arg = &args[src->val.arg_no - 1];
779         if (src->flags & STRINGIFY_ARG)
780           {
781             if (!arg->stringified)
782               stringify_arg (pfile, arg);
783           }
784         else if ((src->flags & PASTE_LEFT)
785                  || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
786           total += arg->count - 1;
787         else
788           {
789             if (!arg->expanded)
790               expand_arg (pfile, arg);
791             total += arg->expanded_count - 1;
792           }
793       }
794
795   dest = (cpp_token *) _cpp_pool_alloc (&pfile->argument_pool,
796                                         total * sizeof (cpp_token));
797   list->first = dest;
798   list->limit = list->first + total;
799
800   for (src = macro->expansion; src < limit; src++)
801     if (src->type == CPP_MACRO_ARG)
802       {
803         unsigned int count;
804         const cpp_token *from;
805
806         arg = &args[src->val.arg_no - 1];
807         if (src->flags & STRINGIFY_ARG)
808           from = arg->stringified, count = 1;
809         else if ((src->flags & PASTE_LEFT)
810                  || (src > macro->expansion && (src[-1].flags & PASTE_LEFT)))
811           count = arg->count, from = arg->first;
812         else
813           count = arg->expanded_count, from = arg->expanded;
814         memcpy (dest, from, count * sizeof (cpp_token));
815
816         /* The first token gets PREV_WHITE of the CPP_MACRO_ARG.  If
817            it is a variable argument, it is also flagged.  */
818         dest->flags &= ~PREV_WHITE;
819         dest->flags |= src->flags & PREV_WHITE;
820         if (macro->var_args && src->val.arg_no == macro->paramc)
821           dest->flags |= VARARGS_FIRST;
822
823         /* The last token gets the PASTE_LEFT of the CPP_MACRO_ARG.  */
824         dest[count - 1].flags |= src->flags & PASTE_LEFT;
825
826         dest += count;
827       }
828     else
829       *dest++ = *src;
830
831   /* Free the expanded arguments.  */
832   for (i = 0; i < macro->paramc; i++)
833     {
834       if (args[i].expanded)
835         free (args[i].expanded);
836       if (args[i].stringified)
837         free (args[i].stringified);
838     }
839 }
840
841 /* Subroutine of expand_arg to put the unexpanded tokens on the
842    context stack.  */
843 static cpp_context *
844 push_arg_context (pfile, arg)
845      cpp_reader *pfile;
846      macro_arg *arg;
847 {
848   cpp_context *context = next_context (pfile);
849   context->macro = 0;
850   context->list.first = arg->first;
851   context->list.limit = arg->first + arg->count;
852
853   return context;
854 }
855
856 static void
857 expand_arg (pfile, arg)
858      cpp_reader *pfile;
859      macro_arg *arg;
860 {
861   cpp_token *token;
862   unsigned int capacity = 256;
863
864   /* Loop, reading in the arguments.  */
865   arg->expanded = (cpp_token *) xmalloc (capacity * sizeof (cpp_token));
866   arg->expanded_count = 0;
867
868   push_arg_context (pfile, arg);
869   do
870     {
871       if (arg->expanded_count >= capacity)
872         {
873           capacity *= 2;
874           arg->expanded = (cpp_token *)
875             xrealloc (arg->expanded, capacity * sizeof (cpp_token));
876         }
877       token = &arg->expanded[arg->expanded_count++];
878       _cpp_get_token (pfile, token);
879     }
880   while (token->type != CPP_EOF);
881
882   arg->expanded_count--;
883
884   /* Pop the context we pushed.  */ 
885   pfile->context = pfile->context->prev;
886 }
887
888 void
889 _cpp_pop_context (pfile)
890      cpp_reader *pfile;
891 {
892   cpp_context *context = pfile->context;
893
894   pfile->context = context->prev;
895   /* Re-enable a macro and free resources when leaving its expansion.  */
896   if (!pfile->state.parsing_args)
897     {
898       if (!pfile->context->prev)
899         unlock_pools (pfile);
900       context->macro->disabled = 0;
901     }
902 }
903
904 /* Internal routine to return a token, either from an in-progress
905    macro expansion, or from the source file as appropriate.  Handles
906    macros, so tokens returned are post-expansion.  Does not filter
907    CPP_PLACEMARKER tokens.  Returns CPP_EOF at EOL and EOF.  */
908 void
909 _cpp_get_token (pfile, token)
910      cpp_reader *pfile;
911      cpp_token *token;
912 {
913  next_token:
914   for (;;)
915     {
916       cpp_context *context = pfile->context;
917
918       if (pfile->la_read)
919         take_lookahead_token (pfile, token);
920       /* Context->prev == 0 <=> base context.  */
921       else if (!context->prev)
922         _cpp_lex_token (pfile, token);
923       else if (context->list.first != context->list.limit)
924         *token = *context->list.first++;
925       else
926         {
927           if (context->macro)
928             {
929               _cpp_pop_context (pfile);
930               continue;
931             }
932           token->type = CPP_EOF;
933           token->flags = 0;
934         }
935       break;
936     }
937
938   /* Only perform macro expansion (and therefore pasting) when not
939      skipping, or when skipping but in a directive.  The only
940      directive where this could be true is #elif.  A possible later
941      optimisation: get do_elif to clear skipping so we don't need the
942      directive test here.  */
943   if (pfile->skipping && !pfile->state.in_directive)
944     return;
945
946   for (;;)
947     {
948       if (token->flags & PASTE_LEFT)
949         paste_all_tokens (pfile, token);
950
951       if (token->type != CPP_NAME)
952         break;
953
954       /* Handle macros and the _Pragma operator.  */
955       if (token->val.node->type == NT_MACRO
956           && !pfile->state.prevent_expansion
957           && !(token->flags & NO_EXPAND))
958         {
959           /* Macros invalidate controlling macros.  */
960           pfile->mi_state = MI_FAILED;
961
962           if (token->val.node->flags & NODE_BUILTIN)
963             {
964               builtin_macro (pfile, token);
965               break;
966             }
967
968           if (enter_macro_context (pfile, token))
969             continue;
970         }
971
972       if (token->val.node != pfile->spec_nodes.n__Pragma)
973         break;
974
975       /* Invalidate controlling macros.  */
976       pfile->mi_state = MI_FAILED;
977       _cpp_do__Pragma (pfile);
978       goto next_token;
979     }
980 }
981
982 /* External interface to get a token.  Tokens are returned after macro
983    expansion and directives have been handled, as a continuous stream.
984    Transparently enters included files.  CPP_EOF indicates end of
985    original source file.  Filters out CPP_PLACEMARKER tokens.
986
987    For the benefit of #pragma callbacks which may want to get the
988    pragma's tokens, returns CPP_EOF to indicate end-of-directive in
989    this case.  */
990 void
991 cpp_get_token (pfile, token)
992      cpp_reader *pfile;
993      cpp_token *token;
994 {
995   for (;;)
996     {
997       _cpp_get_token (pfile, token);
998
999       if (token->type == CPP_EOF)
1000         {
1001           /* In directives we should pass through EOLs for the callbacks.  */
1002           if (pfile->buffer->cur == pfile->buffer->rlimit
1003               || pfile->state.in_directive || pfile->state.parsing_args)
1004             break;
1005           continue;
1006         }
1007       /* We are not merging the PREV_WHITE of CPP_PLACEMARKERS.  I
1008          don't think it really matters.  */
1009       else if (pfile->skipping || token->type == CPP_PLACEMARKER)
1010         continue;
1011
1012       /* Non-comment tokens invalidate any controlling macros.  */
1013       if (token->type != CPP_COMMENT)
1014         pfile->mi_state = MI_FAILED;
1015
1016       break;
1017     }
1018
1019   if (pfile->la_write)
1020     save_lookahead_token (pfile, token);
1021 }
1022
1023 /* Read each token in, until EOF.  Directives are transparently
1024    processed.  */
1025 void
1026 cpp_scan_buffer_nooutput (pfile)
1027      cpp_reader *pfile;
1028 {
1029   cpp_token token;
1030
1031   do
1032     do
1033       cpp_get_token (pfile, &token);
1034     while (token.type != CPP_EOF);
1035   while (cpp_pop_buffer (pfile) != 0);
1036 }
1037
1038 /* Lookahead handling.  */
1039
1040 static void
1041 save_lookahead_token (pfile, token)
1042      cpp_reader *pfile;
1043      const cpp_token *token;
1044 {
1045   if (token->type != CPP_EOF)
1046     {
1047       cpp_lookahead *la = pfile->la_write;
1048       cpp_token_with_pos *twp;
1049
1050       if (la->count == la->cap)
1051         {
1052           la->cap += la->cap + 8;
1053           la->tokens = (cpp_token_with_pos *)
1054             xrealloc (la->tokens, la->cap * sizeof (cpp_token_with_pos));
1055         }
1056
1057       twp = &la->tokens[la->count++];
1058       twp->token = *token;
1059       twp->pos = *cpp_get_line (pfile);
1060     }
1061 }
1062
1063 static void
1064 take_lookahead_token (pfile, token)
1065      cpp_reader *pfile;
1066      cpp_token *token;
1067 {
1068   cpp_lookahead *la = pfile->la_read;
1069   cpp_token_with_pos *twp = &la->tokens[la->cur];
1070
1071   *token = twp->token;
1072   pfile->lexer_pos = twp->pos;
1073
1074   if (++la->cur == la->count)
1075     release_lookahead (pfile);
1076 }
1077
1078 /* Moves the lookahead at the front of the read list to the free store.  */
1079 static void
1080 release_lookahead (pfile)
1081      cpp_reader *pfile;
1082 {
1083   cpp_lookahead *la = pfile->la_read;
1084
1085   pfile->la_read = la->next;
1086   la->next = pfile->la_unused;
1087   pfile->la_unused = la;
1088   unlock_pools (pfile);
1089 }
1090
1091 /* Take a new lookahead from the free store, or allocate one if none.  */
1092 static cpp_lookahead *
1093 alloc_lookahead (pfile)
1094      cpp_reader *pfile;
1095 {
1096   cpp_lookahead *la = pfile->la_unused;
1097
1098   if (la)
1099     pfile->la_unused = la->next;
1100   else
1101     {
1102       la = xnew (cpp_lookahead);
1103       la->tokens = 0;
1104       la->cap = 0;
1105     }
1106
1107   la->cur = la->count = 0;
1108   return la;
1109 }
1110
1111 /* Free memory associated with a lookahead list.  */
1112 static void
1113 free_lookahead (la)
1114      cpp_lookahead *la;
1115 {
1116   if (la->tokens)
1117     free ((PTR) la->tokens);
1118   free ((PTR) la);
1119 }
1120
1121 /* Free all the lookaheads of a cpp_reader.  */
1122 void
1123 _cpp_free_lookaheads (pfile)
1124      cpp_reader *pfile;
1125 {
1126   cpp_lookahead *la, *lan;
1127
1128   if (pfile->la_read)
1129     free_lookahead (pfile->la_read);
1130   if (pfile->la_write)
1131     free_lookahead (pfile->la_write);
1132
1133   for (la = pfile->la_unused; la; la = lan)
1134     {
1135       lan = la->next;
1136       free_lookahead (la);
1137     }
1138 }
1139
1140 /* Allocate a lookahead and move it to the front of the write list.  */
1141 void
1142 cpp_start_lookahead (pfile)
1143      cpp_reader *pfile;
1144 {
1145   cpp_lookahead *la = alloc_lookahead (pfile);
1146
1147   la->next = pfile->la_write;
1148   pfile->la_write = la;
1149
1150   la->pos = *cpp_get_line (pfile);
1151
1152   /* Don't allow memory pools to be re-used whilst we're reading ahead.  */
1153   lock_pools (pfile);
1154 }
1155
1156 /* Stop reading ahead - either step back, or drop the read ahead.  */
1157 void
1158 cpp_stop_lookahead (pfile, drop)
1159      cpp_reader *pfile;
1160      int drop;
1161 {
1162   cpp_lookahead *la = pfile->la_write;
1163
1164   pfile->la_write = la->next;
1165   la->next = pfile->la_read;
1166   pfile->la_read = la;
1167
1168   if (drop || la->count == 0)
1169     release_lookahead (pfile);
1170   else
1171     pfile->lexer_pos = la->pos;
1172 }
1173
1174 /* Push a single token back to the front of the queue.  Only to be
1175    used by cpplib, and only then when necessary.  POS is the position
1176    to report for the preceding token.  */
1177 void
1178 _cpp_push_token (pfile, token, pos)
1179      cpp_reader *pfile;
1180      const cpp_token *token;
1181      const cpp_lexer_pos *pos;
1182 {
1183   cpp_start_lookahead (pfile);
1184   save_lookahead_token (pfile, token);
1185   cpp_stop_lookahead (pfile, 0);
1186   pfile->lexer_pos = *pos;
1187 }
1188
1189 /* #define directive parsing and handling.  */
1190
1191 /* Returns non-zero if a macro redefinition is trivial.  */
1192 static int
1193 check_macro_redefinition (pfile, node, macro2)
1194      cpp_reader *pfile;
1195      const cpp_hashnode *node;
1196      const cpp_macro *macro2;
1197 {
1198   const cpp_macro *macro1;
1199   unsigned int i;
1200
1201   if (node->type != NT_MACRO || node->flags & NODE_BUILTIN)
1202     return ! pfile->done_initializing;
1203
1204   macro1 = node->value.macro;
1205
1206   /* The quick failures.  */
1207   if (macro1->count != macro2->count
1208       || macro1->paramc != macro2->paramc
1209       || macro1->fun_like != macro2->fun_like
1210       || macro1->var_args != macro2->var_args)
1211     return 0;
1212
1213   /* Check each token.  */
1214   for (i = 0; i < macro1->count; i++)
1215     if (! _cpp_equiv_tokens (&macro1->expansion[i], &macro2->expansion[i]))
1216       return 0;
1217
1218   /* Check parameter spellings.  */
1219   for (i = 0; i < macro1->paramc; i++)
1220     if (macro1->params[i] != macro2->params[i])
1221       return 0;
1222
1223   return 1;
1224 }
1225
1226 /* Free the definition of hashnode H.  */
1227
1228 void
1229 _cpp_free_definition (h)
1230      cpp_hashnode *h;
1231 {
1232   /* Macros and assertions no longer have anything to free.  */
1233   h->type = NT_VOID;
1234   /* Clear builtin flag in case of redefinition.  */
1235   h->flags &= ~NODE_BUILTIN;
1236 }
1237
1238 static int
1239 save_parameter (pfile, macro, node)
1240      cpp_reader *pfile;
1241      cpp_macro *macro;
1242      cpp_hashnode *node;
1243 {
1244   cpp_hashnode **dest;
1245
1246   /* Constraint 6.10.3.6 - duplicate parameter names.  */
1247   if (node->arg_index)
1248     {
1249       cpp_error (pfile, "duplicate macro parameter \"%s\"", node->name);
1250       return 1;
1251     }
1252
1253   dest = &macro->params[macro->paramc];
1254
1255   /* Check we have room for the parameters.  */
1256   if ((unsigned char *) (dest + 1) >= POOL_LIMIT (&pfile->macro_pool))
1257     {
1258       _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_hashnode *),
1259                        (unsigned char **) &macro->params);
1260       dest = &macro->params[macro->paramc];
1261     }
1262
1263   *dest = node;
1264   node->arg_index = ++macro->paramc;
1265   return 0;
1266 }
1267
1268 static int
1269 parse_params (pfile, macro)
1270      cpp_reader *pfile;
1271      cpp_macro *macro;
1272 {
1273   cpp_token token;
1274   unsigned int prev_ident = 0;
1275
1276   macro->params = (cpp_hashnode **) POOL_FRONT (&pfile->macro_pool);
1277   for (;;)
1278     {
1279       _cpp_lex_token (pfile, &token);
1280
1281       switch (token.type)
1282         {
1283         default:
1284           cpp_error (pfile, "\"%s\" may not appear in macro parameter list",
1285                      cpp_token_as_text (pfile, &token));
1286           return 0;
1287
1288         case CPP_NAME:
1289           if (prev_ident)
1290             {
1291               cpp_error (pfile, "macro parameters must be comma-separated");
1292               return 0;
1293             }
1294           prev_ident = 1;
1295
1296           if (save_parameter (pfile, macro, token.val.node))
1297             return 0;
1298           continue;
1299
1300         case CPP_CLOSE_PAREN:
1301           if (prev_ident || macro->paramc == 0)
1302             break;
1303
1304           /* Fall through to pick up the error.  */
1305         case CPP_COMMA:
1306           if (!prev_ident)
1307             {
1308               cpp_error (pfile, "parameter name missing");
1309               return 0;
1310             }
1311           prev_ident = 0;
1312           continue;
1313
1314         case CPP_ELLIPSIS:
1315           macro->var_args = 1;
1316           if (!prev_ident)
1317             {
1318               save_parameter (pfile, macro, pfile->spec_nodes.n__VA_ARGS__);
1319               pfile->state.va_args_ok = 1;
1320               if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1321                 cpp_pedwarn (pfile,
1322                      "C89 does not permit anonymous variable arguments");
1323             }
1324           else if (CPP_OPTION (pfile, pedantic))
1325             cpp_pedwarn (pfile,
1326                          "ISO C does not permit named variable arguments");
1327
1328           /* We're at the end, and just expect a closing parenthesis.  */
1329           _cpp_lex_token (pfile, &token);
1330           if (token.type == CPP_CLOSE_PAREN)
1331             break;
1332           /* Fall through.  */
1333
1334         case CPP_EOF:
1335           cpp_error (pfile, "missing ')' in macro parameter list");
1336           return 0;
1337         }
1338
1339       /* Success.  Commit the parameter array.  */
1340       POOL_COMMIT (&pfile->macro_pool,
1341                    macro->paramc * sizeof (cpp_hashnode *));
1342       return 1;
1343     }
1344 }
1345
1346 /* Lex a token from a macro's replacement list.  Translate it to a
1347    CPP_MACRO_ARG if appropriate.  */
1348 static cpp_token *
1349 lex_expansion_token (pfile, macro)
1350      cpp_reader *pfile;
1351      cpp_macro *macro;
1352 {
1353   cpp_token *token = &macro->expansion[macro->count];
1354
1355   /* Check we have room for the token.  */
1356   if ((unsigned char *) (token + 1) >= POOL_LIMIT (&pfile->macro_pool))
1357     {
1358       _cpp_next_chunk (&pfile->macro_pool, sizeof (cpp_token),
1359                        (unsigned char **) &macro->expansion);
1360       token = &macro->expansion[macro->count];
1361     }
1362
1363   macro->count++;
1364   _cpp_lex_token (pfile, token);
1365
1366   /* Is this an argument?  */
1367   if (token->type == CPP_NAME && token->val.node->arg_index)
1368     {
1369       token->type = CPP_MACRO_ARG;
1370       token->val.arg_no = token->val.node->arg_index;
1371     }
1372   else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1373            && (token->type == CPP_STRING || token->type == CPP_CHAR))
1374     check_trad_stringification (pfile, macro, &token->val.str);
1375
1376   return token;
1377 }
1378
1379 /* Parse a macro and save its expansion.  Returns non-zero on success.  */
1380 int
1381 _cpp_create_definition (pfile, node)
1382      cpp_reader *pfile;
1383      cpp_hashnode *node;
1384 {
1385   cpp_macro *macro;
1386   cpp_token *token;
1387   unsigned int i, ok = 1;
1388
1389   macro = (cpp_macro *) _cpp_pool_alloc (&pfile->macro_pool,
1390                                          sizeof (cpp_macro));
1391   macro->file = pfile->buffer->nominal_fname;
1392   macro->line = pfile->directive_pos.line;
1393   macro->params = 0;
1394   macro->paramc = 0;
1395   macro->fun_like = 0;
1396   macro->var_args = 0;
1397   macro->count = 0;
1398   macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1399
1400   /* Get the first token of the expansion (or the '(' of a
1401      function-like macro).  */
1402   token = lex_expansion_token (pfile, macro);
1403   if (token->type == CPP_OPEN_PAREN && !(token->flags & PREV_WHITE))
1404     {
1405       if (!(ok = parse_params (pfile, macro)))
1406         goto cleanup;
1407       macro->count = 0;
1408       macro->fun_like = 1;
1409       /* Some of the pool may have been used for the parameter store.  */
1410       macro->expansion = (cpp_token *) POOL_FRONT (&pfile->macro_pool);
1411       token = lex_expansion_token (pfile, macro);
1412     }
1413   else if (token->type != CPP_EOF && !(token->flags & PREV_WHITE))
1414     cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
1415
1416   /* Setting it here means we don't catch leading comments.  */
1417   pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
1418
1419   for (;;)
1420     {
1421       /* Check the stringifying # constraint 6.10.3.2.1 of
1422          function-like macros when lexing the subsequent token.  */
1423       if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1424         {
1425           if (token->type == CPP_MACRO_ARG)
1426             {
1427               token->flags &= ~PREV_WHITE;
1428               token->flags |= STRINGIFY_ARG;
1429               token->flags |= token[-1].flags & PREV_WHITE;
1430               token[-1] = token[0];
1431               macro->count--;
1432             }
1433           /* Let assembler get away with murder.  */
1434           else if (!CPP_OPTION (pfile, lang_asm))
1435             {
1436               ok = 0;
1437               cpp_error (pfile, "'#' is not followed by a macro parameter");
1438               goto cleanup;
1439             }
1440         }
1441
1442       if (token->type == CPP_EOF)
1443         break;
1444
1445       /* Paste operator constraint 6.10.3.3.1.  */
1446       if (token->type == CPP_PASTE)
1447         {
1448           /* Token-paste ##, can appear in both object-like and
1449              function-like macros, but not at the ends.  */
1450           if (--macro->count > 0)
1451             token = lex_expansion_token (pfile, macro);
1452
1453           if (macro->count == 0 || token->type == CPP_EOF)
1454             {
1455               ok = 0;
1456               cpp_error (pfile,
1457                          "'##' cannot appear at either end of a macro expansion");
1458               goto cleanup;
1459             }
1460
1461           token[-1].flags |= PASTE_LEFT;
1462           /* Give it a PREV_WHITE for -dM etc.  */
1463           token->flags |= PREV_WHITE;
1464         }
1465
1466       token = lex_expansion_token (pfile, macro);
1467     }
1468
1469   /* Don't count the CPP_EOF.  Empty macros become a place marker.  */
1470   if (macro->count > 1)
1471     macro->count--;
1472   else
1473     macro->expansion[0].type = CPP_PLACEMARKER;
1474
1475   /* Clear the whitespace flag from the leading token.  */
1476   macro->expansion[0].flags &= ~PREV_WHITE;
1477
1478   /* Implement the macro-defined-to-itself optimisation.  */
1479   macro->disabled = (macro->count == 1 && !macro->fun_like
1480                      && macro->expansion[0].type == CPP_NAME
1481                      && macro->expansion[0].val.node == node);
1482
1483   /* Commit the memory.  */
1484   POOL_COMMIT (&pfile->macro_pool, macro->count * sizeof (cpp_token));
1485
1486   /* Redefinition of a macro is allowed if and only if the old and new
1487      definitions are the same.  (6.10.3 paragraph 2). */
1488   if (node->type != NT_VOID)
1489     {
1490       if (CPP_PEDANTIC (pfile)
1491           && !check_macro_redefinition (pfile, node, macro))
1492         {
1493           cpp_pedwarn_with_line (pfile, pfile->directive_pos.line,
1494                                  pfile->directive_pos.col,
1495                                  "\"%s\" redefined", node->name);
1496
1497           if (pfile->done_initializing && node->type == NT_MACRO
1498               && !(node->flags & NODE_BUILTIN))
1499             cpp_pedwarn_with_file_and_line (pfile,
1500                                             node->value.macro->file,
1501                                             node->value.macro->line, 1,
1502                             "this is the location of the previous definition");
1503         }
1504       _cpp_free_definition (node);
1505     }
1506
1507   /* Enter definition in hash table.  */
1508   node->type = NT_MACRO;
1509   node->value.macro = macro;
1510
1511  cleanup:
1512
1513   /* Stop the lexer accepting __VA_ARGS__.  */
1514   pfile->state.va_args_ok = 0;
1515
1516   /* Clear the fast argument lookup indices.  */
1517   for (i = macro->paramc; i-- > 0; )
1518     macro->params[i]->arg_index = 0;
1519
1520   return ok;
1521 }
1522
1523 /* Warn if a token in `string' matches one of the function macro
1524    arguments in `info'.  This function assumes that the macro is a
1525    function macro and not an object macro.  */
1526 static void
1527 check_trad_stringification (pfile, macro, string)
1528      cpp_reader *pfile;
1529      const cpp_macro *macro;
1530      const cpp_string *string;
1531 {
1532   unsigned int i, len;
1533   const U_CHAR *p, *q, *limit = string->text + string->len;
1534   
1535   /* Loop over the string.  */
1536   for (p = string->text; p < limit; p = q)
1537     {
1538       /* Find the start of an identifier.  */
1539       while (p < limit && !is_idstart (*p))
1540         p++;
1541
1542       /* Find the end of the identifier.  */
1543       q = p;
1544       while (q < limit && is_idchar (*q))
1545         q++;
1546
1547       len = q - p;
1548
1549       /* Loop over the function macro arguments to see if the
1550          identifier inside the string matches one of them.  */
1551       for (i = 0; i < macro->paramc; i++)
1552         {
1553           const cpp_hashnode *node = macro->params[i];
1554
1555           if (node->length == len && !memcmp (p, node->name, len))
1556             {
1557               cpp_warning (pfile,
1558            "macro argument \"%s\" would be stringified with -traditional.",
1559                            node->name);
1560               break;
1561             }
1562         }
1563     }
1564 }
1565
1566 /* Returns the expansion of a macro, in a format suitable to be read
1567    back in again, and therefore also for DWARF 2 debugging info.
1568    Caller is expected to generate the "#define NAME" bit.  The
1569    returned text is temporary, and automatically freed later.  */
1570
1571 const unsigned char *
1572 cpp_macro_definition (pfile, node)
1573      cpp_reader *pfile;
1574      const cpp_hashnode *node;
1575 {
1576   unsigned int i, len;
1577   const cpp_macro *macro = node->value.macro;
1578   unsigned char *buffer;
1579
1580   if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1581     {
1582       cpp_ice (pfile, "invalid hash type %d in dump_definition", node->type);
1583       return 0;
1584     }
1585
1586   /* Calculate length.  */
1587   len = 1;                      /* ' ' */
1588   if (macro->fun_like)
1589     {
1590       len += 3;         /* "()" plus possible final "." of ellipsis.  */
1591       for (i = 0; i < macro->paramc; i++)
1592         len += macro->params[i]->length + 2; /* ", " */
1593     }
1594
1595   if (macro->count > 1 || macro->expansion[0].type != CPP_PLACEMARKER)
1596     {
1597       for (i = 0; i < macro->count; i++)
1598         {
1599           cpp_token *token = &macro->expansion[i];
1600
1601           if (token->type == CPP_MACRO_ARG)
1602             len += macro->params[token->val.arg_no - 1]->length;
1603           else
1604             len += cpp_token_len (token); /* Includes room for ' '.  */
1605           if (token->flags & STRINGIFY_ARG)
1606             len++;                      /* "#" */
1607           if (token->flags & PASTE_LEFT)
1608             len += 3;           /* " ##" */
1609         }
1610     }
1611
1612   if (len > pfile->macro_buffer_len)
1613     pfile->macro_buffer = (U_CHAR *) xrealloc (pfile->macro_buffer, len);
1614   buffer = pfile->macro_buffer;
1615
1616   /* Parameter names.  */
1617   if (macro->fun_like)
1618     {
1619       *buffer++ = '(';
1620       for (i = 0; i < macro->paramc; i++)
1621         {
1622           cpp_hashnode *param = macro->params[i];
1623
1624           if (param != pfile->spec_nodes.n__VA_ARGS__)
1625             {
1626               memcpy (buffer, param->name, param->length);
1627               buffer += param->length;
1628             }
1629
1630           if (i + 1 < macro->paramc)
1631             *buffer++ = ',', *buffer++ = ' ';
1632           else if (macro->var_args)
1633             *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1634         }
1635       *buffer++ = ')';
1636     }
1637
1638   /* Expansion tokens.  */
1639   if (macro->count > 1 || macro->expansion[0].type != CPP_PLACEMARKER)
1640     {
1641       *buffer++ = ' ';
1642       for (i = 0; i < macro->count; i++)
1643         {
1644           cpp_token *token = &macro->expansion[i];
1645
1646           if (token->flags & PREV_WHITE)
1647             *buffer++ = ' ';
1648           if (token->flags & STRINGIFY_ARG)
1649             *buffer++ = '#';
1650
1651           if (token->type == CPP_MACRO_ARG)
1652             {
1653               len = macro->params[token->val.arg_no - 1]->length;
1654               memcpy (buffer, macro->params[token->val.arg_no - 1]->name, len);
1655               buffer += len;
1656             }
1657           else
1658             buffer = cpp_spell_token (pfile, token, buffer);
1659
1660           if (token->flags & PASTE_LEFT)
1661             {
1662               *buffer++ = ' ';
1663               *buffer++ = '#';
1664               *buffer++ = '#';
1665               /* Next has PREV_WHITE; see _cpp_create_definition.  */
1666             }
1667         }
1668     }
1669
1670   *buffer = '\0';
1671   return pfile->macro_buffer;
1672 }