OSDN Git Service

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