OSDN Git Service

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