OSDN Git Service

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