OSDN Git Service

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