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