OSDN Git Service

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