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