OSDN Git Service

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