OSDN Git Service

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