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