OSDN Git Service

* cpphash.c (trad_stringify): Adjust p after stringification as
[pf3gnuchains/gcc-fork.git] / gcc / cpphash.c
1 /* Part of CPP library.  (Macro 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 "cpplib.h"
29 #include "hashtab.h"
30 #include "cpphash.h"
31
32 #undef abort
33
34 /* Structure allocated for every #define.  For a simple replacement
35    such as
36         #define foo bar
37
38    we allocate an object_defn structure; the expansion field points
39    to the replacement text.  For a function-like macro we allocate a
40    funct_defn structure; nargs is the number of arguments - it can be zero,
41    e.g.
42        #define getchar() getc (stdin)
43
44    When there are args, the expansion is the replacement text with the
45    args squashed out, and the reflist is a list describing how to
46    build the output from the input: e.g., "3 chars, then the 1st arg,
47    then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
48    The chars here come from the expansion.  Whatever is left of the
49    expansion after the last arg-occurrence is copied after that arg.
50    Note that the reflist can be arbitrarily long---
51    its length depends on the number of times the arguments appear in
52    the replacement text, not how many args there are.  Example:
53    #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
54    pattern list
55      { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
56    where (x, y) means (nchars, argno).
57
58    Note that EMPTY and IDENTITY macros have object_defn structures too,
59    but they're just used to hold the file, line, and column.  The
60    expansion field will be NULL.  */
61
62 struct object_defn
63 {
64   const U_CHAR *expansion;
65   unsigned int length;
66
67   const char *file;             /* File, line, column of definition */
68   int line;
69   int col;
70 };  
71
72 struct reflist
73 {
74   const struct reflist *next;
75   char stringify;               /* nonzero if this arg was preceded by a
76                                    # operator. */
77   char raw_before;              /* Nonzero if a ## operator before arg. */
78   char raw_after;               /* Nonzero if a ## operator after arg. */
79   char rest_args;               /* Nonzero if this arg. absorbs the rest */
80   int nchars;                   /* Number of literal chars to copy before
81                                    this arg occurrence.  */
82   int argno;                    /* Number of arg to substitute (origin-0) */
83 };
84
85 struct funct_defn
86 {
87   int nargs;
88   int length;                   /* length of expansion string */
89   const U_CHAR *expansion;
90   char rest_args;               /* Nonzero if last arg. absorbs the rest */
91   const struct reflist *pattern;
92
93   /* Names of macro args, concatenated in order with \0 between
94      them.  The only use of this is that we warn on redefinition if
95      this differs between the old and new definitions.  */
96   U_CHAR *argnames;
97
98   const char *file;             /* File, line, column of definition */
99   int line;
100   int col;
101 };
102
103 static unsigned int hash_HASHNODE PARAMS ((const void *));
104 static int eq_HASHNODE            PARAMS ((const void *, const void *));
105 static void del_HASHNODE          PARAMS ((void *));
106 static HASHNODE *make_HASHNODE    PARAMS ((const U_CHAR *, size_t,
107                                            enum node_type, unsigned int));
108
109 static void dump_funlike_macro    PARAMS ((cpp_reader *,
110                                            const struct funct_defn *));
111 static int dump_hash_helper       PARAMS ((void **, void *));
112
113 static void push_macro_expansion PARAMS ((cpp_reader *, const U_CHAR *,
114                                           int, HASHNODE *));
115 static int unsafe_chars          PARAMS ((cpp_reader *, int, int));
116 static enum cpp_ttype macarg     PARAMS ((cpp_reader *, int));
117 static void special_symbol       PARAMS ((cpp_reader *, HASHNODE *));
118 static int compare_defs          PARAMS ((cpp_reader *,
119                                           const struct funct_defn *,
120                                           const struct funct_defn *));
121
122 /* Initial hash table size.  (It can grow if necessary - see hashtab.c.)  */
123 #define HASHSIZE 500
124
125 /* The arglist structure is built by collect_params to tell
126    collect_funlike_expansion where the argument names begin.  That is,
127    for a define like "#define f(x,y,z) foo+x-bar*y", the arglist would
128    contain pointers to the strings x, y, and z.
129    collect_funlike_expansion would then build a funct_defn node, with
130    reflist nodes pointing to the places x, y, and z had appeared.
131
132    The arglist is just convenience data passed between these two
133    routines.  It is not kept around after the current #define has been
134    processed and entered into the hash table.  */
135
136 struct arg
137 {
138   const U_CHAR *name;
139   unsigned int len;
140   char rest_arg;
141 };
142
143 struct arglist
144 {
145   U_CHAR *namebuf;
146   const struct arg *argv;
147   int argc;
148 };
149
150
151 static struct object_defn *
152 collect_objlike_expansion PARAMS ((cpp_reader *, cpp_toklist *));
153 static struct funct_defn *
154 collect_funlike_expansion PARAMS ((cpp_reader *, cpp_toklist *,
155                                    struct arglist *, unsigned int));
156 static unsigned int collect_params PARAMS ((cpp_reader *, cpp_toklist *,
157                                             struct arglist *));
158
159 static void warn_trad_stringify PARAMS ((cpp_reader *, U_CHAR *, size_t,
160                                          unsigned int, const struct arg *));
161 static unsigned int trad_stringify PARAMS ((cpp_reader *, U_CHAR *, size_t,
162                                             unsigned int, const struct arg *,
163                                             struct reflist **,
164                                             struct reflist **, unsigned int));
165 static int duplicate_arg_p PARAMS ((U_CHAR *, U_CHAR *));
166 static void add_pat PARAMS ((struct reflist **, struct reflist **,
167                              unsigned int, unsigned int, int, int, int, int));
168
169 /* This structure represents one parsed argument in a macro call.
170    `raw' points to the argument text as written (`raw_length' is its length).
171    `expanded' points to the argument's macro-expansion
172    (its length is `expand_length').
173    `stringified_length' is the length the argument would have
174    if stringified.  */
175
176 /* raw and expanded are relative to ARG_BASE */
177 #define ARG_BASE ((pfile)->token_buffer)
178
179 struct argdata
180 {
181   /* Strings relative to pfile->token_buffer */
182   long raw, expanded, stringified;
183   int raw_length, expand_length;
184   int stringified_length;
185 };
186
187 static void scan_arguments      PARAMS ((cpp_reader *,
188                                          const struct funct_defn *,
189                                          struct argdata *, const U_CHAR *));
190 static void stringify           PARAMS ((cpp_reader *, struct argdata *));
191 static void funlike_macroexpand PARAMS ((cpp_reader *, HASHNODE *,
192                                          struct argdata *));
193
194 /* Calculate hash of a string of length LEN.  */
195 unsigned int
196 _cpp_calc_hash (str, len)
197      const U_CHAR *str;
198      size_t len;
199 {
200   size_t n = len;
201   unsigned int r = 0;
202
203   do
204     r = r * 67 + (*str++ - 113);
205   while (--n);
206   return r + len;
207 }
208
209 /* Calculate hash of a HASHNODE structure.  */
210 static unsigned int
211 hash_HASHNODE (x)
212      const void *x;
213 {
214   const HASHNODE *h = (const HASHNODE *)x;
215   return h->hash;
216 }
217
218 /* Compare two HASHNODE structures.  */
219 static int
220 eq_HASHNODE (x, y)
221      const void *x;
222      const void *y;
223 {
224   const HASHNODE *a = (const HASHNODE *)x;
225   const HASHNODE *b = (const HASHNODE *)y;
226
227   return (a->length == b->length
228           && !strncmp (a->name, b->name, a->length));
229 }
230
231 /* Destroy a HASHNODE.  */
232 static void
233 del_HASHNODE (x)
234      void *x;
235 {
236   HASHNODE *h = (HASHNODE *)x;
237
238   _cpp_free_definition (h);
239   free (h);
240 }
241
242 /* Allocate and initialize a HASHNODE structure.
243    Caller must fill in the value field.  */
244
245 static HASHNODE *
246 make_HASHNODE (name, len, type, hash)
247      const U_CHAR *name;
248      size_t len;
249      enum node_type type;
250      unsigned int hash;
251 {
252   HASHNODE *hp = (HASHNODE *) xmalloc (sizeof (HASHNODE) + len + 1);
253   U_CHAR *p = (U_CHAR *)hp + sizeof (HASHNODE);
254
255   hp->type = type;
256   hp->length = len;
257   hp->name = p;
258   hp->hash = hash;
259   hp->disabled = 0;
260
261   memcpy (p, name, len);
262   p[len] = 0;
263
264   return hp;
265 }
266
267 /* Find the hash node for name "name", of length LEN.  */
268
269 HASHNODE *
270 _cpp_lookup (pfile, name, len)
271      cpp_reader *pfile;
272      const U_CHAR *name;
273      int len;
274 {
275   HASHNODE dummy;
276   HASHNODE *new, **slot;
277
278   dummy.name = name;
279   dummy.length = len;
280   dummy.hash = _cpp_calc_hash (name, len);
281
282   slot = (HASHNODE **)
283     htab_find_slot_with_hash (pfile->hashtab, (void *)&dummy,
284                               dummy.hash, INSERT);
285   if (*slot)
286     return *slot;
287
288   new = make_HASHNODE (name, len, T_VOID, dummy.hash);
289   new->value.cpval = NULL;
290   *slot = new;
291   return new;
292 }
293
294 /* Init the hash table.  In here so it can see the hash and eq functions.  */
295 void
296 _cpp_init_macro_hash (pfile)
297      cpp_reader *pfile;
298 {
299   pfile->hashtab = htab_create (HASHSIZE, hash_HASHNODE,
300                                 eq_HASHNODE, del_HASHNODE);
301 }
302
303 /* Free the definition of macro H.  */
304
305 void
306 _cpp_free_definition (h)
307      HASHNODE *h;
308 {
309   if (h->type == T_XCONST)
310     free ((PTR) h->value.cpval);
311   else if (h->type == T_MACRO)
312     {
313       if (h->value.odefn->expansion)
314         free ((PTR) h->value.odefn->expansion);
315       free ((PTR) h->value.odefn);
316     }
317   else if (h->type == T_FMACRO)
318     {
319       const struct funct_defn *d = h->value.fdefn;
320       const struct reflist *ap, *nextap;
321     
322       for (ap = d->pattern; ap != NULL; ap = nextap)
323         {
324           nextap = ap->next;
325           free ((PTR) ap);
326         }
327       if (d->argnames)
328         free ((PTR) d->argnames);
329       free ((PTR) d);
330     }
331   h->value.cpval = NULL;
332 }
333
334 /* Create pat nodes.  */
335
336 static void
337 add_pat (pat, endpat, nchars, argno, raw_before, raw_after, strize, rest)
338      struct reflist **pat, **endpat;
339      unsigned int nchars;
340      unsigned int argno;
341      int raw_before, raw_after, strize, rest;
342 {
343   struct reflist *tpat;
344   tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
345   tpat->next = NULL;
346   tpat->raw_before = raw_before;
347   tpat->raw_after = raw_after;
348   tpat->stringify = strize;
349   tpat->rest_args = rest;
350   tpat->argno = argno;
351   tpat->nchars = nchars;
352
353   if (*endpat == NULL)
354     *pat = tpat;
355   else
356     (*endpat)->next = tpat;
357   *endpat = tpat;
358 }  
359
360 /* Issue warnings for macro argument names seen inside strings.  */
361 static void
362 warn_trad_stringify (pfile, p, len, argc, argv)
363      cpp_reader *pfile;
364      U_CHAR *p;
365      size_t len;
366      unsigned int argc;
367      const struct arg *argv;
368 {
369   U_CHAR *limit;
370   unsigned int i;
371
372   limit = p + len;
373   for (;;)
374     {
375       while (p < limit && !is_idstart (*p)) p++;
376       if (p >= limit)
377         break;
378
379       for (i = 0; i < argc; i++)
380         if (!strncmp (p, argv[i].name, argv[i].len)
381             && ! is_idchar (p[argv[i].len]))
382           {
383             cpp_warning (pfile,
384                 "macro argument \"%s\" would be stringified in traditional C",
385                          argv[i].name);
386             break;
387           }
388       p++;
389       while (p < limit && is_idchar (*p)) p++;
390       if (p >= limit)
391         break;
392     }
393 }
394
395 /* Generate pat nodes for macro arguments seen inside strings.  */
396 static unsigned int
397 trad_stringify (pfile, base, len, argc, argv, pat, endpat, last)
398      cpp_reader *pfile;
399      U_CHAR *base;
400      size_t len;
401      unsigned int argc;
402      const struct arg *argv;
403      struct reflist **pat, **endpat;
404      unsigned int last;
405 {
406   U_CHAR *p, *limit;
407   unsigned int i;
408
409   p = base;
410   limit = base + len;
411   for (;;)
412     {
413     proceed:
414       while (p < limit && !is_idstart (*p)) p++;
415       if (p >= limit)
416         break;
417
418       for (i = 0; i < argc; i++)
419         if (!strncmp (p, argv[i].name, argv[i].len)
420             && ! is_idchar (p[argv[i].len]))
421           {
422             if (CPP_WTRADITIONAL (pfile))
423               cpp_warning (pfile, "macro argument \"%s\" is stringified",
424                            argv[i].name);
425             /* Write out the string up to this point, and add a pat
426                node for the argument.  Note that the argument is NOT
427                stringified.  */
428             CPP_PUTS (pfile, base, p - base);
429             add_pat (pat, endpat, CPP_WRITTEN (pfile) - last, i /* argno */,
430                      !is_hspace (p[-1]) /* raw_before */,
431                      !is_hspace (p[argv[i].len]) /* raw_after */,
432                      0 /* strize */,
433                      argv[i].rest_arg);
434             last = CPP_WRITTEN (pfile);
435             base = p + argv[i].len;
436             p = base;
437             goto proceed;
438           }
439       p++;
440       while (p < limit && is_idchar (*p)) p++;
441       if (p >= limit)
442         break;
443     }
444   CPP_PUTS (pfile, base, p - base);
445   return last;
446 }
447
448 /* Read a replacement list for an object-like macro, and build the
449    object_defn structure.  LIST contains the replacement list,
450    beginning at 1.  */
451 static struct object_defn *
452 collect_objlike_expansion (pfile, list)
453      cpp_reader *pfile;
454      cpp_toklist *list;
455 {
456   struct object_defn *defn;
457   unsigned int i;
458   unsigned int start;
459   int last_was_paste = 0;
460   U_CHAR *exp;
461   size_t len;
462
463   /* We copy the expansion text into the token_buffer, then out to
464      its proper home.  */
465   start = CPP_WRITTEN (pfile);
466   CPP_PUTS (pfile, "\r ", 2);
467
468   for (i = 1; i < list->tokens_used; i++)
469     {
470       switch (list->tokens[i].type)
471         {
472         case CPP_EOF:
473           cpp_ice (pfile, "EOF in collect_expansion");
474           /* fall through */
475         case CPP_VSPACE:
476           goto done;
477
478         case CPP_PASTE:
479           /* ## is not special if it appears right after another ##;
480              nor is it special if -traditional.  */
481           if (last_was_paste || CPP_TRADITIONAL (pfile))
482             break;
483           if (i == 1)
484             cpp_error (pfile, "`##' at start of macro definition");
485
486           last_was_paste = 1;
487           continue;
488
489         default:;
490         }
491
492       if (i > 1 && !last_was_paste
493           && (list->tokens[i].flags & PREV_WHITESPACE))
494         CPP_PUTC (pfile, ' ');
495
496       CPP_PUTS (pfile,
497                 list->tokens[i].val.name.offset + list->namebuf,
498                 list->tokens[i].val.name.len);
499       last_was_paste = 0;
500     }
501  done:
502
503   if (last_was_paste)
504     cpp_error (pfile, "`##' at end of macro definition");
505
506   CPP_PUTS (pfile, "\r ", 2);
507   len = CPP_WRITTEN (pfile) - start;
508   CPP_SET_WRITTEN (pfile, start);
509
510   if (len <= 4)
511     cpp_ice (pfile, "empty object-like macro went through full #define");
512
513   exp = (U_CHAR *) xmalloc (len + 1);
514   memcpy (exp, pfile->token_buffer + start, len);
515   exp[len] = '\0';
516
517   defn = (struct object_defn *) xmalloc (sizeof (struct object_defn));
518   defn->length = len;
519   defn->expansion = exp;
520
521   return defn;
522 }
523
524 /* Read a replacement list for a function-like macro, and build the
525    funct_defn structure.  LIST contains the replacement list,
526    beginning at REPLACEMENT.  ARGLIST specifies the formal parameters
527    to look for in the text of the definition.  */
528
529 static struct funct_defn *
530 collect_funlike_expansion (pfile, list, arglist, replacement)
531      cpp_reader *pfile;
532      cpp_toklist *list;
533      struct arglist *arglist;
534      unsigned int replacement;
535 {
536   struct funct_defn *defn;
537   struct reflist *pat = 0, *endpat = 0;
538   enum cpp_ttype token;
539   unsigned int start, last;
540   unsigned int i;
541   int j, argc;
542   size_t len;
543   const struct arg *argv;
544   U_CHAR *tok, *exp;
545   enum { START = 0, NORM, ARG, STRIZE, PASTE } last_token = START;
546
547   argv = arglist->argv;
548   argc = arglist->argc;
549
550   /* We copy the expansion text into the token_buffer, then out to
551      its proper home.  */
552   last = start = CPP_WRITTEN (pfile);
553   CPP_PUTS (pfile, "\r ", 2);
554
555   for (i = replacement; i < list->tokens_used; i++)
556     {
557       token = list->tokens[i].type;
558       tok = list->tokens[i].val.name.offset + list->namebuf;
559       len = list->tokens[i].val.name.len;
560       switch (token)
561         {
562         case CPP_EOF:
563           cpp_ice (pfile, "EOF in collect_expansion");
564           /* fall through */
565         case CPP_VSPACE:
566           goto done;
567
568         case CPP_HASH:
569           /* # is special in function-like macros with no args.
570              (6.10.3.2 para 1.)  However, it is not special after
571              PASTE. (Implied by 6.10.3.3 para 4.)  Nor is it special
572              if -traditional.  */
573           if (last_token == PASTE || CPP_TRADITIONAL (pfile))
574             break;
575           last_token = STRIZE;
576           continue;
577
578         case CPP_PASTE:
579           /* ## is not special if it appears right after another ##;
580              nor is it special if -traditional.  */
581           if (last_token == PASTE || CPP_TRADITIONAL (pfile))
582             break;
583
584           if (last_token == START)
585             cpp_error (pfile, "`##' at start of macro definition");
586           else if (last_token == ARG)
587             /* If the last token was an argument, mark it raw_after.  */
588             endpat->raw_after = 1;
589           else if (last_token == STRIZE)
590             /* Oops - that wasn't a stringify operator.  */
591             CPP_PUTC (pfile, '#');
592
593           last_token = PASTE;
594           continue;
595
596         default:;
597         }
598
599       if (last_token != PASTE && last_token != START
600           && (list->tokens[i].flags & PREV_WHITESPACE))
601         CPP_PUTC (pfile, ' ');
602       if (last_token == ARG && CPP_TRADITIONAL (pfile)
603           && !(list->tokens[i].flags & PREV_WHITESPACE))
604         endpat->raw_after = 1;
605
606       switch (token)
607         {
608         case CPP_STRING:
609         case CPP_CHAR:
610           if (argc == 0)
611             goto norm;
612           if (CPP_TRADITIONAL (pfile))
613             {
614               last = trad_stringify (pfile, tok, len, argc, argv,
615                                      &pat, &endpat, last);
616               break;
617             }
618           else
619             {
620               if (CPP_WTRADITIONAL (pfile))
621                 warn_trad_stringify (pfile, tok, len, argc, argv);
622               goto norm;
623             }
624           
625         case CPP_NAME:
626           for (j = 0; j < argc; j++)
627             if (argv[j].len == len
628                 && !strncmp (tok, argv[j].name, argv[j].len))
629               goto addref;
630
631           /* fall through */
632         default:
633         norm:
634           if (last_token == STRIZE)
635             cpp_error (pfile, "# is not followed by a macro argument name");
636           CPP_PUTS (pfile, tok, len);
637           last_token = NORM;
638         }
639       continue;
640
641     addref:
642       {
643         int raw_before = (last_token == PASTE
644                           || (CPP_TRADITIONAL (pfile)
645                               && !(list->tokens[i].flags & PREV_WHITESPACE)));
646       
647         add_pat (&pat, &endpat,
648                  CPP_WRITTEN (pfile) - last /* nchars */, j /* argno */,
649                  raw_before, 0 /* raw_after */,
650                  (last_token == STRIZE), argv[j].rest_arg);
651       
652         last = CPP_WRITTEN (pfile);
653       }
654       last_token = ARG;
655     }
656  done:
657
658   if (last_token == STRIZE)
659     cpp_error (pfile, "`#' is not followed by a macro argument name");
660   else if (last_token == PASTE)
661     cpp_error (pfile, "`##' at end of macro definition");
662
663     CPP_PUTS (pfile, "\r ", 2);
664   len = CPP_WRITTEN (pfile) - start;
665   CPP_SET_WRITTEN (pfile, start);
666
667   exp = (U_CHAR *) xmalloc (len + 1);
668   memcpy (exp, pfile->token_buffer + start, len);
669   exp[len] = '\0';
670
671   defn = (struct funct_defn *) xmalloc (sizeof (struct funct_defn));
672   defn->length = len;
673   defn->expansion = exp;
674   defn->pattern = pat;
675   defn->rest_args = argc && argv[argc - 1].rest_arg;
676   defn->nargs = argc;
677   defn->argnames = arglist->namebuf;
678   if (argv)
679     free ((PTR) argv);
680   return defn;
681 }
682
683 /* Is argument NEW, which has just been added to the argument list,
684    a duplicate of a previous argument name?  */
685 static int
686 duplicate_arg_p (args, new)
687      U_CHAR *args, *new;
688 {
689   size_t newlen = strlen (new) + 1;
690   size_t oldlen;
691
692   while (args < new)
693     {
694       oldlen = strlen (args) + 1;
695       if (!memcmp (args, new, MIN (oldlen, newlen)))
696         return 1;
697       args += oldlen;
698     }
699   return 0;
700 }
701
702 static unsigned int
703 collect_params (pfile, list, arglist)
704      cpp_reader *pfile;
705      cpp_toklist *list;
706      struct arglist *arglist;
707 {
708   struct arg *argv = 0;
709   U_CHAR *namebuf, *p, *tok;
710   unsigned int len, argslen;
711   unsigned int argc, a, i, j;
712
713   /* The formal parameters list starts at token 1.  */
714   if (list->tokens[1].type != CPP_OPEN_PAREN)
715     {
716       cpp_ice (pfile, "first token = %d not %d in collect_formal_parameters",
717                list->tokens[1].type, CPP_OPEN_PAREN);
718       return 0;
719     }
720
721   /* Scan once and count the number of parameters; also check for
722      syntax errors here.  */
723   argc = 0;
724   argslen = 0;
725   for (i = 2; i < list->tokens_used; i++)
726     switch (list->tokens[i].type)
727       {
728       case CPP_NAME:
729         argslen += list->tokens[i].val.name.len + 1;
730         argc++;
731         break;
732       case CPP_COMMA:
733         break;
734       case CPP_CLOSE_PAREN:
735         goto scanned;
736       case CPP_VSPACE:
737         cpp_error_with_line (pfile, list->line, list->tokens[i].col,
738                              "missing right paren in macro argument list");
739         return 0;
740
741       default:
742         cpp_error_with_line (pfile, list->line, list->tokens[i].col,
743                              "syntax error in #define");
744         return 0;
745
746       case CPP_ELLIPSIS:
747         if (list->tokens[i-1].type != CPP_NAME)
748           {
749             argslen += sizeof "__VA_ARGS__";
750             argc++;
751           }
752         i++;
753         if (list->tokens[i].type != CPP_CLOSE_PAREN)
754           {
755             cpp_error_with_line (pfile, list->line, list->tokens[i].col,
756                                  "another parameter follows \"...\"");
757             return 0;
758           }
759         goto scanned;
760       }
761
762   cpp_ice (pfile, "collect_params: unreachable - i=%d, ntokens=%d, type=%d",
763            i, list->tokens_used, list->tokens[i-1].type);
764   return 0;
765
766  scanned:
767   if (argc == 0)        /* function-like macro, no arguments */
768     {
769       arglist->argc = 0;
770       arglist->argv = 0;
771       arglist->namebuf = 0;
772       return i + 1;
773     }
774   if (argslen == 0)
775     {
776       cpp_ice (pfile, "collect_params: argc=%d argslen=0", argc);
777       return 0;
778     }
779
780   /* Now allocate space and copy the suckers.  */
781   argv = (struct arg *) xmalloc (argc * sizeof (struct arg));
782   namebuf = (U_CHAR *) xmalloc (argslen);
783   p = namebuf;
784   a = 0;
785   for (j = 2; j < i; j++)
786     switch (list->tokens[j].type)
787       {
788       case CPP_NAME:
789         tok = list->tokens[j].val.name.offset + list->namebuf;
790         len = list->tokens[j].val.name.len;
791         memcpy (p, tok, len);
792         p[len] = '\0';
793         if (duplicate_arg_p (namebuf, p))
794           {
795             cpp_error (pfile, "duplicate macro argument name \"%s\"", tok);
796             a++;
797             break;
798           }
799         if (CPP_PEDANTIC (pfile) && CPP_OPTION (pfile, c99)
800             && len == sizeof "__VA_ARGS__" - 1
801             && !strcmp (p, "__VA_ARGS__"))
802           cpp_pedwarn (pfile,
803         "C99 does not permit use of __VA_ARGS__ as a macro argument name");
804         argv[a].len = len;
805         argv[a].name = p;
806         argv[a].rest_arg = 0;
807         p += len;
808         a++;
809         break;
810
811       case CPP_COMMA:
812         break;
813
814       case CPP_ELLIPSIS:
815         if (list->tokens[j-1].type != CPP_NAME)
816           {
817             if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
818               cpp_pedwarn (pfile, "C89 does not permit varargs macros");
819
820             argv[a].len = sizeof "__VA_ARGS__" - 1;
821             argv[a].name = p;
822             argv[a].rest_arg = 1;
823             strcpy (p, "__VA_ARGS__");
824           }
825         else
826           {
827             if (CPP_PEDANTIC (pfile))
828               cpp_pedwarn (pfile,
829                            "ISO C does not permit named varargs macros");
830             argv[a-1].rest_arg = 1;
831           }
832         break;
833
834       default:
835         cpp_ice (pfile, "collect_params: impossible token type %d",
836                  list->tokens[j].type);
837       }
838
839   arglist->argc = argc;
840   arglist->argv = argv;
841   arglist->namebuf = namebuf;
842   return i + 1;
843 }
844
845 /* Create a definition for a macro.  The replacement text (including
846    formal parameters if present) is in LIST.  If FUNLIKE is true, this
847    is a function-like macro.  */
848
849 int
850 _cpp_create_definition (pfile, list, hp)
851      cpp_reader *pfile;
852      cpp_toklist *list;
853      HASHNODE *hp;
854 {
855   struct funct_defn *fdefn = 0;
856   struct object_defn *odefn = 0;
857   enum node_type ntype;
858   int ok;
859
860   /* Special-case a few simple and common idioms:
861      #define TOKEN   // nothing
862      #define TOKEN TOKEN
863
864      Might also be good to special-case these:
865
866      #define FUNC()  // nothing
867      #define FUNC(a, b, ...) // nothing
868      #define FUNC(a, b, c) FUNC(a, b, c)  */
869
870   if (list->tokens_used == 2)
871     ntype = T_EMPTY;    /* Empty definition of object-like macro.  */
872   else if (list->tokens_used == 3 && list->tokens[1].type == CPP_NAME
873            && list->tokens[0].val.name.len == list->tokens[1].val.name.len
874            && !strncmp (list->tokens[0].val.name.offset + list->namebuf,
875                         list->tokens[1].val.name.offset + list->namebuf,
876                         list->tokens[0].val.name.len))
877     ntype = T_IDENTITY;  /* Object like macro defined to itself.  */
878
879   /* The macro is function-like only if the next character,
880      with no intervening whitespace, is '('.  */
881   else if (list->tokens[1].type == CPP_OPEN_PAREN
882            && ! (list->tokens[1].flags & PREV_WHITESPACE))
883     {
884       struct arglist args;
885       int replacement;
886
887       replacement = collect_params (pfile, list, &args);
888       if (replacement == 0)
889         return 0;
890       fdefn = collect_funlike_expansion (pfile, list, &args, replacement);
891       if (fdefn == 0)
892         return 0;
893
894       ntype = T_FMACRO;
895     }
896
897   /* Otherwise it is an object-like macro, and C99 requires
898      whitespace after the name (6.10.3 para 3).  */
899   else
900     {
901       if (! (list->tokens[1].flags & PREV_WHITESPACE))
902         cpp_pedwarn (pfile,
903                      "The C standard requires whitespace after #define %s",
904                      hp->name);
905
906       odefn = collect_objlike_expansion (pfile, list);
907       if (odefn == 0)
908         return 0;
909
910       ntype = T_MACRO;
911     }
912
913   if (ntype == T_EMPTY || ntype == T_IDENTITY)
914     {
915       odefn = xmalloc (sizeof (struct object_defn));
916       odefn->length = 0;
917       odefn->expansion = 0;
918     }
919
920   /* Check for a redefinition, and its legality.  Redefining a macro
921      of whatever stripe is ok if the definitions are the same.
922      Redefining a built-in _constant_ (T_CONST or T_XCONST) is ok only
923      with -D.  Otherwise a redefinition is not ok.  */
924
925   switch (hp->type)
926     {
927     case T_VOID:  ok = 1; break;
928     default:      ok = 0; break;
929
930     case T_MACRO:
931       ok = (ntype == hp->type
932             && odefn->length == hp->value.odefn->length
933             && !strncmp (odefn->expansion, hp->value.odefn->expansion,
934                          odefn->length));
935       break;
936     case T_FMACRO:
937       ok = (ntype == hp->type
938             && !compare_defs (pfile, fdefn, hp->value.fdefn));
939       break;
940     case T_IDENTITY:
941     case T_EMPTY:
942       ok = (ntype == hp->type);
943       break;
944     case T_CONST:
945     case T_XCONST:
946       ok = ! pfile->done_initializing;
947       break;
948     }
949
950   /* Print the warning or error if it's not ok.  */
951   if (! ok)
952     {
953       cpp_pedwarn (pfile, "\"%s\" redefined", hp->name);
954       if (pfile->done_initializing)
955         {
956           const char *file;
957           unsigned int line, col;
958           if (hp->type == T_FMACRO)
959             {
960               file = hp->value.fdefn->file;
961               line = hp->value.fdefn->line;
962               col  = hp->value.fdefn->col;
963             }
964           else
965             {
966               file = hp->value.odefn->file;
967               line = hp->value.odefn->line;
968               col  = hp->value.odefn->col;
969             }
970         cpp_pedwarn_with_file_and_line (pfile, file, line, col,
971                         "this is the location of the previous definition");
972         }
973     }
974
975   /* And replace the old definition (if any).  */
976
977   _cpp_free_definition (hp);
978
979   hp->type = ntype;
980   if (ntype == T_FMACRO)
981     {
982       fdefn->file = CPP_BUFFER (pfile)->nominal_fname;
983       fdefn->line = list->line;
984       fdefn->col  = list->tokens[0].col;
985       hp->value.fdefn = fdefn;
986     }
987   else
988     {
989       odefn->file = CPP_BUFFER (pfile)->nominal_fname;
990       odefn->line = list->line;
991       odefn->col  = list->tokens[0].col;
992       hp->value.odefn = odefn;
993     }
994   return 1;
995 }
996
997 /*
998  * Parse a macro argument and append the info on PFILE's token_buffer.
999  * REST_ARGS means to absorb the rest of the args.
1000  * Return nonzero to indicate a syntax error.
1001  */
1002
1003 static enum cpp_ttype
1004 macarg (pfile, rest_args)
1005      cpp_reader *pfile;
1006      int rest_args;
1007 {
1008   int paren = 0;
1009   enum cpp_ttype token;
1010
1011   /* Try to parse as much of the argument as exists at this
1012      input stack level.  */
1013   for (;;)
1014     {
1015       token = cpp_get_token (pfile);
1016       switch (token)
1017         {
1018         case CPP_EOF:
1019           /* We've hit end of file; this is an error.
1020              Caller will report it.  */
1021           return token;
1022         case CPP_OPEN_PAREN:
1023           paren++;
1024           break;
1025         case CPP_CLOSE_PAREN:
1026           if (--paren < 0)
1027             goto found;
1028           break;
1029         case CPP_COMMA:
1030           /* if we've returned to lowest level and
1031              we aren't absorbing all args */
1032           if (paren == 0 && rest_args == 0)
1033             goto found;
1034           break;
1035         found:
1036           /* Remove ',' or ')' from argument buffer.  */
1037           CPP_ADJUST_WRITTEN (pfile, -1);
1038           return token;
1039         default:;
1040         }
1041     }
1042 }
1043 \f
1044
1045 static const char * const monthnames[] =
1046 {
1047   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1048   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1049 };
1050
1051 /* Place into PFILE a quoted string representing the string SRC.
1052    Caller must reserve enough space in pfile->token_buffer.  */
1053
1054 void
1055 _cpp_quote_string (pfile, src)
1056      cpp_reader *pfile;
1057      const char *src;
1058 {
1059   U_CHAR c;
1060
1061   CPP_PUTC_Q (pfile, '\"');
1062   for (;;)
1063     switch ((c = *src++))
1064       {
1065       default:
1066         if (ISPRINT (c))
1067           CPP_PUTC_Q (pfile, c);
1068         else
1069           {
1070             sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
1071             CPP_ADJUST_WRITTEN (pfile, 4);
1072           }
1073         break;
1074
1075       case '\"':
1076       case '\\':
1077         CPP_PUTC_Q (pfile, '\\');
1078         CPP_PUTC_Q (pfile, c);
1079         break;
1080       
1081       case '\0':
1082         CPP_PUTC_Q (pfile, '\"');
1083         return;
1084       }
1085 }
1086
1087 /*
1088  * expand things like __FILE__.  Place the expansion into the output
1089  * buffer *without* rescanning.
1090  */
1091
1092 #define DSC(str) (const U_CHAR *)str, sizeof str - 1
1093 static void
1094 special_symbol (pfile, hp)
1095      cpp_reader *pfile;
1096      HASHNODE *hp;
1097 {
1098   const char *buf;
1099   cpp_buffer *ip;
1100
1101   switch (hp->type)
1102     {
1103     case T_FILE:
1104     case T_BASE_FILE:
1105       ip = cpp_file_buffer (pfile);
1106       if (ip == NULL)
1107         {
1108           CPP_PUTS (pfile, "\"\"", 2);
1109           return;
1110         }
1111       if (hp->type == T_BASE_FILE)
1112         while (CPP_PREV_BUFFER (ip) != NULL)
1113           ip = CPP_PREV_BUFFER (ip);
1114
1115       buf = ip->nominal_fname;
1116       CPP_RESERVE (pfile, 3 + 4 * strlen (buf));
1117       _cpp_quote_string (pfile, buf);
1118       return;
1119
1120     case T_INCLUDE_LEVEL:
1121       {
1122         int true_indepth = 0;
1123         ip = cpp_file_buffer (pfile);
1124         while (ip)
1125           {
1126             true_indepth++;
1127             ip = CPP_PREV_BUFFER (ip);
1128           }
1129
1130         CPP_RESERVE (pfile, 10);
1131         sprintf (CPP_PWRITTEN (pfile), "%d", true_indepth);
1132         CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
1133         return;
1134       }
1135
1136     case T_STDC:
1137 #ifdef STDC_0_IN_SYSTEM_HEADERS
1138       ip = cpp_file_buffer (pfile);
1139       if (ip && ip->system_header_p
1140           && !cpp_defined (pfile, DSC("__STRICT_ANSI__")))
1141         {
1142           CPP_PUTC (pfile, '0');
1143           return;
1144         }
1145 #endif
1146     constant:
1147       buf = hp->value.cpval;
1148       if (!buf || *buf == '\0')
1149         return;
1150
1151       CPP_PUTS (pfile, buf, strlen (buf));
1152       return;
1153
1154     case T_SPECLINE:
1155       ip = cpp_file_buffer (pfile);
1156       if (ip == NULL)
1157         {
1158           CPP_PUTC (pfile, '0');
1159           return;
1160         }
1161       CPP_RESERVE (pfile, 10);
1162       sprintf (CPP_PWRITTEN (pfile), "%u", CPP_BUF_LINE (ip));
1163       CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
1164       return;
1165
1166     case T_DATE:
1167     case T_TIME:
1168       /* Generate both __DATE__ and __TIME__, stuff them into their
1169          respective hash nodes, and mark the nodes T_XCONST so we
1170          don't have to do this again.  We don't generate these strings
1171          at init time because time() and localtime() are very slow on
1172          some systems.  */
1173       {
1174         time_t tt = time (NULL);
1175         struct tm *tb = localtime (&tt);
1176         HASHNODE *d, *t;
1177
1178         if (hp->type == T_DATE)
1179           d = hp, t = _cpp_lookup (pfile, DSC("__TIME__"));
1180         else
1181           t = hp, d = _cpp_lookup (pfile, DSC("__DATE__"));
1182
1183         d->value.cpval = xmalloc (sizeof "'Oct 11 1347'");
1184         sprintf ((char *)d->value.cpval, "\"%s %2d %4d\"",
1185                  monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
1186         d->type = T_XCONST;
1187
1188         t->value.cpval = xmalloc (sizeof "'12:34:56'");
1189         sprintf ((char *)t->value.cpval, "\"%02d:%02d:%02d\"",
1190                  tb->tm_hour, tb->tm_min, tb->tm_sec);
1191         t->type = T_XCONST;
1192         goto constant;
1193       }
1194
1195     case T_POISON:
1196       cpp_error (pfile, "attempt to use poisoned `%s'.", hp->name);
1197       CPP_PUTC (pfile, '0');
1198       break;
1199
1200     default:
1201       cpp_ice (pfile, "invalid special hash type");
1202       return;
1203     }
1204 }
1205 #undef DSC
1206
1207 /* Expand a macro call.
1208    HP points to the symbol that is the macro being called.
1209    Put the result of expansion onto the input stack
1210    so that subsequent input by our caller will use it.
1211
1212    If macro wants arguments, caller has already verified that
1213    an argument list follows; arguments come from the input stack.  */
1214
1215 void
1216 _cpp_macroexpand (pfile, hp)
1217      cpp_reader *pfile;
1218      HASHNODE *hp;
1219 {
1220   const struct funct_defn *defn;
1221   struct argdata *args;
1222   unsigned int old_written;
1223   int i;
1224
1225   /* Object like macro - most common case.  */
1226   if (hp->type == T_MACRO)
1227     {
1228       push_macro_expansion (pfile, hp->value.odefn->expansion,
1229                             hp->value.odefn->length, hp);
1230       return;
1231     }
1232
1233   /* Or might it be a constant string?  */
1234   if (hp->type == T_CONST || hp->type == T_XCONST)
1235     {
1236       const U_CHAR *cpval = hp->value.cpval;
1237       if (cpval && *cpval != '\0')
1238         push_macro_expansion (pfile, cpval, strlen (cpval), hp);
1239       return;
1240     }
1241
1242   /* Or a special symbol?  */
1243   if (hp->type != T_FMACRO)
1244     {
1245       U_CHAR *xbuf;
1246       unsigned int len;
1247
1248       old_written = CPP_WRITTEN (pfile);
1249       special_symbol (pfile, hp);
1250       len = CPP_WRITTEN (pfile) - old_written;
1251       CPP_SET_WRITTEN (pfile, old_written);
1252       if (len == 0)
1253         return;
1254
1255       xbuf = (U_CHAR *) xmalloc (len + 1);
1256       memcpy (xbuf, CPP_PWRITTEN (pfile), len);
1257       xbuf[len] = '\0';
1258       push_macro_expansion (pfile, xbuf, len, hp);
1259       return;
1260     }
1261
1262   /* Okay, it's a full-on function-like macro...  */
1263   old_written = CPP_WRITTEN (pfile);
1264   defn = hp->value.fdefn;
1265
1266   args = alloca (MAX (defn->nargs, 1) * sizeof (struct argdata));
1267   for (i = 0; i < MAX (defn->nargs, 1); i++)
1268     {
1269       args[i].raw = args[i].expanded = 0;
1270       args[i].raw_length = 0;
1271       args[i].expand_length = args[i].stringified_length = -1;
1272     }
1273
1274   pfile->output_escapes++;
1275   scan_arguments (pfile, defn, args, hp->name);
1276
1277   /* If macro wants zero args, we parsed the arglist for checking only.
1278      Read directly from the macro definition.  */
1279   if (defn->nargs == 0 || defn->pattern == 0)
1280     {
1281       /* If the defn is the empty string, don't bother pushing it.  */
1282       if (defn->length > 4)
1283         push_macro_expansion (pfile, defn->expansion, defn->length, hp);
1284     }
1285   else
1286     funlike_macroexpand (pfile, hp, args);
1287
1288   CPP_SET_WRITTEN (pfile, old_written);
1289   pfile->output_escapes--;
1290 }
1291
1292 static void
1293 scan_arguments (pfile, defn, args, name)
1294      cpp_reader *pfile;
1295      const struct funct_defn *defn;
1296      struct argdata *args;
1297      const U_CHAR *name;
1298 {
1299   enum cpp_ttype token;
1300   unsigned int start_line, start_column;
1301   unsigned int nargs = defn->nargs;
1302   unsigned int i;
1303   
1304   cpp_buffer *ip = cpp_file_buffer (pfile);
1305   if (ip)
1306     {
1307       start_line = CPP_BUF_LINE (ip);
1308       start_column = CPP_BUF_COL (ip);
1309     }
1310   else
1311     start_line = start_column = 0;
1312
1313   /* Parse all the macro args that are supplied.  I counts them.  The
1314      first NARGS args are stored in ARGS.  The rest are discarded.  If
1315      rest_args is set then we assume macarg absorbed the rest of the
1316      args.  */
1317   i = 0;
1318
1319   /* Skip over the opening parenthesis.  */
1320   CPP_OPTION (pfile, discard_comments)++;
1321   pfile->no_macro_expand++;
1322   pfile->no_directives++;
1323
1324   token = cpp_get_non_space_token (pfile);
1325   if (token != CPP_OPEN_PAREN)
1326     cpp_ice (pfile, "macroexpand: unexpected token %d (wanted LPAREN)",
1327              token);
1328   CPP_ADJUST_WRITTEN (pfile, -1);
1329
1330   token = CPP_EOF;
1331   do
1332     {
1333       if (i < MAX (nargs, 1))
1334         {
1335           args[i].raw = CPP_WRITTEN (pfile);
1336           token = macarg (pfile, (i == nargs - 1 && defn->rest_args));
1337           args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
1338         }
1339       else
1340         token = macarg (pfile, 0);
1341       if (token == CPP_EOF)
1342         cpp_error_with_line (pfile, start_line, start_column,
1343                              "unterminated macro call");
1344       i++;
1345     }
1346   while (token == CPP_COMMA);
1347   CPP_OPTION (pfile, discard_comments)--;
1348   pfile->no_macro_expand--;
1349   pfile->no_directives--;
1350   if (token != CPP_CLOSE_PAREN)
1351     return;
1352
1353   /* foo ( ) is equivalent to foo () unless foo takes exactly one
1354      argument, in which case the former is allowed and the latter
1355      is not.  XXX C99 is silent on this rule, but it seems
1356      inconsistent to me.  */
1357   if (i == 1 && nargs == 0)
1358     {
1359       register U_CHAR *bp = ARG_BASE + args[0].raw;
1360       register U_CHAR *lim = bp + args[0].raw_length;
1361       while (bp != lim && is_space(*bp))
1362         bp++;
1363       if (bp == lim)
1364         i = 0;
1365     }
1366
1367   /* Don't output an error message if we have already output one for
1368      a parse error above.  */
1369   if (nargs == 0 && i > 0)
1370     {
1371       cpp_error (pfile, "arguments given to macro `%s'", name);
1372     }
1373   else if (i < nargs)
1374     {
1375       /* traditional C allows foo() if foo wants one argument.  */
1376       if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
1377         ;
1378       /* the rest args token is allowed to absorb 0 tokens */
1379       else if (i == nargs - 1 && defn->rest_args)
1380         ;
1381       else if (i == 0)
1382         cpp_error (pfile, "macro `%s' used without args", name);
1383       else if (i == 1)
1384         cpp_error (pfile, "macro `%s' used with just one arg", name);
1385       else
1386         cpp_error (pfile, "macro `%s' used with only %d args", name, i);
1387     }
1388   else if (i > nargs)
1389     {
1390       cpp_error (pfile, "macro `%s' used with too many (%d) args", name, i);
1391     }
1392 }
1393
1394 static void
1395 stringify (pfile, arg)
1396      cpp_reader *pfile;
1397      struct argdata *arg;
1398 {
1399   int arglen = arg->raw_length;
1400   int escaped = 0;
1401   int in_string = 0;
1402   int c;
1403   int i;
1404   /* Initially need_space is -1.  Otherwise, 1 means the previous
1405      character was a space, but we suppressed it; 0 means the previous
1406      character was a non-space.  */
1407   int need_space = -1;
1408   i = 0;
1409   arg->stringified = CPP_WRITTEN (pfile);
1410   CPP_PUTC (pfile, '\"');       /* insert beginning quote */
1411   for (; i < arglen; i++)
1412     {
1413       c = (ARG_BASE + arg->raw)[i];
1414
1415       if (!in_string)
1416         {
1417           /* Delete "\r " and "\r-" escapes.  */
1418           if (c == '\r')
1419             {
1420               i++;
1421               continue;
1422             }
1423           /* Internal sequences of whitespace are replaced by one
1424              space except within a string or char token. */
1425           else if (is_space(c))
1426             {
1427               if (need_space == 0)
1428                 need_space = 1;
1429               continue;
1430             }
1431           else if (need_space > 0)
1432             CPP_PUTC (pfile, ' ');
1433           need_space = 0;
1434         }
1435
1436       if (escaped)
1437         escaped = 0;
1438       else
1439         {
1440           if (c == '\\')
1441             escaped = 1;
1442           if (in_string)
1443             {
1444               if (c == in_string)
1445                 in_string = 0;
1446             }
1447           else if (c == '\"' || c == '\'')
1448             in_string = c;
1449         }
1450
1451       /* Escape these chars */
1452       if (c == '\"' || (in_string && c == '\\'))
1453         CPP_PUTC (pfile, '\\');
1454       if (ISPRINT (c))
1455         CPP_PUTC (pfile, c);
1456       else
1457         {
1458           CPP_RESERVE (pfile, 4);
1459           sprintf ((char *) CPP_PWRITTEN (pfile), "\\%03o", (unsigned int) c);
1460           CPP_ADJUST_WRITTEN (pfile, 4);
1461         }
1462     }
1463   CPP_PUTC (pfile, '\"');       /* insert ending quote */
1464   arg->stringified_length  = CPP_WRITTEN (pfile) - arg->stringified;
1465 }
1466
1467 static void
1468 funlike_macroexpand (pfile, hp, args)
1469      cpp_reader *pfile;
1470      HASHNODE *hp;
1471      struct argdata *args;
1472 {
1473   const struct funct_defn *defn = hp->value.fdefn;
1474   register U_CHAR *xbuf;
1475   int xbuf_len;
1476   const U_CHAR *exp = defn->expansion;
1477   int offset;   /* offset in expansion, copied a piece at a time */
1478   int totlen;   /* total amount of exp buffer filled so far */
1479   const struct reflist *ap, *last_ap;
1480   int i;
1481
1482   /* Compute length in characters of the macro's expansion.
1483      Also count number of times each arg is used.  */
1484   xbuf_len = defn->length;
1485   for (ap = defn->pattern; ap != NULL; ap = ap->next)
1486     {
1487       if (ap->stringify)
1488         {
1489           /* Stringify if it hasn't already been */
1490           if (args[ap->argno].stringified_length < 0)
1491             stringify (pfile, &args[ap->argno]);
1492           xbuf_len += args[ap->argno].stringified_length;
1493         }
1494       else if (ap->raw_before || ap->raw_after)
1495         /* Add 4 for two \r-space markers to prevent
1496            token concatenation.  */
1497         xbuf_len += args[ap->argno].raw_length + 4;
1498       else
1499         {
1500           /* We have an ordinary (expanded) occurrence of the arg.
1501              So compute its expansion, if we have not already.  */
1502           if (args[ap->argno].expand_length < 0)
1503             {
1504               args[ap->argno].expanded = CPP_WRITTEN (pfile);
1505               _cpp_expand_to_buffer (pfile, ARG_BASE + args[ap->argno].raw,
1506                                      args[ap->argno].raw_length);
1507
1508               args[ap->argno].expand_length
1509                 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
1510             }
1511
1512           /* Add 4 for two \r-space markers to prevent
1513              token concatenation.  */
1514           xbuf_len += args[ap->argno].expand_length + 4;
1515         }
1516     }
1517
1518   xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1519
1520   /* Generate in XBUF the complete expansion with arguments
1521      substituted in.  TOTLEN is the total size generated so far.
1522      OFFSET is the index in the definition of where we are copying
1523      from.  */
1524   offset = totlen = 0;
1525   for (last_ap = NULL, ap = defn->pattern; ap != NULL;
1526        last_ap = ap, ap = ap->next)
1527     {
1528       register struct argdata *arg = &args[ap->argno];
1529       int count_before = totlen;
1530
1531       /* Add chars to XBUF.  */
1532       i = ap->nchars;
1533       memcpy (&xbuf[totlen], &exp[offset], i);
1534       totlen += i;
1535       offset += i;
1536
1537       /* If followed by an empty rest arg with concatenation,
1538          delete the last run of nonwhite chars.  */
1539       if (arg->raw_length == 0 && totlen > count_before
1540           && ((ap->rest_args && ap->raw_before)
1541               || (last_ap != NULL && last_ap->rest_args
1542                   && last_ap->raw_after)))
1543         {
1544           /* Delete final whitespace.  */
1545           while (totlen > count_before && is_space(xbuf[totlen - 1]))
1546             totlen--;
1547
1548           /* Delete the nonwhites before them.  */
1549           while (totlen > count_before && !is_space(xbuf[totlen - 1]))
1550             totlen--;
1551         }
1552
1553       if (ap->stringify != 0)
1554         {
1555           memcpy (xbuf + totlen, ARG_BASE + arg->stringified,
1556                   arg->stringified_length);
1557           totlen += arg->stringified_length;
1558         }
1559       else if (ap->raw_before || ap->raw_after)
1560         {
1561           U_CHAR *p1 = ARG_BASE + arg->raw;
1562           U_CHAR *l1 = p1 + arg->raw_length;
1563           if (ap->raw_before)
1564             {
1565               /* Arg is concatenated before: delete leading whitespace,
1566                  whitespace markers, and no-reexpansion markers.  */
1567               while (p1 != l1)
1568                 {
1569                   if (is_space(p1[0]))
1570                     p1++;
1571                   else if (p1[0] == '\r')
1572                     p1 += 2;
1573                   else
1574                     break;
1575                 }
1576             }
1577           if (ap->raw_after)
1578             {
1579               /* Arg is concatenated after: delete trailing whitespace,
1580                  whitespace markers, and no-reexpansion markers.  */
1581               while (p1 != l1)
1582                 {
1583                   if (is_space(l1[-1]))
1584                     l1--;
1585                   else if (l1[-1] == '\r')
1586                     l1--;
1587                   else if (l1[-1] == '-')
1588                     {
1589                       if (l1 != p1 + 1 && l1[-2] == '\r')
1590                         l1 -= 2;
1591                       else
1592                         break;
1593                     }
1594                   else
1595                     break;
1596                 }
1597             }
1598
1599           /* Delete any no-reexpansion marker that precedes
1600              an identifier at the beginning of the argument. */
1601           if (p1[0] == '\r' && p1[1] == '-')
1602             p1 += 2;
1603
1604           memcpy (xbuf + totlen, p1, l1 - p1);
1605           totlen += l1 - p1;
1606         }
1607       else
1608         {
1609           U_CHAR *expanded = ARG_BASE + arg->expanded;
1610           if (!ap->raw_before && totlen > 0 && arg->expand_length
1611               && unsafe_chars (pfile, xbuf[totlen - 1], expanded[0]))
1612             {
1613               xbuf[totlen++] = '\r';
1614               xbuf[totlen++] = ' ';
1615             }
1616
1617           memcpy (xbuf + totlen, expanded, arg->expand_length);
1618           totlen += arg->expand_length;
1619
1620           if (!ap->raw_after && totlen > 0 && offset < defn->length
1621               && unsafe_chars (pfile, xbuf[totlen - 1], exp[offset]))
1622             {
1623               xbuf[totlen++] = '\r';
1624               xbuf[totlen++] = ' ';
1625             }
1626         }
1627     }
1628
1629   /* if there is anything left of the definition
1630      after handling the arg list, copy that in too.  */
1631
1632   for (i = offset; i < defn->length; i++)
1633     xbuf[totlen++] = exp[i];
1634   xbuf[totlen] = 0;
1635
1636   if (totlen > xbuf_len)
1637     /* Just die - we've trashed the heap at this point.  */
1638     abort ();
1639   
1640   /* Now put the expansion on the input stack
1641      so our caller will commence reading from it.  */
1642   push_macro_expansion (pfile, xbuf, totlen, hp);
1643
1644   /* Overload buffer->mapped to indicate that xbuf needs to be freed.  */
1645   CPP_BUFFER (pfile)->mapped = 1;
1646 }
1647
1648 /* Return 1 iff a token ending in C1 followed directly by a token C2
1649    could cause mis-tokenization.  */
1650
1651 static int
1652 unsafe_chars (pfile, c1, c2)
1653      cpp_reader *pfile;
1654      int c1, c2;
1655 {
1656   /* If c2 is EOF, that's always safe.  */
1657   if (c2 == EOF)
1658     return 0;
1659
1660   switch (c1)
1661     {
1662     case EOF:
1663       /* We don't know what the previous character was.  We do know
1664          that it can't have been an idchar (or else it would have been
1665          pasted with the idchars of the macro name), and there are a
1666          number of second characters for which it doesn't matter what
1667          the first was.  */
1668       if (is_idchar (c2) || c2 == '\'' || c2 == '\"'
1669           || c2 == '(' || c2 == '[' || c2 == '{'
1670           || c2 == ')' || c2 == ']' || c2 == '}')
1671         return 0;
1672       return 1;
1673
1674     case '+':  case '-':
1675       if (c2 == c1 || c2 == '=')
1676         return 1;
1677       goto letter;
1678
1679     case 'e':  case 'E':  case 'p':  case 'P':
1680       if (c2 == '-' || c2 == '+')
1681         return 1;               /* could extend a pre-processing number */
1682       goto letter;
1683
1684     case '$':
1685       if (CPP_OPTION (pfile, dollars_in_ident))
1686         goto letter;
1687       return 0;
1688
1689     case 'L':
1690       if (c2 == '\'' || c2 == '\"')
1691         return 1;               /* Could turn into L"xxx" or L'xxx'.  */
1692       goto letter;
1693
1694     case '.':  case '0':  case '1':  case '2':  case '3':
1695     case '4':  case '5':  case '6':  case '7':  case '8':  case '9':
1696     case '_':  case 'a':  case 'b':  case 'c':  case 'd':  case 'f':
1697     case 'g':  case 'h':  case 'i':  case 'j':  case 'k':  case 'l':
1698     case 'm':  case 'n':  case 'o':  case 'q':  case 'r':  case 's':
1699     case 't':  case 'u':  case 'v':  case 'w':  case 'x':  case 'y':
1700     case 'z':  case 'A':  case 'B':  case 'C':  case 'D':  case 'F':
1701     case 'G':  case 'H':  case 'I':  case 'J':  case 'K':  case 'M':
1702     case 'N':  case 'O':  case 'Q':  case 'R':  case 'S':  case 'T':
1703     case 'U':  case 'V':  case 'W':  case 'X':  case 'Y':  case 'Z':
1704     letter:
1705     /* We're in the middle of either a name or a pre-processing number.  */
1706       return (is_idchar(c2) || c2 == '.');
1707
1708     case '<':  case '>':  case '!':  case '%':  case '#':  case ':':
1709     case '^':  case '&':  case '|':  case '*':  case '/':  case '=':
1710       return (c2 == c1 || c2 == '=');
1711     }
1712   return 0;
1713 }
1714
1715 static void
1716 push_macro_expansion (pfile, xbuf, len, hp)
1717      cpp_reader *pfile;
1718      const U_CHAR *xbuf;
1719      int len;
1720      HASHNODE *hp;
1721 {
1722   cpp_buffer *mbuf;
1723   int advance_cur = 0;
1724
1725   /* The first chars of the expansion should be a "\r " added by
1726      collect_expansion.  This is to prevent accidental token-pasting
1727      between the text preceding the macro invocation, and the macro
1728      expansion text.
1729
1730      We would like to avoid adding unneeded spaces (for the sake of
1731      tools that use cpp, such as imake).  In some common cases we can
1732      tell that it is safe to omit the space.  */
1733
1734   if (xbuf[0] == '\r' && xbuf[1] == ' '
1735       && !unsafe_chars (pfile, EOF, xbuf[2]))
1736     advance_cur = 1;
1737
1738   /* Likewise, avoid the extra space at the end of the macro expansion
1739      if this is safe.  We can do a better job here since we can know
1740      what the next char will be.  */
1741   if (len >= 3 && xbuf[len-2] == '\r' && xbuf[len-1] == ' '
1742       && !unsafe_chars (pfile, xbuf[len-3], CPP_BUF_PEEK (CPP_BUFFER (pfile))))
1743     len -= 2;
1744
1745   /* If the total expansion is "\r \r ", we must not trim both escapes.  */
1746   if (len == 2 && advance_cur)
1747     advance_cur = 0;
1748
1749   mbuf = cpp_push_buffer (pfile, xbuf, len);
1750   if (mbuf == NULL)
1751     return;
1752   if (advance_cur)
1753     mbuf->cur += 2;
1754   mbuf->macro = hp;
1755   mbuf->has_escapes = 1;
1756
1757   /* In C89, a macro cannot be expanded recursively.  Traditional C
1758      permits it, but any use in an object-like macro must lead to
1759      infinite recursion, so always follow C89 in object-like macros.
1760      Likewise, in a function-like macro it must cause infinite
1761      recursion unless we are actually doing something with the
1762      arguments.
1763
1764      Even that criterion is too weak.  The only example known where
1765      macro recursion isn't infinite is:
1766         #define bar(x,y) foo(x(y, 0))
1767         bar(bar, baz)
1768      which expands to foo(bar(baz, 0)) in C89 and
1769      foo(foo(baz(0, 0)) in K+R.  This looks pathological to me.
1770      If someone has a real-world example I would love to see it.  */
1771   if (hp->type != T_FMACRO
1772       || hp->value.fdefn->nargs == 0
1773       || hp->value.fdefn->pattern == 0
1774       || !CPP_TRADITIONAL (pfile))
1775     hp->disabled = 1;
1776 }
1777
1778 /* Return zero if two funct_defns are isomorphic.  */
1779
1780 static int
1781 compare_defs (pfile, d1, d2)
1782      cpp_reader *pfile;
1783      const struct funct_defn *d1, *d2;
1784 {
1785   const struct reflist *a1, *a2;
1786
1787   if (d1->nargs != d2->nargs)
1788     return 1;
1789   if (strcmp (d1->expansion, d2->expansion))
1790     return 1;
1791   if (CPP_PEDANTIC (pfile)
1792       && d1->argnames && d2->argnames)
1793     {
1794       U_CHAR *arg1 = d1->argnames;
1795       U_CHAR *arg2 = d2->argnames;
1796       size_t len;
1797       int i = d1->nargs;
1798       while (i--)
1799         {
1800           len = strlen (arg1) + 1;
1801           if (strcmp (arg1, arg2))
1802             return 1;
1803           arg1 += len;
1804           arg2 += len;
1805         }
1806     }
1807   for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1808        a1 = a1->next, a2 = a2->next)
1809     {
1810       if (a1->nchars != a2->nchars
1811           || a1->argno != a2->argno
1812           || a1->stringify != a2->stringify
1813           || a1->raw_before != a2->raw_before
1814           || a1->raw_after != a2->raw_after)
1815         return 1;
1816     }
1817   if (a1 != a2)
1818     return 1;
1819
1820   return 0;
1821 }
1822
1823 /* Dump the definition of macro MACRO on stdout.  The format is suitable
1824    to be read back in again. */
1825
1826 void
1827 _cpp_dump_definition (pfile, hp)
1828      cpp_reader *pfile;
1829      HASHNODE *hp;
1830 {
1831   CPP_RESERVE (pfile, hp->length + sizeof "#define ");
1832   CPP_PUTS_Q (pfile, "#define ", sizeof "#define " - 1);
1833   CPP_PUTS_Q (pfile, hp->name, hp->length);
1834
1835   if (hp->type == T_EMPTY)
1836     /* do nothing */;
1837   else if (hp->type == T_FMACRO)
1838     dump_funlike_macro (pfile, hp->value.fdefn);
1839   else
1840     {
1841       CPP_PUTC_Q (pfile, ' ');
1842
1843       if (hp->type == T_IDENTITY)
1844         CPP_PUTS (pfile, hp->name, hp->length);
1845       else if (hp->type == T_MACRO)
1846         {
1847           /* The first and last two characters of a macro expansion are
1848              always "\r "; this needs to be trimmed out.
1849              So we need length-4 chars of space, plus one for the NUL.  */
1850           CPP_RESERVE (pfile, hp->value.odefn->length - 4 + 1);
1851           CPP_PUTS_Q (pfile, hp->value.odefn->expansion + 2,
1852                       hp->value.odefn->length - 4);
1853         }
1854       else
1855         cpp_ice (pfile, "invalid hash type %d in dump_definition", hp->type);
1856     }
1857   if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
1858     CPP_PUTC (pfile, '\n');
1859 }
1860
1861 static void
1862 dump_funlike_macro (pfile, defn)
1863      cpp_reader *pfile;
1864      const struct funct_defn *defn;
1865 {
1866   const struct reflist *r;
1867   const U_CHAR **argv = (const U_CHAR **) alloca (defn->nargs *
1868                                                   sizeof(const U_CHAR *));
1869   int *argl = (int *) alloca (defn->nargs * sizeof(int));
1870   const U_CHAR *x;
1871   int i;
1872
1873   /* First extract the argument list. */
1874   x = defn->argnames;
1875   for (i = 0; i < defn->nargs; i++)
1876     {
1877       argv[i] = x;
1878       argl[i] = strlen (x);
1879       x += argl[i] + 1;
1880     }
1881       
1882   /* Now print out the argument list. */
1883   CPP_PUTC_Q (pfile, '(');
1884   for (i = 0; i < defn->nargs; i++)
1885     {
1886       CPP_RESERVE (pfile, argl[i] + 2);
1887       if (!(i == defn->nargs-1 && defn->rest_args
1888             && !strcmp (argv[i], "__VA_ARGS__")))
1889         CPP_PUTS_Q (pfile, argv[i], argl[i]);
1890       if (i < defn->nargs-1)
1891         CPP_PUTS_Q (pfile, ", ", 2);
1892     }
1893   if (defn->rest_args)
1894     CPP_PUTS (pfile, "...", 3);
1895   CPP_PUTS (pfile, ") ", 2);
1896
1897   /* Now the definition. */
1898   x = defn->expansion;
1899   for (r = defn->pattern; r; r = r->next)
1900     {
1901       i = r->nchars;
1902       if (*x == '\r') x += 2, i -= 2;
1903       /* i chars for macro text, plus the length of the macro
1904          argument name, plus one for a stringify marker, plus two for
1905          each concatenation marker. */
1906       CPP_RESERVE (pfile,
1907                    i + argl[r->argno] + r->stringify
1908                    + (r->raw_before + r->raw_after) * 2);
1909
1910       if (i > 0) CPP_PUTS_Q (pfile, x, i);
1911       if (r->raw_before)
1912         CPP_PUTS_Q (pfile, "##", 2);
1913       if (r->stringify)
1914         CPP_PUTC_Q (pfile, '#');
1915       CPP_PUTS_Q (pfile, argv[r->argno], argl[r->argno]);
1916       if (r->raw_after && !(r->next && r->next->nchars == 0
1917                             && r->next->raw_before))
1918         CPP_PUTS_Q (pfile, "##", 2);
1919
1920       x += i;
1921     }
1922
1923   i = defn->length - (x - defn->expansion) - 2;
1924   if (*x == '\r') x += 2, i -= 2;
1925   if (i > 0) CPP_PUTS (pfile, x, i);
1926 }
1927
1928 /* Dump out the hash table.  */
1929 static int
1930 dump_hash_helper (h, p)
1931      void **h;
1932      void *p;
1933 {
1934   HASHNODE *hp = (HASHNODE *)*h;
1935   cpp_reader *pfile = (cpp_reader *)p;
1936
1937   if (hp->type == T_MACRO)
1938     _cpp_dump_definition (pfile, hp);
1939   return 1;
1940 }
1941
1942 void
1943 _cpp_dump_macro_hash (pfile)
1944      cpp_reader *pfile;
1945 {
1946   htab_traverse (pfile->hashtab, dump_hash_helper, pfile);
1947 }