OSDN Git Service

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