OSDN Git Service

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