xref: /openbsd/gnu/usr.bin/gcc/gcc/cppmacro.c (revision 4cfece93)
1 /* Part of CPP library.  (Macro and #define handling.)
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3    1999, 2000, 2001, 2002 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 "cpplib.h"
29 #include "cpphash.h"
30 
31 typedef struct macro_arg macro_arg;
32 struct macro_arg
33 {
34   const cpp_token **first;	/* First token in unexpanded argument.  */
35   const cpp_token **expanded;	/* Macro-expanded argument.  */
36   const cpp_token *stringified;	/* Stringified argument.  */
37   unsigned int count;		/* # of tokens in argument.  */
38   unsigned int expanded_count;	/* # of tokens in expanded argument.  */
39 };
40 
41 /* Macro expansion.  */
42 
43 static int enter_macro_context PARAMS ((cpp_reader *, cpp_hashnode *));
44 static int builtin_macro PARAMS ((cpp_reader *, cpp_hashnode *));
45 static void push_token_context
46   PARAMS ((cpp_reader *, cpp_hashnode *, const cpp_token *, unsigned int));
47 static void push_ptoken_context
48   PARAMS ((cpp_reader *, cpp_hashnode *, _cpp_buff *,
49 	   const cpp_token **, unsigned int));
50 static _cpp_buff *collect_args PARAMS ((cpp_reader *, const cpp_hashnode *));
51 static cpp_context *next_context PARAMS ((cpp_reader *));
52 static const cpp_token *padding_token
53   PARAMS ((cpp_reader *, const cpp_token *));
54 static void expand_arg PARAMS ((cpp_reader *, macro_arg *));
55 static const cpp_token *new_string_token PARAMS ((cpp_reader *, uchar *,
56 						  unsigned int));
57 static const cpp_token *stringify_arg PARAMS ((cpp_reader *, macro_arg *));
58 static void paste_all_tokens PARAMS ((cpp_reader *, const cpp_token *));
59 static bool paste_tokens PARAMS ((cpp_reader *, const cpp_token **,
60 				  const cpp_token *));
61 static void replace_args PARAMS ((cpp_reader *, cpp_hashnode *, cpp_macro *,
62 				  macro_arg *));
63 static _cpp_buff *funlike_invocation_p PARAMS ((cpp_reader *, cpp_hashnode *));
64 static bool create_iso_definition PARAMS ((cpp_reader *, cpp_macro *));
65 
66 /* #define directive parsing and handling.  */
67 
68 static cpp_token *alloc_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
69 static cpp_token *lex_expansion_token PARAMS ((cpp_reader *, cpp_macro *));
70 static bool warn_of_redefinition PARAMS ((cpp_reader *, const cpp_hashnode *,
71 					  const cpp_macro *));
72 static bool parse_params PARAMS ((cpp_reader *, cpp_macro *));
73 static void check_trad_stringification PARAMS ((cpp_reader *,
74 						const cpp_macro *,
75 						const cpp_string *));
76 
77 /* Emits a warning if NODE is a macro defined in the main file that
78    has not been used.  */
79 int
80 _cpp_warn_if_unused_macro (pfile, node, v)
81      cpp_reader *pfile;
82      cpp_hashnode *node;
83      void *v ATTRIBUTE_UNUSED;
84 {
85   if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
86     {
87       cpp_macro *macro = node->value.macro;
88 
89       if (!macro->used
90 	  /* Skip front-end built-ins and command line macros.  */
91 	  && macro->line >= pfile->first_unused_line
92 	  && MAIN_FILE_P (lookup_line (&pfile->line_maps, macro->line)))
93 	cpp_error_with_line (pfile, DL_WARNING, macro->line, 0,
94 			     "macro \"%s\" is not used", NODE_NAME (node));
95     }
96 
97   return 1;
98 }
99 
100 /* Allocates and returns a CPP_STRING token, containing TEXT of length
101    LEN, after null-terminating it.  TEXT must be in permanent storage.  */
102 static const cpp_token *
103 new_string_token (pfile, text, len)
104      cpp_reader *pfile;
105      unsigned char *text;
106      unsigned int len;
107 {
108   cpp_token *token = _cpp_temp_token (pfile);
109 
110   text[len] = '\0';
111   token->type = CPP_STRING;
112   token->val.str.len = len;
113   token->val.str.text = text;
114   token->flags = 0;
115   return token;
116 }
117 
118 static const char * const monthnames[] =
119 {
120   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
121   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
122 };
123 
124 /* Handle builtin macros like __FILE__, and push the resulting token
125    on the context stack.  Also handles _Pragma, for which no new token
126    is created.  Returns 1 if it generates a new token context, 0 to
127    return the token to the caller.  */
128 const uchar *
129 _cpp_builtin_macro_text (pfile, node)
130      cpp_reader *pfile;
131      cpp_hashnode *node;
132 {
133   const uchar *result = NULL;
134   unsigned int number = 1;
135 
136   switch (node->value.builtin)
137     {
138     default:
139       cpp_error (pfile, DL_ICE, "invalid built-in macro \"%s\"",
140 		 NODE_NAME (node));
141       break;
142 
143     case BT_FILE:
144     case BT_BASE_FILE:
145       {
146 	unsigned int len;
147 	const char *name;
148 	uchar *buf;
149 	const struct line_map *map = pfile->map;
150 
151 	if (node->value.builtin == BT_BASE_FILE)
152 	  while (! MAIN_FILE_P (map))
153 	    map = INCLUDED_FROM (&pfile->line_maps, map);
154 
155 	name = map->to_file;
156 	len = strlen (name);
157 	buf = _cpp_unaligned_alloc (pfile, len * 4 + 3);
158 	result = buf;
159 	*buf = '"';
160 	buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
161 	*buf++ = '"';
162 	*buf = '\0';
163       }
164       break;
165 
166     case BT_INCLUDE_LEVEL:
167       /* The line map depth counts the primary source as level 1, but
168 	 historically __INCLUDE_DEPTH__ has called the primary source
169 	 level 0.  */
170       number = pfile->line_maps.depth - 1;
171       break;
172 
173     case BT_SPECLINE:
174       /* If __LINE__ is embedded in a macro, it must expand to the
175 	 line of the macro's invocation, not its definition.
176 	 Otherwise things like assert() will not work properly.  */
177       if (CPP_OPTION (pfile, traditional))
178 	number = pfile->line;
179       else
180 	number = pfile->cur_token[-1].line;
181       number = SOURCE_LINE (pfile->map, number);
182       break;
183 
184       /* __STDC__ has the value 1 under normal circumstances.
185 	 However, if (a) we are in a system header, (b) the option
186 	 stdc_0_in_system_headers is true (set by target config), and
187 	 (c) we are not in strictly conforming mode, then it has the
188 	 value 0.  */
189     case BT_STDC:
190       {
191 	if (CPP_IN_SYSTEM_HEADER (pfile)
192 	    && CPP_OPTION (pfile, stdc_0_in_system_headers)
193 	    && !CPP_OPTION (pfile,std))
194 	  number = 0;
195 	else
196 	  number = 1;
197       }
198       break;
199 
200     case BT_DATE:
201     case BT_TIME:
202       if (pfile->date == NULL)
203 	{
204 	  /* Allocate __DATE__ and __TIME__ strings from permanent
205 	     storage.  We only do this once, and don't generate them
206 	     at init time, because time() and localtime() are very
207 	     slow on some systems.  */
208 	  time_t tt;
209 	  struct tm *tb = NULL;
210 
211 	  /* (time_t) -1 is a legitimate value for "number of seconds
212 	     since the Epoch", so we have to do a little dance to
213 	     distinguish that from a genuine error.  */
214 	  errno = 0;
215 	  tt = time(NULL);
216 	  if (tt != (time_t)-1 || errno == 0)
217 	    tb = localtime (&tt);
218 
219 	  if (tb)
220 	    {
221 	      pfile->date = _cpp_unaligned_alloc (pfile,
222 						  sizeof ("\"Oct 11 1347\""));
223 	      sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
224 		       monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
225 
226 	      pfile->time = _cpp_unaligned_alloc (pfile,
227 						  sizeof ("\"12:34:56\""));
228 	      sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
229 		       tb->tm_hour, tb->tm_min, tb->tm_sec);
230 	    }
231 	  else
232 	    {
233 	      cpp_errno (pfile, DL_WARNING,
234 			 "could not determine date and time");
235 
236 	      pfile->date = U"\"??? ?? ????\"";
237 	      pfile->time = U"\"??:??:??\"";
238 	    }
239 	}
240 
241       if (node->value.builtin == BT_DATE)
242 	result = pfile->date;
243       else
244 	result = pfile->time;
245       break;
246     }
247 
248   if (result == NULL)
249     {
250       /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers.  */
251       result = _cpp_unaligned_alloc (pfile, 21);
252       sprintf ((char *) result, "%u", number);
253     }
254 
255   return result;
256 }
257 
258 /* Convert builtin macros like __FILE__ to a token and push it on the
259    context stack.  Also handles _Pragma, for which no new token is
260    created.  Returns 1 if it generates a new token context, 0 to
261    return the token to the caller.  */
262 static int
263 builtin_macro (pfile, node)
264      cpp_reader *pfile;
265      cpp_hashnode *node;
266 {
267   const uchar *buf;
268 
269   if (node->value.builtin == BT_PRAGMA)
270     {
271       /* Don't interpret _Pragma within directives.  The standard is
272          not clear on this, but to me this makes most sense.  */
273       if (pfile->state.in_directive)
274 	return 0;
275 
276       _cpp_do__Pragma (pfile);
277       return 1;
278     }
279 
280   buf = _cpp_builtin_macro_text (pfile, node);
281 
282   cpp_push_buffer (pfile, buf, ustrlen (buf), /* from_stage3 */ true, 1);
283 
284   /* Tweak the column number the lexer will report.  */
285   pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
286 
287   /* We don't want a leading # to be interpreted as a directive.  */
288   pfile->buffer->saved_flags = 0;
289 
290   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
291   pfile->cur_token = _cpp_temp_token (pfile);
292   push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
293   if (pfile->buffer->cur != pfile->buffer->rlimit)
294     cpp_error (pfile, DL_ICE, "invalid built-in macro \"%s\"",
295 	       NODE_NAME (node));
296   _cpp_pop_buffer (pfile);
297 
298   return 1;
299 }
300 
301 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
302    backslashes and double quotes.  Non-printable characters are
303    converted to octal.  DEST must be of sufficient size.  Returns
304    a pointer to the end of the string.  */
305 uchar *
306 cpp_quote_string (dest, src, len)
307      uchar *dest;
308      const uchar *src;
309      unsigned int len;
310 {
311   while (len--)
312     {
313       uchar c = *src++;
314 
315       if (c == '\\' || c == '"')
316 	{
317 	  *dest++ = '\\';
318 	  *dest++ = c;
319 	}
320       else
321 	{
322 	  if (ISPRINT (c))
323 	    *dest++ = c;
324 	  else
325 	    {
326 	      sprintf ((char *) dest, "\\%03o", c);
327 	      dest += 4;
328 	    }
329 	}
330     }
331 
332   return dest;
333 }
334 
335 /* Convert a token sequence ARG to a single string token according to
336    the rules of the ISO C #-operator.  */
337 static const cpp_token *
338 stringify_arg (pfile, arg)
339      cpp_reader *pfile;
340      macro_arg *arg;
341 {
342   unsigned char *dest = BUFF_FRONT (pfile->u_buff);
343   unsigned int i, escape_it, backslash_count = 0;
344   const cpp_token *source = NULL;
345   size_t len;
346 
347   /* Loop, reading in the argument's tokens.  */
348   for (i = 0; i < arg->count; i++)
349     {
350       const cpp_token *token = arg->first[i];
351 
352       if (token->type == CPP_PADDING)
353 	{
354 	  if (source == NULL)
355 	    source = token->val.source;
356 	  continue;
357 	}
358 
359       escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
360 		   || token->type == CPP_CHAR || token->type == CPP_WCHAR);
361 
362       /* Room for each char being written in octal, initial space and
363 	 final NUL.  */
364       len = cpp_token_len (token);
365       if (escape_it)
366 	len *= 4;
367       len += 2;
368 
369       if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
370 	{
371 	  size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
372 	  _cpp_extend_buff (pfile, &pfile->u_buff, len);
373 	  dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
374 	}
375 
376       /* Leading white space?  */
377       if (dest != BUFF_FRONT (pfile->u_buff))
378 	{
379 	  if (source == NULL)
380 	    source = token;
381 	  if (source->flags & PREV_WHITE)
382 	    *dest++ = ' ';
383 	}
384       source = NULL;
385 
386       if (escape_it)
387 	{
388 	  _cpp_buff *buff = _cpp_get_buff (pfile, len);
389 	  unsigned char *buf = BUFF_FRONT (buff);
390 	  len = cpp_spell_token (pfile, token, buf) - buf;
391 	  dest = cpp_quote_string (dest, buf, len);
392 	  _cpp_release_buff (pfile, buff);
393 	}
394       else
395 	dest = cpp_spell_token (pfile, token, dest);
396 
397       if (token->type == CPP_OTHER && token->val.c == '\\')
398 	backslash_count++;
399       else
400 	backslash_count = 0;
401     }
402 
403   /* Ignore the final \ of invalid string literals.  */
404   if (backslash_count & 1)
405     {
406       cpp_error (pfile, DL_WARNING,
407 		 "invalid string literal, ignoring final '\\'");
408       dest--;
409     }
410 
411   /* Commit the memory, including NUL, and return the token.  */
412   if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < 1)
413     {
414       size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
415       _cpp_extend_buff (pfile, &pfile->u_buff, 1);
416       dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
417     }
418   len = dest - BUFF_FRONT (pfile->u_buff);
419   BUFF_FRONT (pfile->u_buff) = dest + 1;
420   return new_string_token (pfile, dest - len, len);
421 }
422 
423 /* Try to paste two tokens.  On success, return nonzero.  In any
424    case, PLHS is updated to point to the pasted token, which is
425    guaranteed to not have the PASTE_LEFT flag set.  */
426 static bool
427 paste_tokens (pfile, plhs, rhs)
428      cpp_reader *pfile;
429      const cpp_token **plhs, *rhs;
430 {
431   unsigned char *buf, *end;
432   const cpp_token *lhs;
433   unsigned int len;
434   bool valid;
435 
436   lhs = *plhs;
437   len = cpp_token_len (lhs) + cpp_token_len (rhs) + 1;
438   buf = (unsigned char *) alloca (len);
439   end = cpp_spell_token (pfile, lhs, buf);
440 
441   /* Avoid comment headers, since they are still processed in stage 3.
442      It is simpler to insert a space here, rather than modifying the
443      lexer to ignore comments in some circumstances.  Simply returning
444      false doesn't work, since we want to clear the PASTE_LEFT flag.  */
445   if (lhs->type == CPP_DIV && rhs->type != CPP_EQ)
446     *end++ = ' ';
447   end = cpp_spell_token (pfile, rhs, end);
448   *end = '\0';
449 
450   cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true, 1);
451 
452   /* Tweak the column number the lexer will report.  */
453   pfile->buffer->col_adjust = pfile->cur_token[-1].col - 1;
454 
455   /* We don't want a leading # to be interpreted as a directive.  */
456   pfile->buffer->saved_flags = 0;
457 
458   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
459   pfile->cur_token = _cpp_temp_token (pfile);
460   *plhs = _cpp_lex_direct (pfile);
461   valid = pfile->buffer->cur == pfile->buffer->rlimit;
462   _cpp_pop_buffer (pfile);
463 
464   return valid;
465 }
466 
467 /* Handles an arbitrarily long sequence of ## operators, with initial
468    operand LHS.  This implementation is left-associative,
469    non-recursive, and finishes a paste before handling succeeding
470    ones.  If a paste fails, we back up to the RHS of the failing ##
471    operator before pushing the context containing the result of prior
472    successful pastes, with the effect that the RHS appears in the
473    output stream after the pasted LHS normally.  */
474 static void
475 paste_all_tokens (pfile, lhs)
476      cpp_reader *pfile;
477      const cpp_token *lhs;
478 {
479   const cpp_token *rhs;
480   cpp_context *context = pfile->context;
481 
482   do
483     {
484       /* Take the token directly from the current context.  We can do
485 	 this, because we are in the replacement list of either an
486 	 object-like macro, or a function-like macro with arguments
487 	 inserted.  In either case, the constraints to #define
488 	 guarantee we have at least one more token.  */
489       if (context->direct_p)
490 	rhs = FIRST (context).token++;
491       else
492 	rhs = *FIRST (context).ptoken++;
493 
494       if (rhs->type == CPP_PADDING)
495 	abort ();
496 
497       if (!paste_tokens (pfile, &lhs, rhs))
498 	{
499 	  _cpp_backup_tokens (pfile, 1);
500 
501 	  /* Mandatory error for all apart from assembler.  */
502 	  if (CPP_OPTION (pfile, lang) != CLK_ASM)
503 	    cpp_error (pfile, DL_ERROR,
504 	 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
505 		       cpp_token_as_text (pfile, lhs),
506 		       cpp_token_as_text (pfile, rhs));
507 	  break;
508 	}
509     }
510   while (rhs->flags & PASTE_LEFT);
511 
512   /* Put the resulting token in its own context.  */
513   push_token_context (pfile, NULL, lhs, 1);
514 }
515 
516 /* Returns TRUE if the number of arguments ARGC supplied in an
517    invocation of the MACRO referenced by NODE is valid.  An empty
518    invocation to a macro with no parameters should pass ARGC as zero.
519 
520    Note that MACRO cannot necessarily be deduced from NODE, in case
521    NODE was redefined whilst collecting arguments.  */
522 bool
523 _cpp_arguments_ok (pfile, macro, node, argc)
524      cpp_reader *pfile;
525      cpp_macro *macro;
526      const cpp_hashnode *node;
527      unsigned int argc;
528 {
529   if (argc == macro->paramc)
530     return true;
531 
532   if (argc < macro->paramc)
533     {
534       /* As an extension, a rest argument is allowed to not appear in
535 	 the invocation at all.
536 	 e.g. #define debug(format, args...) something
537 	 debug("string");
538 
539 	 This is exactly the same as if there had been an empty rest
540 	 argument - debug("string", ).  */
541 
542       if (argc + 1 == macro->paramc && macro->variadic)
543 	{
544 	  if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
545 	    cpp_error (pfile, DL_PEDWARN,
546 		       "ISO C99 requires rest arguments to be used");
547 	  return true;
548 	}
549 
550       cpp_error (pfile, DL_ERROR,
551 		 "macro \"%s\" requires %u arguments, but only %u given",
552 		 NODE_NAME (node), macro->paramc, argc);
553     }
554   else
555     cpp_error (pfile, DL_ERROR,
556 	       "macro \"%s\" passed %u arguments, but takes just %u",
557 	       NODE_NAME (node), argc, macro->paramc);
558 
559   return false;
560 }
561 
562 /* Reads and returns the arguments to a function-like macro
563    invocation.  Assumes the opening parenthesis has been processed.
564    If there is an error, emits an appropriate diagnostic and returns
565    NULL.  Each argument is terminated by a CPP_EOF token, for the
566    future benefit of expand_arg().  */
567 static _cpp_buff *
568 collect_args (pfile, node)
569      cpp_reader *pfile;
570      const cpp_hashnode *node;
571 {
572   _cpp_buff *buff, *base_buff;
573   cpp_macro *macro;
574   macro_arg *args, *arg;
575   const cpp_token *token;
576   unsigned int argc;
577 
578   macro = node->value.macro;
579   if (macro->paramc)
580     argc = macro->paramc;
581   else
582     argc = 1;
583   buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
584 				       + sizeof (macro_arg)));
585   base_buff = buff;
586   args = (macro_arg *) buff->base;
587   memset (args, 0, argc * sizeof (macro_arg));
588   buff->cur = (unsigned char *) &args[argc];
589   arg = args, argc = 0;
590 
591   /* Collect the tokens making up each argument.  We don't yet know
592      how many arguments have been supplied, whether too many or too
593      few.  Hence the slightly bizarre usage of "argc" and "arg".  */
594   do
595     {
596       unsigned int paren_depth = 0;
597       unsigned int ntokens = 0;
598 
599       argc++;
600       arg->first = (const cpp_token **) buff->cur;
601 
602       for (;;)
603 	{
604 	  /* Require space for 2 new tokens (including a CPP_EOF).  */
605 	  if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
606 	    {
607 	      buff = _cpp_append_extend_buff (pfile, buff,
608 					      1000 * sizeof (cpp_token *));
609 	      arg->first = (const cpp_token **) buff->cur;
610 	    }
611 
612 	  token = cpp_get_token (pfile);
613 
614 	  if (token->type == CPP_PADDING)
615 	    {
616 	      /* Drop leading padding.  */
617 	      if (ntokens == 0)
618 		continue;
619 	    }
620 	  else if (token->type == CPP_OPEN_PAREN)
621 	    paren_depth++;
622 	  else if (token->type == CPP_CLOSE_PAREN)
623 	    {
624 	      if (paren_depth-- == 0)
625 		break;
626 	    }
627 	  else if (token->type == CPP_COMMA)
628 	    {
629 	      /* A comma does not terminate an argument within
630 		 parentheses or as part of a variable argument.  */
631 	      if (paren_depth == 0
632 		  && ! (macro->variadic && argc == macro->paramc))
633 		break;
634 	    }
635 	  else if (token->type == CPP_EOF
636 		   || (token->type == CPP_HASH && token->flags & BOL))
637 	    break;
638 
639 	  arg->first[ntokens++] = token;
640 	}
641 
642       /* Drop trailing padding.  */
643       while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
644 	ntokens--;
645 
646       arg->count = ntokens;
647       arg->first[ntokens] = &pfile->eof;
648 
649       /* Terminate the argument.  Excess arguments loop back and
650 	 overwrite the final legitimate argument, before failing.  */
651       if (argc <= macro->paramc)
652 	{
653 	  buff->cur = (unsigned char *) &arg->first[ntokens + 1];
654 	  if (argc != macro->paramc)
655 	    arg++;
656 	}
657     }
658   while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
659 
660   if (token->type == CPP_EOF)
661     {
662       /* We still need the CPP_EOF to end directives, and to end
663 	 pre-expansion of a macro argument.  Step back is not
664 	 unconditional, since we don't want to return a CPP_EOF to our
665 	 callers at the end of an -include-d file.  */
666       if (pfile->context->prev || pfile->state.in_directive)
667 	_cpp_backup_tokens (pfile, 1);
668       cpp_error (pfile, DL_ERROR,
669 		 "unterminated argument list invoking macro \"%s\"",
670 		 NODE_NAME (node));
671     }
672   else
673     {
674       /* A single empty argument is counted as no argument.  */
675       if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
676 	argc = 0;
677       if (_cpp_arguments_ok (pfile, macro, node, argc))
678 	{
679 	  /* GCC has special semantics for , ## b where b is a varargs
680 	     parameter: we remove the comma if b was omitted entirely.
681 	     If b was merely an empty argument, the comma is retained.
682 	     If the macro takes just one (varargs) parameter, then we
683 	     retain the comma only if we are standards conforming.
684 
685 	     If FIRST is NULL replace_args () swallows the comma.  */
686 	  if (macro->variadic && (argc < macro->paramc
687 				  || (argc == 1 && args[0].count == 0
688 				      && !CPP_OPTION (pfile, std))))
689 	    args[macro->paramc - 1].first = NULL;
690 	  return base_buff;
691 	}
692     }
693 
694   /* An error occurred.  */
695   _cpp_release_buff (pfile, base_buff);
696   return NULL;
697 }
698 
699 /* Search for an opening parenthesis to the macro of NODE, in such a
700    way that, if none is found, we don't lose the information in any
701    intervening padding tokens.  If we find the parenthesis, collect
702    the arguments and return the buffer containing them.  */
703 static _cpp_buff *
704 funlike_invocation_p (pfile, node)
705      cpp_reader *pfile;
706      cpp_hashnode *node;
707 {
708   const cpp_token *token, *padding = NULL;
709 
710   for (;;)
711     {
712       token = cpp_get_token (pfile);
713       if (token->type != CPP_PADDING)
714 	break;
715       if (padding == NULL
716 	  || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
717 	padding = token;
718     }
719 
720   if (token->type == CPP_OPEN_PAREN)
721     {
722       pfile->state.parsing_args = 2;
723       return collect_args (pfile, node);
724     }
725 
726   /* CPP_EOF can be the end of macro arguments, or the end of the
727      file.  We mustn't back up over the latter.  Ugh.  */
728   if (token->type != CPP_EOF || token == &pfile->eof)
729     {
730       /* Back up.  We may have skipped padding, in which case backing
731 	 up more than one token when expanding macros is in general
732 	 too difficult.  We re-insert it in its own context.  */
733       _cpp_backup_tokens (pfile, 1);
734       if (padding)
735 	push_token_context (pfile, NULL, padding, 1);
736     }
737 
738   return NULL;
739 }
740 
741 /* Push the context of a macro with hash entry NODE onto the context
742    stack.  If we can successfully expand the macro, we push a context
743    containing its yet-to-be-rescanned replacement list and return one.
744    Otherwise, we don't push a context and return zero.  */
745 static int
746 enter_macro_context (pfile, node)
747      cpp_reader *pfile;
748      cpp_hashnode *node;
749 {
750   /* The presence of a macro invalidates a file's controlling macro.  */
751   pfile->mi_valid = false;
752 
753   pfile->state.angled_headers = false;
754 
755   /* Handle standard macros.  */
756   if (! (node->flags & NODE_BUILTIN))
757     {
758       cpp_macro *macro = node->value.macro;
759 
760       if (macro->fun_like)
761 	{
762 	  _cpp_buff *buff;
763 
764 	  pfile->state.prevent_expansion++;
765 	  pfile->keep_tokens++;
766 	  pfile->state.parsing_args = 1;
767 	  buff = funlike_invocation_p (pfile, node);
768 	  pfile->state.parsing_args = 0;
769 	  pfile->keep_tokens--;
770 	  pfile->state.prevent_expansion--;
771 
772 	  if (buff == NULL)
773 	    {
774 	      if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
775 		cpp_error (pfile, DL_WARNING,
776  "function-like macro \"%s\" must be used with arguments in traditional C",
777 			   NODE_NAME (node));
778 
779 	      return 0;
780 	    }
781 
782 	  if (macro->paramc > 0)
783 	    replace_args (pfile, node, macro, (macro_arg *) buff->base);
784 	  _cpp_release_buff (pfile, buff);
785 	}
786 
787       /* Disable the macro within its expansion.  */
788       node->flags |= NODE_DISABLED;
789 
790       macro->used = 1;
791 
792       if (macro->paramc == 0)
793 	push_token_context (pfile, node, macro->exp.tokens, macro->count);
794 
795       return 1;
796     }
797 
798   /* Handle built-in macros and the _Pragma operator.  */
799   return builtin_macro (pfile, node);
800 }
801 
802 /* Replace the parameters in a function-like macro of NODE with the
803    actual ARGS, and place the result in a newly pushed token context.
804    Expand each argument before replacing, unless it is operated upon
805    by the # or ## operators.  */
806 static void
807 replace_args (pfile, node, macro, args)
808      cpp_reader *pfile;
809      cpp_hashnode *node;
810      cpp_macro *macro;
811      macro_arg *args;
812 {
813   unsigned int i, total;
814   const cpp_token *src, *limit;
815   const cpp_token **dest, **first;
816   macro_arg *arg;
817   _cpp_buff *buff;
818 
819   /* First, fully macro-expand arguments, calculating the number of
820      tokens in the final expansion as we go.  The ordering of the if
821      statements below is subtle; we must handle stringification before
822      pasting.  */
823   total = macro->count;
824   limit = macro->exp.tokens + macro->count;
825 
826   for (src = macro->exp.tokens; src < limit; src++)
827     if (src->type == CPP_MACRO_ARG)
828       {
829 	/* Leading and trailing padding tokens.  */
830 	total += 2;
831 
832 	/* We have an argument.  If it is not being stringified or
833 	   pasted it is macro-replaced before insertion.  */
834 	arg = &args[src->val.arg_no - 1];
835 
836 	if (src->flags & STRINGIFY_ARG)
837 	  {
838 	    if (!arg->stringified)
839 	      arg->stringified = stringify_arg (pfile, arg);
840 	  }
841 	else if ((src->flags & PASTE_LEFT)
842 		 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
843 	  total += arg->count - 1;
844 	else
845 	  {
846 	    if (!arg->expanded)
847 	      expand_arg (pfile, arg);
848 	    total += arg->expanded_count - 1;
849 	  }
850       }
851 
852   /* Now allocate space for the expansion, copy the tokens and replace
853      the arguments.  */
854   buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
855   first = (const cpp_token **) buff->base;
856   dest = first;
857 
858   for (src = macro->exp.tokens; src < limit; src++)
859     {
860       unsigned int count;
861       const cpp_token **from, **paste_flag;
862 
863       if (src->type != CPP_MACRO_ARG)
864 	{
865 	  *dest++ = src;
866 	  continue;
867 	}
868 
869       paste_flag = 0;
870       arg = &args[src->val.arg_no - 1];
871       if (src->flags & STRINGIFY_ARG)
872 	count = 1, from = &arg->stringified;
873       else if (src->flags & PASTE_LEFT)
874 	count = arg->count, from = arg->first;
875       else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
876 	{
877 	  count = arg->count, from = arg->first;
878 	  if (dest != first)
879 	    {
880 	      if (dest[-1]->type == CPP_COMMA
881 		  && macro->variadic
882 		  && src->val.arg_no == macro->paramc)
883 		{
884 		  /* Swallow a pasted comma if from == NULL, otherwise
885 		     drop the paste flag.  */
886 		  if (from == NULL)
887 		    dest--;
888 		  else
889 		    paste_flag = dest - 1;
890 		}
891 	      /* Remove the paste flag if the RHS is a placemarker.  */
892 	      else if (count == 0)
893 		paste_flag = dest - 1;
894 	    }
895 	}
896       else
897 	count = arg->expanded_count, from = arg->expanded;
898 
899       /* Padding on the left of an argument (unless RHS of ##).  */
900       if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
901 	  && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
902 	*dest++ = padding_token (pfile, src);
903 
904       if (count)
905 	{
906 	  memcpy (dest, from, count * sizeof (cpp_token *));
907 	  dest += count;
908 
909 	  /* With a non-empty argument on the LHS of ##, the last
910 	     token should be flagged PASTE_LEFT.  */
911 	  if (src->flags & PASTE_LEFT)
912 	    paste_flag = dest - 1;
913 	}
914 
915       /* Avoid paste on RHS (even case count == 0).  */
916       if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
917 	*dest++ = &pfile->avoid_paste;
918 
919       /* Add a new paste flag, or remove an unwanted one.  */
920       if (paste_flag)
921 	{
922 	  cpp_token *token = _cpp_temp_token (pfile);
923 	  token->type = (*paste_flag)->type;
924 	  token->val.str = (*paste_flag)->val.str;
925 	  if (src->flags & PASTE_LEFT)
926 	    token->flags = (*paste_flag)->flags | PASTE_LEFT;
927 	  else
928 	    token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
929 	  *paste_flag = token;
930 	}
931     }
932 
933   /* Free the expanded arguments.  */
934   for (i = 0; i < macro->paramc; i++)
935     if (args[i].expanded)
936       free (args[i].expanded);
937 
938   push_ptoken_context (pfile, node, buff, first, dest - first);
939 }
940 
941 /* Return a special padding token, with padding inherited from SOURCE.  */
942 static const cpp_token *
943 padding_token (pfile, source)
944      cpp_reader *pfile;
945      const cpp_token *source;
946 {
947   cpp_token *result = _cpp_temp_token (pfile);
948 
949   result->type = CPP_PADDING;
950   result->val.source = source;
951   result->flags = 0;
952   return result;
953 }
954 
955 /* Get a new uninitialized context.  Create a new one if we cannot
956    re-use an old one.  */
957 static cpp_context *
958 next_context (pfile)
959      cpp_reader *pfile;
960 {
961   cpp_context *result = pfile->context->next;
962 
963   if (result == 0)
964     {
965       result = xnew (cpp_context);
966       result->prev = pfile->context;
967       result->next = 0;
968       pfile->context->next = result;
969     }
970 
971   pfile->context = result;
972   return result;
973 }
974 
975 /* Push a list of pointers to tokens.  */
976 static void
977 push_ptoken_context (pfile, macro, buff, first, count)
978      cpp_reader *pfile;
979      cpp_hashnode *macro;
980      _cpp_buff *buff;
981      const cpp_token **first;
982      unsigned int count;
983 {
984   cpp_context *context = next_context (pfile);
985 
986   context->direct_p = false;
987   context->macro = macro;
988   context->buff = buff;
989   FIRST (context).ptoken = first;
990   LAST (context).ptoken = first + count;
991 }
992 
993 /* Push a list of tokens.  */
994 static void
995 push_token_context (pfile, macro, first, count)
996      cpp_reader *pfile;
997      cpp_hashnode *macro;
998      const cpp_token *first;
999      unsigned int count;
1000 {
1001   cpp_context *context = next_context (pfile);
1002 
1003   context->direct_p = true;
1004   context->macro = macro;
1005   context->buff = NULL;
1006   FIRST (context).token = first;
1007   LAST (context).token = first + count;
1008 }
1009 
1010 /* Push a traditional macro's replacement text.  */
1011 void
1012 _cpp_push_text_context (pfile, macro, start, len)
1013      cpp_reader *pfile;
1014      cpp_hashnode *macro;
1015      const uchar *start;
1016      size_t len;
1017 {
1018   cpp_context *context = next_context (pfile);
1019 
1020   context->direct_p = true;
1021   context->macro = macro;
1022   context->buff = NULL;
1023   CUR (context) = start;
1024   RLIMIT (context) = start + len;
1025   macro->flags |= NODE_DISABLED;
1026 }
1027 
1028 /* Expand an argument ARG before replacing parameters in a
1029    function-like macro.  This works by pushing a context with the
1030    argument's tokens, and then expanding that into a temporary buffer
1031    as if it were a normal part of the token stream.  collect_args()
1032    has terminated the argument's tokens with a CPP_EOF so that we know
1033    when we have fully expanded the argument.  */
1034 static void
1035 expand_arg (pfile, arg)
1036      cpp_reader *pfile;
1037      macro_arg *arg;
1038 {
1039   unsigned int capacity;
1040   bool saved_warn_trad;
1041 
1042   if (arg->count == 0)
1043     return;
1044 
1045   /* Don't warn about funlike macros when pre-expanding.  */
1046   saved_warn_trad = CPP_WTRADITIONAL (pfile);
1047   CPP_WTRADITIONAL (pfile) = 0;
1048 
1049   /* Loop, reading in the arguments.  */
1050   capacity = 256;
1051   arg->expanded = (const cpp_token **)
1052     xmalloc (capacity * sizeof (cpp_token *));
1053 
1054   push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
1055   for (;;)
1056     {
1057       const cpp_token *token;
1058 
1059       if (arg->expanded_count + 1 >= capacity)
1060 	{
1061 	  capacity *= 2;
1062 	  arg->expanded = (const cpp_token **)
1063 	    xrealloc (arg->expanded, capacity * sizeof (cpp_token *));
1064 	}
1065 
1066       token = cpp_get_token (pfile);
1067 
1068       if (token->type == CPP_EOF)
1069 	break;
1070 
1071       arg->expanded[arg->expanded_count++] = token;
1072     }
1073 
1074   _cpp_pop_context (pfile);
1075 
1076   CPP_WTRADITIONAL (pfile) = saved_warn_trad;
1077 }
1078 
1079 /* Pop the current context off the stack, re-enabling the macro if the
1080    context represented a macro's replacement list.  The context
1081    structure is not freed so that we can re-use it later.  */
1082 void
1083 _cpp_pop_context (pfile)
1084      cpp_reader *pfile;
1085 {
1086   cpp_context *context = pfile->context;
1087 
1088   if (context->macro)
1089     context->macro->flags &= ~NODE_DISABLED;
1090 
1091   if (context->buff)
1092     _cpp_release_buff (pfile, context->buff);
1093 
1094   pfile->context = context->prev;
1095 }
1096 
1097 /* Eternal routine to get a token.  Also used nearly everywhere
1098    internally, except for places where we know we can safely call
1099    the lexer directly, such as lexing a directive name.
1100 
1101    Macro expansions and directives are transparently handled,
1102    including entering included files.  Thus tokens are post-macro
1103    expansion, and after any intervening directives.  External callers
1104    see CPP_EOF only at EOF.  Internal callers also see it when meeting
1105    a directive inside a macro call, when at the end of a directive and
1106    state.in_directive is still 1, and at the end of argument
1107    pre-expansion.  */
1108 const cpp_token *
1109 cpp_get_token (pfile)
1110      cpp_reader *pfile;
1111 {
1112   const cpp_token *result;
1113 
1114   for (;;)
1115     {
1116       cpp_hashnode *node;
1117       cpp_context *context = pfile->context;
1118 
1119       /* Context->prev == 0 <=> base context.  */
1120       if (!context->prev)
1121 	result = _cpp_lex_token (pfile);
1122       else if (FIRST (context).token != LAST (context).token)
1123 	{
1124 	  if (context->direct_p)
1125 	    result = FIRST (context).token++;
1126 	  else
1127 	    result = *FIRST (context).ptoken++;
1128 
1129 	  if (result->flags & PASTE_LEFT)
1130 	    {
1131 	      paste_all_tokens (pfile, result);
1132 	      if (pfile->state.in_directive)
1133 		continue;
1134 	      return padding_token (pfile, result);
1135 	    }
1136 	}
1137       else
1138 	{
1139 	  _cpp_pop_context (pfile);
1140 	  if (pfile->state.in_directive)
1141 	    continue;
1142 	  return &pfile->avoid_paste;
1143 	}
1144 
1145       if (pfile->state.in_directive && result->type == CPP_COMMENT)
1146 	continue;
1147 
1148       if (result->type != CPP_NAME)
1149 	break;
1150 
1151       node = result->val.node;
1152 
1153       if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1154 	break;
1155 
1156       if (!(node->flags & NODE_DISABLED))
1157 	{
1158 	  if (!pfile->state.prevent_expansion
1159 	      && enter_macro_context (pfile, node))
1160 	    {
1161 	      if (pfile->state.in_directive)
1162 		continue;
1163 	      return padding_token (pfile, result);
1164 	    }
1165 	}
1166       else
1167 	{
1168 	  /* Flag this token as always unexpandable.  FIXME: move this
1169 	     to collect_args()?.  */
1170 	  cpp_token *t = _cpp_temp_token (pfile);
1171 	  t->type = result->type;
1172 	  t->flags = result->flags | NO_EXPAND;
1173 	  t->val.str = result->val.str;
1174 	  result = t;
1175 	}
1176 
1177       break;
1178     }
1179 
1180   return result;
1181 }
1182 
1183 /* Returns true if we're expanding an object-like macro that was
1184    defined in a system header.  Just checks the macro at the top of
1185    the stack.  Used for diagnostic suppression.  */
1186 int
1187 cpp_sys_macro_p (pfile)
1188      cpp_reader *pfile;
1189 {
1190   cpp_hashnode *node = pfile->context->macro;
1191 
1192   return node && node->value.macro && node->value.macro->syshdr;
1193 }
1194 
1195 /* Read each token in, until end of the current file.  Directives are
1196    transparently processed.  */
1197 void
1198 cpp_scan_nooutput (pfile)
1199      cpp_reader *pfile;
1200 {
1201   /* Request a CPP_EOF token at the end of this file, rather than
1202      transparently continuing with the including file.  */
1203   pfile->buffer->return_at_eof = true;
1204 
1205   if (CPP_OPTION (pfile, traditional))
1206     while (_cpp_read_logical_line_trad (pfile))
1207       ;
1208   else
1209     while (cpp_get_token (pfile)->type != CPP_EOF)
1210       ;
1211 }
1212 
1213 /* Step back one (or more) tokens.  Can only step mack more than 1 if
1214    they are from the lexer, and not from macro expansion.  */
1215 void
1216 _cpp_backup_tokens (pfile, count)
1217      cpp_reader *pfile;
1218      unsigned int count;
1219 {
1220   if (pfile->context->prev == NULL)
1221     {
1222       pfile->lookaheads += count;
1223       while (count--)
1224 	{
1225 	  pfile->cur_token--;
1226 	  if (pfile->cur_token == pfile->cur_run->base
1227 	      /* Possible with -fpreprocessed and no leading #line.  */
1228 	      && pfile->cur_run->prev != NULL)
1229 	    {
1230 	      pfile->cur_run = pfile->cur_run->prev;
1231 	      pfile->cur_token = pfile->cur_run->limit;
1232 	    }
1233 	}
1234     }
1235   else
1236     {
1237       if (count != 1)
1238 	abort ();
1239       if (pfile->context->direct_p)
1240 	FIRST (pfile->context).token--;
1241       else
1242 	FIRST (pfile->context).ptoken--;
1243     }
1244 }
1245 
1246 /* #define directive parsing and handling.  */
1247 
1248 /* Returns nonzero if a macro redefinition warning is required.  */
1249 static bool
1250 warn_of_redefinition (pfile, node, macro2)
1251      cpp_reader *pfile;
1252      const cpp_hashnode *node;
1253      const cpp_macro *macro2;
1254 {
1255   const cpp_macro *macro1;
1256   unsigned int i;
1257 
1258   /* Some redefinitions need to be warned about regardless.  */
1259   if (node->flags & NODE_WARN)
1260     return true;
1261 
1262   /* Redefinition of a macro is allowed if and only if the old and new
1263      definitions are the same.  (6.10.3 paragraph 2).  */
1264   macro1 = node->value.macro;
1265 
1266   /* Don't check count here as it can be different in valid
1267      traditional redefinitions with just whitespace differences.  */
1268   if (macro1->paramc != macro2->paramc
1269       || macro1->fun_like != macro2->fun_like
1270       || macro1->variadic != macro2->variadic)
1271     return true;
1272 
1273   /* Check parameter spellings.  */
1274   for (i = 0; i < macro1->paramc; i++)
1275     if (macro1->params[i] != macro2->params[i])
1276       return true;
1277 
1278   /* Check the replacement text or tokens.  */
1279   if (CPP_OPTION (pfile, traditional))
1280     return _cpp_expansions_different_trad (macro1, macro2);
1281 
1282   if (macro1->count != macro2->count)
1283     return true;
1284 
1285   for (i = 0; i < macro1->count; i++)
1286     if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
1287       return true;
1288 
1289   return false;
1290 }
1291 
1292 /* Free the definition of hashnode H.  */
1293 void
1294 _cpp_free_definition (h)
1295      cpp_hashnode *h;
1296 {
1297   /* Macros and assertions no longer have anything to free.  */
1298   h->type = NT_VOID;
1299   /* Clear builtin flag in case of redefinition.  */
1300   h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1301 }
1302 
1303 /* Save parameter NODE to the parameter list of macro MACRO.  Returns
1304    zero on success, nonzero if the parameter is a duplicate.  */
1305 bool
1306 _cpp_save_parameter (pfile, macro, node)
1307      cpp_reader *pfile;
1308      cpp_macro *macro;
1309      cpp_hashnode *node;
1310 {
1311   /* Constraint 6.10.3.6 - duplicate parameter names.  */
1312   if (node->arg_index)
1313     {
1314       cpp_error (pfile, DL_ERROR, "duplicate macro parameter \"%s\"",
1315 		 NODE_NAME (node));
1316       return true;
1317     }
1318 
1319   if (BUFF_ROOM (pfile->a_buff)
1320       < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1321     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1322 
1323   ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1324   node->arg_index = macro->paramc;
1325   return false;
1326 }
1327 
1328 /* Check the syntax of the parameters in a MACRO definition.  Returns
1329    false if an error occurs.  */
1330 static bool
1331 parse_params (pfile, macro)
1332      cpp_reader *pfile;
1333      cpp_macro *macro;
1334 {
1335   unsigned int prev_ident = 0;
1336 
1337   for (;;)
1338     {
1339       const cpp_token *token = _cpp_lex_token (pfile);
1340 
1341       switch (token->type)
1342 	{
1343 	default:
1344 	  /* Allow/ignore comments in parameter lists if we are
1345 	     preserving comments in macro expansions.  */
1346 	  if (token->type == CPP_COMMENT
1347 	      && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
1348 	    continue;
1349 
1350 	  cpp_error (pfile, DL_ERROR,
1351 		     "\"%s\" may not appear in macro parameter list",
1352 		     cpp_token_as_text (pfile, token));
1353 	  return false;
1354 
1355 	case CPP_NAME:
1356 	  if (prev_ident)
1357 	    {
1358 	      cpp_error (pfile, DL_ERROR,
1359 			 "macro parameters must be comma-separated");
1360 	      return false;
1361 	    }
1362 	  prev_ident = 1;
1363 
1364 	  if (_cpp_save_parameter (pfile, macro, token->val.node))
1365 	    return false;
1366 	  continue;
1367 
1368 	case CPP_CLOSE_PAREN:
1369 	  if (prev_ident || macro->paramc == 0)
1370 	    return true;
1371 
1372 	  /* Fall through to pick up the error.  */
1373 	case CPP_COMMA:
1374 	  if (!prev_ident)
1375 	    {
1376 	      cpp_error (pfile, DL_ERROR, "parameter name missing");
1377 	      return false;
1378 	    }
1379 	  prev_ident = 0;
1380 	  continue;
1381 
1382 	case CPP_ELLIPSIS:
1383 	  macro->variadic = 1;
1384 	  if (!prev_ident)
1385 	    {
1386 	      _cpp_save_parameter (pfile, macro,
1387 				   pfile->spec_nodes.n__VA_ARGS__);
1388 	      pfile->state.va_args_ok = 1;
1389 	      if (! CPP_OPTION (pfile, c99) && CPP_OPTION (pfile, pedantic))
1390 		cpp_error (pfile, DL_PEDWARN,
1391 			   "anonymous variadic macros were introduced in C99");
1392 	    }
1393 	  else if (CPP_OPTION (pfile, pedantic))
1394 	    cpp_error (pfile, DL_PEDWARN,
1395 		       "ISO C does not permit named variadic macros");
1396 
1397 	  /* We're at the end, and just expect a closing parenthesis.  */
1398 	  token = _cpp_lex_token (pfile);
1399 	  if (token->type == CPP_CLOSE_PAREN)
1400 	    return true;
1401 	  /* Fall through.  */
1402 
1403 	case CPP_EOF:
1404 	  cpp_error (pfile, DL_ERROR, "missing ')' in macro parameter list");
1405 	  return false;
1406 	}
1407     }
1408 }
1409 
1410 /* Allocate room for a token from a macro's replacement list.  */
1411 static cpp_token *
1412 alloc_expansion_token (pfile, macro)
1413      cpp_reader *pfile;
1414      cpp_macro *macro;
1415 {
1416   if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1417     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1418 
1419   return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1420 }
1421 
1422 /* Lex a token from the expansion of MACRO, but mark parameters as we
1423    find them and warn of traditional stringification.  */
1424 static cpp_token *
1425 lex_expansion_token (pfile, macro)
1426      cpp_reader *pfile;
1427      cpp_macro *macro;
1428 {
1429   cpp_token *token;
1430 
1431   pfile->cur_token = alloc_expansion_token (pfile, macro);
1432   token = _cpp_lex_direct (pfile);
1433 
1434   /* Is this a parameter?  */
1435   if (token->type == CPP_NAME && token->val.node->arg_index)
1436     {
1437       token->type = CPP_MACRO_ARG;
1438       token->val.arg_no = token->val.node->arg_index;
1439     }
1440   else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1441 	   && (token->type == CPP_STRING || token->type == CPP_CHAR))
1442     check_trad_stringification (pfile, macro, &token->val.str);
1443 
1444   return token;
1445 }
1446 
1447 static bool
1448 create_iso_definition (pfile, macro)
1449      cpp_reader *pfile;
1450      cpp_macro *macro;
1451 {
1452   cpp_token *token;
1453   const cpp_token *ctoken;
1454 
1455   /* Get the first token of the expansion (or the '(' of a
1456      function-like macro).  */
1457   ctoken = _cpp_lex_token (pfile);
1458 
1459   if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1460     {
1461       bool ok = parse_params (pfile, macro);
1462       macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1463       if (!ok)
1464 	return false;
1465 
1466       /* Success.  Commit the parameter array.  */
1467       BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1468       macro->fun_like = 1;
1469     }
1470   else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1471     cpp_error (pfile, DL_PEDWARN,
1472 	       "ISO C requires whitespace after the macro name");
1473 
1474   if (macro->fun_like)
1475     token = lex_expansion_token (pfile, macro);
1476   else
1477     {
1478       token = alloc_expansion_token (pfile, macro);
1479       *token = *ctoken;
1480     }
1481 
1482   for (;;)
1483     {
1484       /* Check the stringifying # constraint 6.10.3.2.1 of
1485 	 function-like macros when lexing the subsequent token.  */
1486       if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1487 	{
1488 	  if (token->type == CPP_MACRO_ARG)
1489 	    {
1490 	      token->flags &= ~PREV_WHITE;
1491 	      token->flags |= STRINGIFY_ARG;
1492 	      token->flags |= token[-1].flags & PREV_WHITE;
1493 	      token[-1] = token[0];
1494 	      macro->count--;
1495 	    }
1496 	  /* Let assembler get away with murder.  */
1497 	  else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1498 	    {
1499 	      cpp_error (pfile, DL_ERROR,
1500 			 "'#' is not followed by a macro parameter");
1501 	      return false;
1502 	    }
1503 	}
1504 
1505       if (token->type == CPP_EOF)
1506 	break;
1507 
1508       /* Paste operator constraint 6.10.3.3.1.  */
1509       if (token->type == CPP_PASTE)
1510 	{
1511 	  /* Token-paste ##, can appear in both object-like and
1512 	     function-like macros, but not at the ends.  */
1513 	  if (--macro->count > 0)
1514 	    token = lex_expansion_token (pfile, macro);
1515 
1516 	  if (macro->count == 0 || token->type == CPP_EOF)
1517 	    {
1518 	      cpp_error (pfile, DL_ERROR,
1519 			 "'##' cannot appear at either end of a macro expansion");
1520 	      return false;
1521 	    }
1522 
1523 	  token[-1].flags |= PASTE_LEFT;
1524 	}
1525 
1526       token = lex_expansion_token (pfile, macro);
1527     }
1528 
1529   macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1530 
1531   /* Don't count the CPP_EOF.  */
1532   macro->count--;
1533 
1534   /* Clear whitespace on first token for warn_of_redefinition().  */
1535   if (macro->count)
1536     macro->exp.tokens[0].flags &= ~PREV_WHITE;
1537 
1538   /* Commit the memory.  */
1539   BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
1540 
1541   return true;
1542 }
1543 
1544 /* Parse a macro and save its expansion.  Returns nonzero on success.  */
1545 bool
1546 _cpp_create_definition (pfile, node)
1547      cpp_reader *pfile;
1548      cpp_hashnode *node;
1549 {
1550   cpp_macro *macro;
1551   unsigned int i;
1552   bool ok;
1553 
1554   macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1555   macro->line = pfile->directive_line;
1556   macro->params = 0;
1557   macro->paramc = 0;
1558   macro->variadic = 0;
1559   macro->used = 0;
1560   macro->count = 0;
1561   macro->fun_like = 0;
1562   /* To suppress some diagnostics.  */
1563   macro->syshdr = pfile->map->sysp != 0;
1564 
1565   if (CPP_OPTION (pfile, traditional))
1566     ok = _cpp_create_trad_definition (pfile, macro);
1567   else
1568     {
1569       cpp_token *saved_cur_token = pfile->cur_token;
1570 
1571       ok = create_iso_definition (pfile, macro);
1572 
1573       /* Restore lexer position because of games lex_expansion_token()
1574 	 plays lexing the macro.  We set the type for SEEN_EOL() in
1575 	 cpplib.c.
1576 
1577 	 Longer term we should lex the whole line before coming here,
1578 	 and just copy the expansion.  */
1579       saved_cur_token[-1].type = pfile->cur_token[-1].type;
1580       pfile->cur_token = saved_cur_token;
1581 
1582       /* Stop the lexer accepting __VA_ARGS__.  */
1583       pfile->state.va_args_ok = 0;
1584     }
1585 
1586   /* Clear the fast argument lookup indices.  */
1587   for (i = macro->paramc; i-- > 0; )
1588     macro->params[i]->arg_index = 0;
1589 
1590   if (!ok)
1591     return ok;
1592 
1593   if (node->type == NT_MACRO)
1594     {
1595       if (CPP_OPTION (pfile, warn_unused_macros))
1596 	_cpp_warn_if_unused_macro (pfile, node, NULL);
1597 
1598       if (warn_of_redefinition (pfile, node, macro))
1599 	{
1600 	  cpp_error_with_line (pfile, DL_PEDWARN, pfile->directive_line, 0,
1601 			       "\"%s\" redefined", NODE_NAME (node));
1602 
1603 	  if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1604 	    cpp_error_with_line (pfile, DL_PEDWARN,
1605 				 node->value.macro->line, 0,
1606 			 "this is the location of the previous definition");
1607 	}
1608     }
1609 
1610   if (node->type != NT_VOID)
1611     _cpp_free_definition (node);
1612 
1613   /* Enter definition in hash table.  */
1614   node->type = NT_MACRO;
1615   node->value.macro = macro;
1616   if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1617     node->flags |= NODE_WARN;
1618 
1619   return ok;
1620 }
1621 
1622 /* Warn if a token in STRING matches one of a function-like MACRO's
1623    parameters.  */
1624 static void
1625 check_trad_stringification (pfile, macro, string)
1626      cpp_reader *pfile;
1627      const cpp_macro *macro;
1628      const cpp_string *string;
1629 {
1630   unsigned int i, len;
1631   const uchar *p, *q, *limit = string->text + string->len;
1632 
1633   /* Loop over the string.  */
1634   for (p = string->text; p < limit; p = q)
1635     {
1636       /* Find the start of an identifier.  */
1637       while (p < limit && !is_idstart (*p))
1638 	p++;
1639 
1640       /* Find the end of the identifier.  */
1641       q = p;
1642       while (q < limit && is_idchar (*q))
1643 	q++;
1644 
1645       len = q - p;
1646 
1647       /* Loop over the function macro arguments to see if the
1648 	 identifier inside the string matches one of them.  */
1649       for (i = 0; i < macro->paramc; i++)
1650 	{
1651 	  const cpp_hashnode *node = macro->params[i];
1652 
1653 	  if (NODE_LEN (node) == len
1654 	      && !memcmp (p, NODE_NAME (node), len))
1655 	    {
1656 	      cpp_error (pfile, DL_WARNING,
1657 	   "macro argument \"%s\" would be stringified in traditional C",
1658 			 NODE_NAME (node));
1659 	      break;
1660 	    }
1661 	}
1662     }
1663 }
1664 
1665 /* Returns the name, arguments and expansion of a macro, in a format
1666    suitable to be read back in again, and therefore also for DWARF 2
1667    debugging info.  e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1668    Caller is expected to generate the "#define" bit if needed.  The
1669    returned text is temporary, and automatically freed later.  */
1670 const unsigned char *
1671 cpp_macro_definition (pfile, node)
1672      cpp_reader *pfile;
1673      const cpp_hashnode *node;
1674 {
1675   unsigned int i, len;
1676   const cpp_macro *macro = node->value.macro;
1677   unsigned char *buffer;
1678 
1679   if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1680     {
1681       cpp_error (pfile, DL_ICE,
1682 		 "invalid hash type %d in cpp_macro_definition", node->type);
1683       return 0;
1684     }
1685 
1686   /* Calculate length.  */
1687   len = NODE_LEN (node) + 2;			/* ' ' and NUL.  */
1688   if (macro->fun_like)
1689     {
1690       len += 4;		/* "()" plus possible final ".." of named
1691 			   varargs (we have + 1 below).  */
1692       for (i = 0; i < macro->paramc; i++)
1693 	len += NODE_LEN (macro->params[i]) + 1; /* "," */
1694     }
1695 
1696   if (CPP_OPTION (pfile, traditional))
1697     len += _cpp_replacement_text_len (macro);
1698   else
1699     {
1700       for (i = 0; i < macro->count; i++)
1701 	{
1702 	  cpp_token *token = &macro->exp.tokens[i];
1703 
1704 	  if (token->type == CPP_MACRO_ARG)
1705 	    len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1706 	  else
1707 	    len += cpp_token_len (token); /* Includes room for ' '.  */
1708 	  if (token->flags & STRINGIFY_ARG)
1709 	    len++;			/* "#" */
1710 	  if (token->flags & PASTE_LEFT)
1711 	    len += 3;		/* " ##" */
1712 	}
1713     }
1714 
1715   if (len > pfile->macro_buffer_len)
1716     {
1717       pfile->macro_buffer = (uchar *) xrealloc (pfile->macro_buffer, len);
1718       pfile->macro_buffer_len = len;
1719     }
1720 
1721   /* Fill in the buffer.  Start with the macro name.  */
1722   buffer = pfile->macro_buffer;
1723   memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1724   buffer += NODE_LEN (node);
1725 
1726   /* Parameter names.  */
1727   if (macro->fun_like)
1728     {
1729       *buffer++ = '(';
1730       for (i = 0; i < macro->paramc; i++)
1731 	{
1732 	  cpp_hashnode *param = macro->params[i];
1733 
1734 	  if (param != pfile->spec_nodes.n__VA_ARGS__)
1735 	    {
1736 	      memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1737 	      buffer += NODE_LEN (param);
1738 	    }
1739 
1740 	  if (i + 1 < macro->paramc)
1741 	    /* Don't emit a space after the comma here; we're trying
1742 	       to emit a Dwarf-friendly definition, and the Dwarf spec
1743 	       forbids spaces in the argument list.  */
1744 	    *buffer++ = ',';
1745 	  else if (macro->variadic)
1746 	    *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1747 	}
1748       *buffer++ = ')';
1749     }
1750 
1751   /* The Dwarf spec requires a space after the macro name, even if the
1752      definition is the empty string.  */
1753   *buffer++ = ' ';
1754 
1755   if (CPP_OPTION (pfile, traditional))
1756     buffer = _cpp_copy_replacement_text (macro, buffer);
1757   else if (macro->count)
1758   /* Expansion tokens.  */
1759     {
1760       for (i = 0; i < macro->count; i++)
1761 	{
1762 	  cpp_token *token = &macro->exp.tokens[i];
1763 
1764 	  if (token->flags & PREV_WHITE)
1765 	    *buffer++ = ' ';
1766 	  if (token->flags & STRINGIFY_ARG)
1767 	    *buffer++ = '#';
1768 
1769 	  if (token->type == CPP_MACRO_ARG)
1770 	    {
1771 	      len = NODE_LEN (macro->params[token->val.arg_no - 1]);
1772 	      memcpy (buffer,
1773 		      NODE_NAME (macro->params[token->val.arg_no - 1]), len);
1774 	      buffer += len;
1775 	    }
1776 	  else
1777 	    buffer = cpp_spell_token (pfile, token, buffer);
1778 
1779 	  if (token->flags & PASTE_LEFT)
1780 	    {
1781 	      *buffer++ = ' ';
1782 	      *buffer++ = '#';
1783 	      *buffer++ = '#';
1784 	      /* Next has PREV_WHITE; see _cpp_create_definition.  */
1785 	    }
1786 	}
1787     }
1788 
1789   *buffer = '\0';
1790   return pfile->macro_buffer;
1791 }
1792