OSDN Git Service

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