Add partial support for IA-64 unwind sections.
[official-gcc.git] / gcc / cpphash.c
blobfe594a2dadc3c8f1d67a41a229e4d0aec8eec19a
1 /* Part of CPP library. (Macro handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3 1999, 2000 Free Software Foundation, Inc.
4 Written by Per Bothner, 1994.
5 Based on CCCP program by Paul Rubin, June 1986
6 Adapted to ANSI C, Richard Stallman, Jan 1987
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.
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.
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.
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! */
26 #include "config.h"
27 #include "system.h"
28 #include "cpplib.h"
29 #include "hashtab.h"
30 #include "cpphash.h"
32 #undef abort
34 static unsigned int hash_HASHNODE PARAMS ((const void *));
35 static int eq_HASHNODE PARAMS ((const void *, const void *));
36 static void del_HASHNODE PARAMS ((void *));
37 static void dump_DEFINITION PARAMS ((cpp_reader *, DEFINITION *));
38 static int dump_hash_helper PARAMS ((void **, void *));
40 static void push_macro_expansion PARAMS ((cpp_reader *, const U_CHAR *,
41 int, HASHNODE *));
42 static int unsafe_chars PARAMS ((cpp_reader *, int, int));
43 static int macro_cleanup PARAMS ((cpp_buffer *, cpp_reader *));
44 static enum cpp_ttype macarg PARAMS ((cpp_reader *, int));
45 static void special_symbol PARAMS ((cpp_reader *, HASHNODE *));
46 static int compare_defs PARAMS ((cpp_reader *, DEFINITION *,
47 DEFINITION *));
49 /* Initial hash table size. (It can grow if necessary - see hashtab.c.) */
50 #define HASHSIZE 500
52 /* The arglist structure is built by create_definition to tell
53 collect_expansion where the argument names begin. That
54 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
55 would contain pointers to the strings x, y, and z.
56 collect_expansion would then build a DEFINITION node,
57 with reflist nodes pointing to the places x, y, and z had
58 appeared. So the arglist is just convenience data passed
59 between these two routines. It is not kept around after
60 the current #define has been processed and entered into the
61 hash table. */
63 struct arg
65 const U_CHAR *name;
66 unsigned int len;
67 char rest_arg;
70 struct arglist
72 U_CHAR *namebuf;
73 const struct arg *argv;
74 int argc;
78 static DEFINITION *
79 collect_objlike_expansion PARAMS ((cpp_reader *, cpp_toklist *));
80 static DEFINITION *
81 collect_funlike_expansion PARAMS ((cpp_reader *, cpp_toklist *,
82 struct arglist *, unsigned int));
83 static unsigned int collect_params PARAMS ((cpp_reader *, cpp_toklist *,
84 struct arglist *));
86 static void warn_trad_stringify PARAMS ((cpp_reader *, U_CHAR *, size_t,
87 unsigned int, const struct arg *));
88 static unsigned int trad_stringify PARAMS ((cpp_reader *, U_CHAR *, size_t,
89 unsigned int, const struct arg *,
90 struct reflist **,
91 struct reflist **, unsigned int));
92 static int duplicate_arg_p PARAMS ((U_CHAR *, U_CHAR *));
93 static void add_pat PARAMS ((struct reflist **, struct reflist **,
94 unsigned int, unsigned int, int, int, int, int));
96 /* This structure represents one parsed argument in a macro call.
97 `raw' points to the argument text as written (`raw_length' is its length).
98 `expanded' points to the argument's macro-expansion
99 (its length is `expand_length').
100 `stringified_length' is the length the argument would have
101 if stringified. */
103 /* raw and expanded are relative to ARG_BASE */
104 #define ARG_BASE ((pfile)->token_buffer)
106 struct argdata
108 /* Strings relative to pfile->token_buffer */
109 long raw, expanded, stringified;
110 int raw_length, expand_length;
111 int stringified_length;
114 static void scan_arguments PARAMS ((cpp_reader *, DEFINITION *,
115 struct argdata *, const U_CHAR *));
116 static void stringify PARAMS ((cpp_reader *, struct argdata *));
117 static void funlike_macroexpand PARAMS ((cpp_reader *, HASHNODE *,
118 struct argdata *));
120 /* Calculate hash of a string of length LEN. */
121 unsigned int
122 _cpp_calc_hash (str, len)
123 const U_CHAR *str;
124 size_t len;
126 size_t n = len;
127 unsigned int r = 0;
130 r = r * 67 + (*str++ - 113);
131 while (--n);
132 return r + len;
135 /* Calculate hash of a HASHNODE structure. */
136 static unsigned int
137 hash_HASHNODE (x)
138 const void *x;
140 const HASHNODE *h = (const HASHNODE *)x;
141 return h->hash;
144 /* Compare two HASHNODE structures. */
145 static int
146 eq_HASHNODE (x, y)
147 const void *x;
148 const void *y;
150 const HASHNODE *a = (const HASHNODE *)x;
151 const HASHNODE *b = (const HASHNODE *)y;
153 return (a->length == b->length
154 && !strncmp (a->name, b->name, a->length));
157 /* Destroy a HASHNODE. */
158 static void
159 del_HASHNODE (x)
160 void *x;
162 HASHNODE *h = (HASHNODE *)x;
164 if (h->type == T_MACRO)
165 _cpp_free_definition (h->value.defn);
166 else if (h->type == T_MCONST)
167 free ((void *) h->value.cpval);
168 free ((void *) h->name);
169 free (h);
172 /* Allocate and initialize a HASHNODE structure.
173 Caller must fill in the value field. */
175 HASHNODE *
176 _cpp_make_hashnode (name, len, type, hash)
177 const U_CHAR *name;
178 size_t len;
179 enum node_type type;
180 unsigned long hash;
182 HASHNODE *hp = (HASHNODE *) xmalloc (sizeof (HASHNODE));
183 U_CHAR *p = xmalloc (len + 1);
185 hp->type = type;
186 hp->length = len;
187 hp->name = p;
188 hp->hash = hash;
189 hp->disabled = 0;
191 memcpy (p, name, len);
192 p[len] = 0;
194 return hp;
197 /* Find the hash node for name "name", which ends at the first
198 non-identifier char.
200 If LEN is >= 0, it is the length of the name.
201 Otherwise, compute the length now. */
203 HASHNODE *
204 _cpp_lookup (pfile, name, len)
205 cpp_reader *pfile;
206 const U_CHAR *name;
207 int len;
209 const U_CHAR *bp;
210 HASHNODE dummy;
212 if (len < 0)
214 for (bp = name; is_idchar (*bp); bp++);
215 len = bp - name;
218 dummy.name = name;
219 dummy.length = len;
220 dummy.hash = _cpp_calc_hash (name, len);
222 return (HASHNODE *) htab_find_with_hash (pfile->hashtab,
223 (void *)&dummy, dummy.hash);
226 /* Find the hashtable slot for name "name". Used to insert or delete. */
228 HASHNODE **
229 _cpp_lookup_slot (pfile, name, len, insert, hash)
230 cpp_reader *pfile;
231 const U_CHAR *name;
232 int len;
233 enum insert_option insert;
234 unsigned long *hash;
236 const U_CHAR *bp;
237 HASHNODE dummy;
238 HASHNODE **slot;
240 if (len < 0)
242 for (bp = name; is_idchar (*bp); bp++)
245 len = bp - name;
248 dummy.name = name;
249 dummy.length = len;
250 dummy.hash = _cpp_calc_hash (name, len);
252 slot = (HASHNODE **) htab_find_slot_with_hash (pfile->hashtab,
253 (void *) &dummy,
254 dummy.hash, insert);
255 if (insert)
256 *hash = dummy.hash;
257 return slot;
260 /* Init the hash table. In here so it can see the hash and eq functions. */
261 void
262 _cpp_init_macro_hash (pfile)
263 cpp_reader *pfile;
265 pfile->hashtab = htab_create (HASHSIZE, hash_HASHNODE,
266 eq_HASHNODE, del_HASHNODE);
269 /* Free a DEFINITION structure. Used by delete_macro, and by
270 do_define when redefining macros. */
272 void
273 _cpp_free_definition (d)
274 DEFINITION *d;
276 struct reflist *ap, *nextap;
278 for (ap = d->pattern; ap != NULL; ap = nextap)
280 nextap = ap->next;
281 free (ap);
283 if (d->argnames)
284 free (d->argnames);
285 free (d);
288 static int
289 macro_cleanup (pbuf, pfile)
290 cpp_buffer *pbuf;
291 cpp_reader *pfile ATTRIBUTE_UNUSED;
293 HASHNODE *m = pbuf->macro;
295 m->disabled = 0;
296 if (m->type == T_FMACRO && pbuf->buf != m->value.defn->expansion)
297 free ((PTR) pbuf->buf);
298 else if (m->type != T_MACRO && m->type != T_FMACRO && m->type != T_CONST
299 && m->type != T_MCONST && m->type != T_XCONST)
300 free ((PTR) pbuf->buf);
301 return 0;
304 /* Create pat nodes. */
306 static void
307 add_pat (pat, endpat, nchars, argno, raw_before, raw_after, strize, rest)
308 struct reflist **pat, **endpat;
309 unsigned int nchars;
310 unsigned int argno;
311 int raw_before, raw_after, strize, rest;
313 struct reflist *tpat;
314 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
315 tpat->next = NULL;
316 tpat->raw_before = raw_before;
317 tpat->raw_after = raw_after;
318 tpat->stringify = strize;
319 tpat->rest_args = rest;
320 tpat->argno = argno;
321 tpat->nchars = nchars;
323 if (*endpat == NULL)
324 *pat = tpat;
325 else
326 (*endpat)->next = tpat;
327 *endpat = tpat;
330 /* Issue warnings for macro argument names seen inside strings. */
331 static void
332 warn_trad_stringify (pfile, p, len, argc, argv)
333 cpp_reader *pfile;
334 U_CHAR *p;
335 size_t len;
336 unsigned int argc;
337 const struct arg *argv;
339 U_CHAR *limit;
340 unsigned int i;
342 limit = p + len;
343 for (;;)
345 while (p < limit && !is_idstart (*p)) p++;
346 if (p >= limit)
347 break;
349 for (i = 0; i < argc; i++)
350 if (!strncmp (p, argv[i].name, argv[i].len)
351 && ! is_idchar (p[argv[i].len]))
353 cpp_warning (pfile,
354 "macro argument \"%s\" would be stringified in traditional C",
355 argv[i].name);
356 break;
358 p++;
359 while (p < limit && is_idchar (*p)) p++;
360 if (p >= limit)
361 break;
365 /* Generate pat nodes for macro arguments seen inside strings. */
366 static unsigned int
367 trad_stringify (pfile, base, len, argc, argv, pat, endpat, last)
368 cpp_reader *pfile;
369 U_CHAR *base;
370 size_t len;
371 unsigned int argc;
372 const struct arg *argv;
373 struct reflist **pat, **endpat;
374 unsigned int last;
376 U_CHAR *p, *limit;
377 unsigned int i;
379 p = base;
380 limit = base + len;
381 for (;;)
383 proceed:
384 while (p < limit && !is_idstart (*p)) p++;
385 if (p >= limit)
386 break;
388 for (i = 0; i < argc; i++)
389 if (!strncmp (p, argv[i].name, argv[i].len)
390 && ! is_idchar (p[argv[i].len]))
392 if (CPP_WTRADITIONAL (pfile))
393 cpp_warning (pfile, "macro argument \"%s\" is stringified",
394 argv[i].name);
395 /* Write out the string up to this point, and add a pat
396 node for the argument. Note that the argument is NOT
397 stringified. */
398 CPP_PUTS (pfile, base, p - base);
399 add_pat (pat, endpat, CPP_WRITTEN (pfile) - last, i /* argno */,
400 !is_hspace (p[-1]) /* raw_before */,
401 !is_hspace (p[argv[i].len]) /* raw_after */,
402 0 /* strize */,
403 argv[i].rest_arg);
404 last = CPP_WRITTEN (pfile);
405 base = p + argv[i].len;
406 goto proceed;
408 p++;
409 while (p < limit && is_idchar (*p)) p++;
410 if (p >= limit)
411 break;
413 CPP_PUTS (pfile, base, p - base);
414 return last;
417 /* Read a replacement list for an object-like macro, and build the
418 DEFINITION structure. LIST contains the replacement list,
419 beginning at 1. */
420 static DEFINITION *
421 collect_objlike_expansion (pfile, list)
422 cpp_reader *pfile;
423 cpp_toklist *list;
425 DEFINITION *defn;
426 unsigned int i;
427 unsigned int start;
428 int last_was_paste = 0;
429 U_CHAR *exp;
430 size_t len;
432 /* We copy the expansion text into the token_buffer, then out to
433 its proper home. */
434 start = CPP_WRITTEN (pfile);
435 CPP_PUTS (pfile, "\r ", 2);
437 for (i = 1; i < list->tokens_used; i++)
439 switch (list->tokens[i].type)
441 case CPP_POP:
442 case CPP_EOF:
443 cpp_ice (pfile, "EOF in collect_expansion");
444 /* fall through */
445 case CPP_VSPACE:
446 goto done;
448 case CPP_PASTE:
449 /* ## is not special if it appears right after another ##;
450 nor is it special if -traditional. */
451 if (last_was_paste || CPP_TRADITIONAL (pfile))
452 break;
453 if (i == 1)
454 cpp_error (pfile, "`##' at start of macro definition");
456 last_was_paste = 1;
457 continue;
459 default:;
462 if (i > 1 && !last_was_paste
463 && (list->tokens[i].flags & PREV_WHITESPACE))
464 CPP_PUTC (pfile, ' ');
466 CPP_PUTS (pfile,
467 list->tokens[i].val.name.offset + list->namebuf,
468 list->tokens[i].val.name.len);
469 last_was_paste = 0;
471 done:
473 if (last_was_paste)
474 cpp_error (pfile, "`##' at end of macro definition");
476 CPP_PUTS (pfile, "\r ", 2);
477 len = CPP_WRITTEN (pfile) - start;
478 CPP_SET_WRITTEN (pfile, start);
480 if (len <= 4)
481 cpp_ice (pfile, "empty object-like macro went through full #define");
483 exp = (U_CHAR *) xmalloc (len + 1);
484 memcpy (exp, pfile->token_buffer + start, len);
485 exp[len] = '\0';
487 defn = (DEFINITION *) xmalloc (sizeof (DEFINITION));
488 defn->length = len;
489 defn->expansion = exp;
490 defn->pattern = 0;
491 defn->rest_args = 0;
492 defn->argnames = 0;
493 defn->nargs = -1;
495 return defn;
498 /* Read a replacement list for a function-like macro, and build the
499 DEFINITION structure. LIST contains the replacement list,
500 beginning at REPLACEMENT. ARGLIST specifies the formal parameters
501 to look for in the text of the definition. */
503 static DEFINITION *
504 collect_funlike_expansion (pfile, list, arglist, replacement)
505 cpp_reader *pfile;
506 cpp_toklist *list;
507 struct arglist *arglist;
508 unsigned int replacement;
510 DEFINITION *defn;
511 struct reflist *pat = 0, *endpat = 0;
512 enum cpp_ttype token;
513 unsigned int start, last;
514 unsigned int i;
515 int j, argc;
516 size_t len;
517 const struct arg *argv;
518 U_CHAR *tok, *exp;
519 enum { START = 0, NORM, ARG, STRIZE, PASTE } last_token = START;
521 argv = arglist->argv;
522 argc = arglist->argc;
524 /* We copy the expansion text into the token_buffer, then out to
525 its proper home. */
526 last = start = CPP_WRITTEN (pfile);
527 CPP_PUTS (pfile, "\r ", 2);
529 for (i = replacement; i < list->tokens_used; i++)
531 token = list->tokens[i].type;
532 tok = list->tokens[i].val.name.offset + list->namebuf;
533 len = list->tokens[i].val.name.len;
534 switch (token)
536 case CPP_POP:
537 case CPP_EOF:
538 cpp_ice (pfile, "EOF in collect_expansion");
539 /* fall through */
540 case CPP_VSPACE:
541 goto done;
543 case CPP_HASH:
544 /* # is special in function-like macros with no args.
545 (6.10.3.2 para 1.) However, it is not special after
546 PASTE. (Implied by 6.10.3.3 para 4.) Nor is it special
547 if -traditional. */
548 if (last_token == PASTE || CPP_TRADITIONAL (pfile))
549 break;
550 last_token = STRIZE;
551 continue;
553 case CPP_PASTE:
554 /* ## is not special if it appears right after another ##;
555 nor is it special if -traditional. */
556 if (last_token == PASTE || CPP_TRADITIONAL (pfile))
557 break;
559 if (last_token == START)
560 cpp_error (pfile, "`##' at start of macro definition");
561 else if (last_token == ARG)
562 /* If the last token was an argument, mark it raw_after. */
563 endpat->raw_after = 1;
564 else if (last_token == STRIZE)
565 /* Oops - that wasn't a stringify operator. */
566 CPP_PUTC (pfile, '#');
568 last_token = PASTE;
569 continue;
571 default:;
574 if (last_token != PASTE && last_token != START
575 && (list->tokens[i].flags & PREV_WHITESPACE))
576 CPP_PUTC (pfile, ' ');
577 if (last_token == ARG && CPP_TRADITIONAL (pfile)
578 && !(list->tokens[i].flags & PREV_WHITESPACE))
579 endpat->raw_after = 1;
581 switch (token)
583 case CPP_STRING:
584 case CPP_CHAR:
585 if (argc == 0)
586 goto norm;
587 if (CPP_TRADITIONAL (pfile))
589 last = trad_stringify (pfile, tok, len, argc, argv,
590 &pat, &endpat, last);
591 break;
593 else
595 if (CPP_WTRADITIONAL (pfile))
596 warn_trad_stringify (pfile, tok, len, argc, argv);
597 goto norm;
600 case CPP_NAME:
601 for (j = 0; j < argc; j++)
602 if (argv[j].len == len
603 && !strncmp (tok, argv[j].name, argv[j].len))
604 goto addref;
606 /* fall through */
607 default:
608 norm:
609 if (last_token == STRIZE)
610 cpp_error (pfile, "# is not followed by a macro argument name");
611 CPP_PUTS (pfile, tok, len);
612 last_token = NORM;
614 continue;
616 addref:
618 int raw_before = (last_token == PASTE
619 || (CPP_TRADITIONAL (pfile)
620 && !(list->tokens[i].flags & PREV_WHITESPACE)));
622 add_pat (&pat, &endpat,
623 CPP_WRITTEN (pfile) - last /* nchars */, j /* argno */,
624 raw_before, 0 /* raw_after */,
625 (last_token == STRIZE), argv[j].rest_arg);
627 last = CPP_WRITTEN (pfile);
629 last_token = ARG;
631 done:
633 if (last_token == STRIZE)
634 cpp_error (pfile, "`#' is not followed by a macro argument name");
635 else if (last_token == PASTE)
636 cpp_error (pfile, "`##' at end of macro definition");
638 CPP_PUTS (pfile, "\r ", 2);
639 len = CPP_WRITTEN (pfile) - start;
640 CPP_SET_WRITTEN (pfile, start);
642 exp = (U_CHAR *) xmalloc (len + 1);
643 memcpy (exp, pfile->token_buffer + start, len);
644 exp[len] = '\0';
646 defn = (DEFINITION *) xmalloc (sizeof (DEFINITION));
647 defn->length = len;
648 defn->expansion = exp;
649 defn->pattern = pat;
650 defn->rest_args = argc && argv[argc - 1].rest_arg;
651 defn->nargs = argc;
652 defn->argnames = arglist->namebuf;
653 if (argv)
654 free ((PTR) argv);
655 return defn;
658 /* Is argument NEW, which has just been added to the argument list,
659 a duplicate of a previous argument name? */
660 static int
661 duplicate_arg_p (args, new)
662 U_CHAR *args, *new;
664 size_t newlen = strlen (new) + 1;
665 size_t oldlen;
667 while (args < new)
669 oldlen = strlen (args) + 1;
670 if (!memcmp (args, new, MIN (oldlen, newlen)))
671 return 1;
672 args += oldlen;
674 return 0;
677 static unsigned int
678 collect_params (pfile, list, arglist)
679 cpp_reader *pfile;
680 cpp_toklist *list;
681 struct arglist *arglist;
683 struct arg *argv = 0;
684 U_CHAR *namebuf, *p, *tok;
685 unsigned int len, argslen;
686 unsigned int argc, a, i, j;
688 /* The formal parameters list starts at token 1. */
689 if (list->tokens[1].type != CPP_OPEN_PAREN)
691 cpp_ice (pfile, "first token = %d not %d in collect_formal_parameters",
692 list->tokens[1].type, CPP_OPEN_PAREN);
693 return 0;
696 /* Scan once and count the number of parameters; also check for
697 syntax errors here. */
698 argc = 0;
699 argslen = 0;
700 for (i = 2; i < list->tokens_used; i++)
701 switch (list->tokens[i].type)
703 case CPP_NAME:
704 argslen += list->tokens[i].val.name.len + 1;
705 argc++;
706 break;
707 case CPP_COMMA:
708 break;
709 case CPP_CLOSE_PAREN:
710 goto scanned;
711 case CPP_VSPACE:
712 cpp_error_with_line (pfile, list->line, list->tokens[i].col,
713 "missing right paren in macro argument list");
714 return 0;
716 default:
717 cpp_error_with_line (pfile, list->line, list->tokens[i].col,
718 "syntax error in #define");
719 return 0;
721 case CPP_ELLIPSIS:
722 if (list->tokens[i-1].type != CPP_NAME)
724 argslen += sizeof "__VA_ARGS__";
725 argc++;
727 i++;
728 if (list->tokens[i].type != CPP_CLOSE_PAREN)
730 cpp_error_with_line (pfile, list->line, list->tokens[i].col,
731 "another parameter follows \"...\"");
732 return 0;
734 goto scanned;
737 cpp_ice (pfile, "collect_params: unreachable - i=%d, ntokens=%d, type=%d",
738 i, list->tokens_used, list->tokens[i-1].type);
739 return 0;
741 scanned:
742 if (argc == 0) /* function-like macro, no arguments */
744 arglist->argc = 0;
745 arglist->argv = 0;
746 arglist->namebuf = 0;
747 return i + 1;
749 if (argslen == 0)
751 cpp_ice (pfile, "collect_params: argc=%d argslen=0", argc);
752 return 0;
755 /* Now allocate space and copy the suckers. */
756 argv = (struct arg *) xmalloc (argc * sizeof (struct arg));
757 namebuf = (U_CHAR *) xmalloc (argslen);
758 p = namebuf;
759 a = 0;
760 for (j = 2; j < i; j++)
761 switch (list->tokens[j].type)
763 case CPP_NAME:
764 tok = list->tokens[j].val.name.offset + list->namebuf;
765 len = list->tokens[j].val.name.len;
766 memcpy (p, tok, len);
767 p[len] = '\0';
768 if (duplicate_arg_p (namebuf, p))
770 cpp_error (pfile, "duplicate macro argument name \"%s\"", tok);
771 a++;
772 break;
774 if (CPP_PEDANTIC (pfile) && CPP_OPTION (pfile, c99)
775 && len == sizeof "__VA_ARGS__" - 1
776 && !strcmp (p, "__VA_ARGS__"))
777 cpp_pedwarn (pfile,
778 "C99 does not permit use of __VA_ARGS__ as a macro argument name");
779 argv[a].len = len;
780 argv[a].name = p;
781 argv[a].rest_arg = 0;
782 p += len;
783 a++;
784 break;
786 case CPP_COMMA:
787 break;
789 case CPP_ELLIPSIS:
790 if (list->tokens[j-1].type != CPP_NAME)
792 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
793 cpp_pedwarn (pfile, "C89 does not permit varargs macros");
795 argv[a].len = sizeof "__VA_ARGS__" - 1;
796 argv[a].name = p;
797 argv[a].rest_arg = 1;
798 strcpy (p, "__VA_ARGS__");
800 else
802 if (CPP_PEDANTIC (pfile))
803 cpp_pedwarn (pfile,
804 "ISO C does not permit named varargs macros");
805 argv[a-1].rest_arg = 1;
807 break;
809 default:
810 cpp_ice (pfile, "collect_params: impossible token type %d",
811 list->tokens[j].type);
814 arglist->argc = argc;
815 arglist->argv = argv;
816 arglist->namebuf = namebuf;
817 return i + 1;
820 /* Create a DEFINITION node for a macro. The replacement text
821 (including formal parameters if present) is in LIST. If FUNLIKE is
822 true, this is a function-like macro. */
825 _cpp_create_definition (pfile, list, hp)
826 cpp_reader *pfile;
827 cpp_toklist *list;
828 HASHNODE *hp;
830 DEFINITION *defn = 0;
831 U_CHAR *cpval = 0;
832 enum node_type ntype;
833 int ok;
835 /* Special-case a few simple and common idioms:
836 #define TOKEN // nothing
837 #define TOKEN TOKEN
838 #define TOKEN OTHERTOKEN
840 Might also be good to special-case these:
842 #define FUNC() // nothing
843 #define FUNC(a, b, ...) // nothing
844 #define FUNC(a, b, c) FUNC(a, b, c)
845 #define FUNC(a, b, c) foobar(a, b, c) */
847 if (list->tokens_used == 2)
848 ntype = T_EMPTY; /* Empty definition of object-like macro. */
849 else if (list->tokens_used == 3 && list->tokens[1].type == CPP_NAME)
851 if (list->tokens[0].val.name.len == list->tokens[1].val.name.len
852 && !strncmp (list->tokens[0].val.name.offset + list->namebuf,
853 list->tokens[1].val.name.offset + list->namebuf,
854 list->tokens[0].val.name.len))
855 ntype = T_IDENTITY;
856 else
858 ntype = T_MCONST;
859 cpval = xmalloc (list->tokens[1].val.name.len + 1);
860 memcpy (cpval, list->tokens[1].val.name.offset + list->namebuf,
861 list->tokens[1].val.name.len);
862 cpval[list->tokens[1].val.name.len] = '\0';
866 /* The macro is function-like only if the next character,
867 with no intervening whitespace, is '('. */
868 else if (list->tokens[1].type == CPP_OPEN_PAREN
869 && ! (list->tokens[1].flags & PREV_WHITESPACE))
871 struct arglist args;
872 int replacement;
874 replacement = collect_params (pfile, list, &args);
875 if (replacement == 0)
876 return 0;
877 defn = collect_funlike_expansion (pfile, list, &args, replacement);
878 if (defn == 0)
879 return 0;
881 ntype = T_FMACRO;
884 /* Otherwise it is an object-like macro, and C99 requires
885 whitespace after the name (6.10.3 para 3). */
886 else
888 if (! (list->tokens[1].flags & PREV_WHITESPACE))
889 cpp_pedwarn (pfile,
890 "The C standard requires whitespace after #define %s",
891 hp->name);
893 defn = collect_objlike_expansion (pfile, list);
894 if (defn == 0)
895 return 0;
897 ntype = T_MACRO;
900 /* Check for a redefinition, and its legality. Redefining a macro
901 of whatever stripe is ok if the definitions are the same.
902 Redefining a built-in _constant_ (T_CONST or T_XCONST) is ok only
903 with -D. Otherwise a redefinition is not ok. */
905 switch (hp->type)
907 case T_VOID: ok = 1; break;
908 default: ok = 0; break;
910 case T_MACRO: case T_FMACRO:
911 ok = (ntype == hp->type && !compare_defs (pfile, defn, hp->value.defn));
912 break;
913 case T_IDENTITY:
914 case T_EMPTY:
915 ok = (ntype == hp->type);
916 break;
917 case T_MCONST:
918 ok = (ntype == hp->type && !strcmp (cpval, hp->value.cpval));
919 break;
920 case T_CONST:
921 case T_XCONST:
922 ok = ! pfile->done_initializing;
923 break;
926 /* Print the warning or error if it's not ok. */
927 if (! ok)
929 cpp_pedwarn (pfile, "\"%s\" redefined", hp->name);
930 if (pfile->done_initializing)
931 cpp_pedwarn_with_file_and_line (pfile, hp->file, hp->line, hp->col,
932 "this is the location of the previous definition");
935 /* And replace the old definition (if any). */
937 if (hp->type == T_MACRO || hp->type == T_FMACRO)
938 _cpp_free_definition (hp->value.defn);
939 else if (hp->type == T_MCONST || hp->type == T_XCONST)
940 free ((PTR) hp->value.cpval);
942 if (ntype == T_MACRO || ntype == T_FMACRO)
943 hp->value.defn = defn;
944 else
945 hp->value.cpval = cpval;
947 hp->type = ntype;
948 hp->file = CPP_BUFFER (pfile)->nominal_fname;
949 hp->line = list->line;
950 hp->col = list->tokens[0].col;
951 return 1;
955 * Parse a macro argument and append the info on PFILE's token_buffer.
956 * REST_ARGS means to absorb the rest of the args.
957 * Return nonzero to indicate a syntax error.
960 static enum cpp_ttype
961 macarg (pfile, rest_args)
962 cpp_reader *pfile;
963 int rest_args;
965 int paren = 0;
966 enum cpp_ttype token;
968 /* Try to parse as much of the argument as exists at this
969 input stack level. */
970 for (;;)
972 token = cpp_get_token (pfile);
973 switch (token)
975 case CPP_EOF:
976 return token;
977 case CPP_POP:
978 /* If we've hit end of file, it's an error (reported by caller).
979 Ditto if it's the end of cpp_expand_to_buffer text.
980 If we've hit end of macro, just continue. */
981 if (!CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
982 return token;
983 break;
984 case CPP_OPEN_PAREN:
985 paren++;
986 break;
987 case CPP_CLOSE_PAREN:
988 if (--paren < 0)
989 goto found;
990 break;
991 case CPP_COMMA:
992 /* if we've returned to lowest level and
993 we aren't absorbing all args */
994 if (paren == 0 && rest_args == 0)
995 goto found;
996 break;
997 found:
998 /* Remove ',' or ')' from argument buffer. */
999 CPP_ADJUST_WRITTEN (pfile, -1);
1000 return token;
1001 default:;
1007 static const char * const monthnames[] =
1009 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1010 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1013 /* Place into PFILE a quoted string representing the string SRC.
1014 Caller must reserve enough space in pfile->token_buffer. */
1016 void
1017 _cpp_quote_string (pfile, src)
1018 cpp_reader *pfile;
1019 const char *src;
1021 U_CHAR c;
1023 CPP_PUTC_Q (pfile, '\"');
1024 for (;;)
1025 switch ((c = *src++))
1027 default:
1028 if (ISPRINT (c))
1029 CPP_PUTC_Q (pfile, c);
1030 else
1032 sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
1033 CPP_ADJUST_WRITTEN (pfile, 4);
1035 break;
1037 case '\"':
1038 case '\\':
1039 CPP_PUTC_Q (pfile, '\\');
1040 CPP_PUTC_Q (pfile, c);
1041 break;
1043 case '\0':
1044 CPP_PUTC_Q (pfile, '\"');
1045 return;
1050 * expand things like __FILE__. Place the expansion into the output
1051 * buffer *without* rescanning.
1054 #define DSC(str) (const U_CHAR *)str, sizeof str - 1
1055 static void
1056 special_symbol (pfile, hp)
1057 cpp_reader *pfile;
1058 HASHNODE *hp;
1060 const char *buf;
1061 cpp_buffer *ip;
1063 switch (hp->type)
1065 case T_FILE:
1066 case T_BASE_FILE:
1067 ip = cpp_file_buffer (pfile);
1068 if (ip == NULL)
1070 CPP_PUTS (pfile, "\"\"", 2);
1071 return;
1073 if (hp->type == T_BASE_FILE)
1074 while (CPP_PREV_BUFFER (ip) != NULL)
1075 ip = CPP_PREV_BUFFER (ip);
1077 buf = ip->nominal_fname;
1078 CPP_RESERVE (pfile, 3 + 4 * strlen (buf));
1079 _cpp_quote_string (pfile, buf);
1080 return;
1082 case T_INCLUDE_LEVEL:
1084 int true_indepth = 0;
1085 ip = cpp_file_buffer (pfile);
1086 while (ip)
1088 true_indepth++;
1089 ip = CPP_PREV_BUFFER (ip);
1092 CPP_RESERVE (pfile, 10);
1093 sprintf (CPP_PWRITTEN (pfile), "%d", true_indepth);
1094 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
1095 return;
1098 case T_STDC:
1099 #ifdef STDC_0_IN_SYSTEM_HEADERS
1100 ip = cpp_file_buffer (pfile);
1101 if (ip && ip->system_header_p
1102 && !cpp_defined (pfile, DSC("__STRICT_ANSI__")))
1104 CPP_PUTC (pfile, '0');
1105 return;
1107 #endif
1108 constant:
1109 buf = hp->value.cpval;
1110 if (!buf || *buf == '\0')
1111 return;
1113 CPP_PUTS (pfile, buf, strlen (buf));
1114 return;
1116 case T_SPECLINE:
1117 ip = cpp_file_buffer (pfile);
1118 if (ip == NULL)
1120 CPP_PUTC (pfile, '0');
1121 return;
1123 CPP_RESERVE (pfile, 10);
1124 sprintf (CPP_PWRITTEN (pfile), "%u", CPP_BUF_LINE (ip));
1125 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
1126 return;
1128 case T_DATE:
1129 case T_TIME:
1130 /* Generate both __DATE__ and __TIME__, stuff them into their
1131 respective hash nodes, and mark the nodes T_XCONST so we
1132 don't have to do this again. We don't generate these strings
1133 at init time because time() and localtime() are very slow on
1134 some systems. */
1136 time_t tt = time (NULL);
1137 struct tm *tb = localtime (&tt);
1138 HASHNODE *d, *t;
1140 if (hp->type == T_DATE)
1141 d = hp, t = _cpp_lookup (pfile, DSC("__TIME__"));
1142 else
1143 t = hp, d = _cpp_lookup (pfile, DSC("__DATE__"));
1145 d->value.cpval = xmalloc (sizeof "'Oct 11 1347'");
1146 sprintf ((char *)d->value.cpval, "\"%s %2d %4d\"",
1147 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
1148 d->type = T_XCONST;
1150 t->value.cpval = xmalloc (sizeof "'12:34:56'");
1151 sprintf ((char *)t->value.cpval, "\"%02d:%02d:%02d\"",
1152 tb->tm_hour, tb->tm_min, tb->tm_sec);
1153 t->type = T_XCONST;
1154 goto constant;
1157 case T_POISON:
1158 cpp_error (pfile, "attempt to use poisoned `%s'.", hp->name);
1159 CPP_PUTC (pfile, '0');
1160 break;
1162 default:
1163 cpp_ice (pfile, "invalid special hash type");
1164 return;
1167 #undef DSC
1169 /* Expand a macro call.
1170 HP points to the symbol that is the macro being called.
1171 Put the result of expansion onto the input stack
1172 so that subsequent input by our caller will use it.
1174 If macro wants arguments, caller has already verified that
1175 an argument list follows; arguments come from the input stack. */
1177 void
1178 _cpp_macroexpand (pfile, hp)
1179 cpp_reader *pfile;
1180 HASHNODE *hp;
1182 DEFINITION *defn;
1183 struct argdata *args;
1184 unsigned int old_written;
1185 int i;
1187 /* Object like macro - most common case. */
1188 if (hp->type == T_MACRO)
1190 push_macro_expansion (pfile, hp->value.defn->expansion,
1191 hp->value.defn->length, hp);
1192 return;
1195 /* Or might it be a constant string? */
1196 if (hp->type == T_MCONST || hp->type == T_CONST || hp->type == T_XCONST)
1198 const U_CHAR *cpval = hp->value.cpval;
1199 if (cpval && *cpval != '\0')
1200 push_macro_expansion (pfile, cpval, strlen (cpval), hp);
1201 return;
1204 /* Or a special symbol? */
1205 if (hp->type != T_FMACRO)
1207 U_CHAR *xbuf;
1208 unsigned int len, old_written = CPP_WRITTEN (pfile);
1210 special_symbol (pfile, hp);
1211 len = CPP_WRITTEN (pfile) - old_written;
1212 CPP_SET_WRITTEN (pfile, old_written);
1213 if (len == 0)
1214 return;
1216 xbuf = (U_CHAR *) xmalloc (len + 1);
1217 memcpy (xbuf, CPP_PWRITTEN (pfile), len);
1218 xbuf[len] = '\0';
1219 push_macro_expansion (pfile, xbuf, len, hp);
1220 return;
1223 /* Okay, it's a full-on function-like macro... */
1224 old_written = CPP_WRITTEN (pfile);
1225 defn = hp->value.defn;
1227 args = alloca (MAX (defn->nargs, 1) * sizeof (struct argdata));
1228 for (i = 0; i < MAX (defn->nargs, 1); i++)
1230 args[i].raw = args[i].expanded = 0;
1231 args[i].raw_length = 0;
1232 args[i].expand_length = args[i].stringified_length = -1;
1235 pfile->output_escapes++;
1236 scan_arguments (pfile, defn, args, hp->name);
1238 /* If macro wants zero args, we parsed the arglist for checking only.
1239 Read directly from the macro definition. */
1240 if (defn->nargs == 0 || defn->pattern == 0)
1242 /* If the defn is the empty string, don't bother pushing it. */
1243 if (defn->length > 4)
1244 push_macro_expansion (pfile, defn->expansion, defn->length, hp);
1246 else
1247 funlike_macroexpand (pfile, hp, args);
1249 CPP_SET_WRITTEN (pfile, old_written);
1250 pfile->output_escapes--;
1253 static void
1254 scan_arguments (pfile, defn, args, name)
1255 cpp_reader *pfile;
1256 DEFINITION *defn;
1257 struct argdata *args;
1258 const U_CHAR *name;
1260 enum cpp_ttype token;
1261 unsigned int start_line, start_column;
1262 unsigned int nargs = defn->nargs;
1263 unsigned int i;
1265 cpp_buffer *ip = cpp_file_buffer (pfile);
1266 if (ip)
1268 start_line = CPP_BUF_LINE (ip);
1269 start_column = CPP_BUF_COL (ip);
1271 else
1272 start_line = start_column = 0;
1274 /* Parse all the macro args that are supplied. I counts them. The
1275 first NARGS args are stored in ARGS. The rest are discarded. If
1276 rest_args is set then we assume macarg absorbed the rest of the
1277 args. */
1278 i = 0;
1280 /* Skip over the opening parenthesis. */
1281 CPP_OPTION (pfile, discard_comments)++;
1282 pfile->no_macro_expand++;
1283 pfile->no_directives++;
1285 token = cpp_get_non_space_token (pfile);
1286 if (token != CPP_OPEN_PAREN)
1287 cpp_ice (pfile, "macroexpand: unexpected token %d (wanted LPAREN)",
1288 token);
1289 CPP_ADJUST_WRITTEN (pfile, -1);
1291 token = CPP_EOF;
1294 if (i < MAX (nargs, 1))
1296 args[i].raw = CPP_WRITTEN (pfile);
1297 token = macarg (pfile, (i == nargs - 1 && defn->rest_args));
1298 args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
1300 else
1301 token = macarg (pfile, 0);
1302 if (token == CPP_EOF || token == CPP_POP)
1303 cpp_error_with_line (pfile, start_line, start_column,
1304 "unterminated macro call");
1305 i++;
1307 while (token == CPP_COMMA);
1308 CPP_OPTION (pfile, discard_comments)--;
1309 pfile->no_macro_expand--;
1310 pfile->no_directives--;
1311 if (token != CPP_CLOSE_PAREN)
1312 return;
1314 /* foo ( ) is equivalent to foo () unless foo takes exactly one
1315 argument, in which case the former is allowed and the latter
1316 is not. XXX C99 is silent on this rule, but it seems
1317 inconsistent to me. */
1318 if (i == 1 && nargs == 0)
1320 register U_CHAR *bp = ARG_BASE + args[0].raw;
1321 register U_CHAR *lim = bp + args[0].raw_length;
1322 while (bp != lim && is_space(*bp))
1323 bp++;
1324 if (bp == lim)
1325 i = 0;
1328 /* Don't output an error message if we have already output one for
1329 a parse error above. */
1330 if (nargs == 0 && i > 0)
1332 cpp_error (pfile, "arguments given to macro `%s'", name);
1334 else if (i < nargs)
1336 /* traditional C allows foo() if foo wants one argument. */
1337 if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
1339 /* the rest args token is allowed to absorb 0 tokens */
1340 else if (i == nargs - 1 && defn->rest_args)
1342 else if (i == 0)
1343 cpp_error (pfile, "macro `%s' used without args", name);
1344 else if (i == 1)
1345 cpp_error (pfile, "macro `%s' used with just one arg", name);
1346 else
1347 cpp_error (pfile, "macro `%s' used with only %d args", name, i);
1349 else if (i > nargs)
1351 cpp_error (pfile, "macro `%s' used with too many (%d) args", name, i);
1355 static void
1356 stringify (pfile, arg)
1357 cpp_reader *pfile;
1358 struct argdata *arg;
1360 int arglen = arg->raw_length;
1361 int escaped = 0;
1362 int in_string = 0;
1363 int c;
1364 int i;
1365 /* Initially need_space is -1. Otherwise, 1 means the previous
1366 character was a space, but we suppressed it; 0 means the previous
1367 character was a non-space. */
1368 int need_space = -1;
1369 i = 0;
1370 arg->stringified = CPP_WRITTEN (pfile);
1371 CPP_PUTC (pfile, '\"'); /* insert beginning quote */
1372 for (; i < arglen; i++)
1374 c = (ARG_BASE + arg->raw)[i];
1376 if (!in_string)
1378 /* Delete "\r " and "\r-" escapes. */
1379 if (c == '\r')
1381 i++;
1382 continue;
1384 /* Internal sequences of whitespace are replaced by one
1385 space except within a string or char token. */
1386 else if (is_space(c))
1388 if (need_space == 0)
1389 need_space = 1;
1390 continue;
1392 else if (need_space > 0)
1393 CPP_PUTC (pfile, ' ');
1394 need_space = 0;
1397 if (escaped)
1398 escaped = 0;
1399 else
1401 if (c == '\\')
1402 escaped = 1;
1403 if (in_string)
1405 if (c == in_string)
1406 in_string = 0;
1408 else if (c == '\"' || c == '\'')
1409 in_string = c;
1412 /* Escape these chars */
1413 if (c == '\"' || (in_string && c == '\\'))
1414 CPP_PUTC (pfile, '\\');
1415 if (ISPRINT (c))
1416 CPP_PUTC (pfile, c);
1417 else
1419 CPP_RESERVE (pfile, 4);
1420 sprintf ((char *) CPP_PWRITTEN (pfile), "\\%03o", (unsigned int) c);
1421 CPP_ADJUST_WRITTEN (pfile, 4);
1424 CPP_PUTC (pfile, '\"'); /* insert ending quote */
1425 arg->stringified_length = CPP_WRITTEN (pfile) - arg->stringified;
1428 static void
1429 funlike_macroexpand (pfile, hp, args)
1430 cpp_reader *pfile;
1431 HASHNODE *hp;
1432 struct argdata *args;
1434 DEFINITION *defn = hp->value.defn;
1435 register U_CHAR *xbuf;
1436 int xbuf_len;
1437 U_CHAR *exp = defn->expansion;
1438 int offset; /* offset in expansion, copied a piece at a time */
1439 int totlen; /* total amount of exp buffer filled so far */
1440 struct reflist *ap, *last_ap;
1441 int i;
1443 /* Compute length in characters of the macro's expansion.
1444 Also count number of times each arg is used. */
1445 xbuf_len = defn->length;
1446 for (ap = defn->pattern; ap != NULL; ap = ap->next)
1448 if (ap->stringify)
1450 /* Stringify if it hasn't already been */
1451 if (args[ap->argno].stringified_length < 0)
1452 stringify (pfile, &args[ap->argno]);
1453 xbuf_len += args[ap->argno].stringified_length;
1455 else if (ap->raw_before || ap->raw_after)
1456 /* Add 4 for two \r-space markers to prevent
1457 token concatenation. */
1458 xbuf_len += args[ap->argno].raw_length + 4;
1459 else
1461 /* We have an ordinary (expanded) occurrence of the arg.
1462 So compute its expansion, if we have not already. */
1463 if (args[ap->argno].expand_length < 0)
1465 args[ap->argno].expanded = CPP_WRITTEN (pfile);
1466 _cpp_expand_to_buffer (pfile, ARG_BASE + args[ap->argno].raw,
1467 args[ap->argno].raw_length);
1469 args[ap->argno].expand_length
1470 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
1473 /* Add 4 for two \r-space markers to prevent
1474 token concatenation. */
1475 xbuf_len += args[ap->argno].expand_length + 4;
1479 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1481 /* Generate in XBUF the complete expansion with arguments
1482 substituted in. TOTLEN is the total size generated so far.
1483 OFFSET is the index in the definition of where we are copying
1484 from. */
1485 offset = totlen = 0;
1486 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
1487 last_ap = ap, ap = ap->next)
1489 register struct argdata *arg = &args[ap->argno];
1490 int count_before = totlen;
1492 /* Add chars to XBUF. */
1493 i = ap->nchars;
1494 memcpy (&xbuf[totlen], &exp[offset], i);
1495 totlen += i;
1496 offset += i;
1498 /* If followed by an empty rest arg with concatenation,
1499 delete the last run of nonwhite chars. */
1500 if (arg->raw_length == 0 && totlen > count_before
1501 && ((ap->rest_args && ap->raw_before)
1502 || (last_ap != NULL && last_ap->rest_args
1503 && last_ap->raw_after)))
1505 /* Delete final whitespace. */
1506 while (totlen > count_before && is_space(xbuf[totlen - 1]))
1507 totlen--;
1509 /* Delete the nonwhites before them. */
1510 while (totlen > count_before && !is_space(xbuf[totlen - 1]))
1511 totlen--;
1514 if (ap->stringify != 0)
1516 memcpy (xbuf + totlen, ARG_BASE + arg->stringified,
1517 arg->stringified_length);
1518 totlen += arg->stringified_length;
1520 else if (ap->raw_before || ap->raw_after)
1522 U_CHAR *p1 = ARG_BASE + arg->raw;
1523 U_CHAR *l1 = p1 + arg->raw_length;
1524 if (ap->raw_before)
1526 /* Arg is concatenated before: delete leading whitespace,
1527 whitespace markers, and no-reexpansion markers. */
1528 while (p1 != l1)
1530 if (is_space(p1[0]))
1531 p1++;
1532 else if (p1[0] == '\r')
1533 p1 += 2;
1534 else
1535 break;
1538 if (ap->raw_after)
1540 /* Arg is concatenated after: delete trailing whitespace,
1541 whitespace markers, and no-reexpansion markers. */
1542 while (p1 != l1)
1544 if (is_space(l1[-1]))
1545 l1--;
1546 else if (l1[-1] == '\r')
1547 l1--;
1548 else if (l1[-1] == '-')
1550 if (l1 != p1 + 1 && l1[-2] == '\r')
1551 l1 -= 2;
1552 else
1553 break;
1555 else
1556 break;
1560 /* Delete any no-reexpansion marker that precedes
1561 an identifier at the beginning of the argument. */
1562 if (p1[0] == '\r' && p1[1] == '-')
1563 p1 += 2;
1565 memcpy (xbuf + totlen, p1, l1 - p1);
1566 totlen += l1 - p1;
1568 else
1570 U_CHAR *expanded = ARG_BASE + arg->expanded;
1571 if (!ap->raw_before && totlen > 0 && arg->expand_length
1572 && unsafe_chars (pfile, xbuf[totlen - 1], expanded[0]))
1574 xbuf[totlen++] = '\r';
1575 xbuf[totlen++] = ' ';
1578 memcpy (xbuf + totlen, expanded, arg->expand_length);
1579 totlen += arg->expand_length;
1581 if (!ap->raw_after && totlen > 0 && offset < defn->length
1582 && unsafe_chars (pfile, xbuf[totlen - 1], exp[offset]))
1584 xbuf[totlen++] = '\r';
1585 xbuf[totlen++] = ' ';
1590 /* if there is anything left of the definition
1591 after handling the arg list, copy that in too. */
1593 for (i = offset; i < defn->length; i++)
1594 xbuf[totlen++] = exp[i];
1595 xbuf[totlen] = 0;
1597 if (totlen > xbuf_len)
1598 /* Just die - we've trashed the heap at this point. */
1599 abort ();
1601 /* Now put the expansion on the input stack
1602 so our caller will commence reading from it. */
1603 push_macro_expansion (pfile, xbuf, totlen, hp);
1606 /* Return 1 iff a token ending in C1 followed directly by a token C2
1607 could cause mis-tokenization. */
1609 static int
1610 unsafe_chars (pfile, c1, c2)
1611 cpp_reader *pfile;
1612 int c1, c2;
1614 /* If c2 is EOF, that's always safe. */
1615 if (c2 == EOF)
1616 return 0;
1618 switch (c1)
1620 case EOF:
1621 /* We don't know what the previous character was. We do know
1622 that it can't have been an idchar (or else it would have been
1623 pasted with the idchars of the macro name), and there are a
1624 number of second characters for which it doesn't matter what
1625 the first was. */
1626 if (is_idchar (c2) || c2 == '\'' || c2 == '\"'
1627 || c2 == '(' || c2 == '[' || c2 == '{'
1628 || c2 == ')' || c2 == ']' || c2 == '}')
1629 return 0;
1630 return 1;
1632 case '+': case '-':
1633 if (c2 == c1 || c2 == '=')
1634 return 1;
1635 goto letter;
1637 case 'e': case 'E': case 'p': case 'P':
1638 if (c2 == '-' || c2 == '+')
1639 return 1; /* could extend a pre-processing number */
1640 goto letter;
1642 case '$':
1643 if (CPP_OPTION (pfile, dollars_in_ident))
1644 goto letter;
1645 return 0;
1647 case 'L':
1648 if (c2 == '\'' || c2 == '\"')
1649 return 1; /* Could turn into L"xxx" or L'xxx'. */
1650 goto letter;
1652 case '.': case '0': case '1': case '2': case '3':
1653 case '4': case '5': case '6': case '7': case '8': case '9':
1654 case '_': case 'a': case 'b': case 'c': case 'd': case 'f':
1655 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1656 case 'm': case 'n': case 'o': case 'q': case 'r': case 's':
1657 case 't': case 'u': case 'v': case 'w': case 'x': case 'y':
1658 case 'z': case 'A': case 'B': case 'C': case 'D': case 'F':
1659 case 'G': case 'H': case 'I': case 'J': case 'K': case 'M':
1660 case 'N': case 'O': case 'Q': case 'R': case 'S': case 'T':
1661 case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
1662 letter:
1663 /* We're in the middle of either a name or a pre-processing number. */
1664 return (is_idchar(c2) || c2 == '.');
1666 case '<': case '>': case '!': case '%': case '#': case ':':
1667 case '^': case '&': case '|': case '*': case '/': case '=':
1668 return (c2 == c1 || c2 == '=');
1670 return 0;
1673 static void
1674 push_macro_expansion (pfile, xbuf, len, hp)
1675 cpp_reader *pfile;
1676 const U_CHAR *xbuf;
1677 int len;
1678 HASHNODE *hp;
1680 cpp_buffer *mbuf;
1681 int advance_cur = 0;
1683 /* The first chars of the expansion should be a "\r " added by
1684 collect_expansion. This is to prevent accidental token-pasting
1685 between the text preceding the macro invocation, and the macro
1686 expansion text.
1688 We would like to avoid adding unneeded spaces (for the sake of
1689 tools that use cpp, such as imake). In some common cases we can
1690 tell that it is safe to omit the space. */
1692 if (xbuf[0] == '\r' && xbuf[1] == ' '
1693 && !unsafe_chars (pfile, EOF, xbuf[2]))
1694 advance_cur = 1;
1696 /* Likewise, avoid the extra space at the end of the macro expansion
1697 if this is safe. We can do a better job here since we can know
1698 what the next char will be. */
1699 if (len >= 3 && xbuf[len-2] == '\r' && xbuf[len-1] == ' '
1700 && !unsafe_chars (pfile, xbuf[len-3], CPP_BUF_PEEK (CPP_BUFFER (pfile))))
1701 len -= 2;
1703 /* If the total expansion is "\r \r ", we must not trim both escapes. */
1704 if (len == 2 && advance_cur)
1705 advance_cur = 0;
1707 mbuf = cpp_push_buffer (pfile, xbuf, len);
1708 if (mbuf == NULL)
1709 return;
1710 if (advance_cur)
1711 mbuf->cur += 2;
1712 mbuf->cleanup = macro_cleanup;
1713 mbuf->macro = hp;
1714 mbuf->has_escapes = 1;
1716 /* In C89, a macro cannot be expanded recursively. Traditional C
1717 permits it, but any use in an object-like macro must lead to
1718 infinite recursion, so always follow C89 in object-like macros.
1719 Likewise, in a function-like macro it must cause infinite
1720 recursion unless we are actually doing something with the
1721 arguments.
1723 Even that criterion is too weak. The only example known where
1724 macro recursion isn't infinite is:
1725 #define bar(x,y) foo(x(y, 0))
1726 bar(bar, baz)
1727 which expands to foo(bar(baz, 0)) in C89 and
1728 foo(foo(baz(0, 0)) in K+R. This looks pathological to me.
1729 If someone has a real-world example I would love to see it. */
1730 if (hp->type != T_FMACRO
1731 || hp->value.defn->nargs == 0
1732 || hp->value.defn->pattern == 0
1733 || !CPP_TRADITIONAL (pfile))
1734 hp->disabled = 1;
1737 /* Return zero if two DEFINITIONs are isomorphic. */
1739 static int
1740 compare_defs (pfile, d1, d2)
1741 cpp_reader *pfile;
1742 DEFINITION *d1, *d2;
1744 struct reflist *a1, *a2;
1746 if (d1->nargs != d2->nargs)
1747 return 1;
1748 if (strcmp (d1->expansion, d2->expansion))
1749 return 1;
1750 if (CPP_PEDANTIC (pfile)
1751 && d1->argnames && d2->argnames)
1753 U_CHAR *arg1 = d1->argnames;
1754 U_CHAR *arg2 = d2->argnames;
1755 size_t len;
1756 int i = d1->nargs;
1757 while (i--)
1759 len = strlen (arg1) + 1;
1760 if (strcmp (arg1, arg2))
1761 return 1;
1762 arg1 += len;
1763 arg2 += len;
1766 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1767 a1 = a1->next, a2 = a2->next)
1769 if (a1->nchars != a2->nchars
1770 || a1->argno != a2->argno
1771 || a1->stringify != a2->stringify
1772 || a1->raw_before != a2->raw_before
1773 || a1->raw_after != a2->raw_after)
1774 return 1;
1776 if (a1 != a2)
1777 return 1;
1779 return 0;
1782 /* Dump the definition of macro MACRO on stdout. The format is suitable
1783 to be read back in again. */
1785 void
1786 _cpp_dump_definition (pfile, hp)
1787 cpp_reader *pfile;
1788 HASHNODE *hp;
1790 CPP_RESERVE (pfile, hp->length + sizeof "#define ");
1791 CPP_PUTS_Q (pfile, "#define ", sizeof "#define " - 1);
1792 CPP_PUTS_Q (pfile, hp->name, hp->length);
1794 if (hp->type == T_EMPTY)
1795 /* do nothing */;
1796 else if (hp->type == T_FMACRO)
1797 dump_DEFINITION (pfile, hp->value.defn);
1798 else
1800 CPP_PUTC_Q (pfile, ' ');
1802 if (hp->type == T_IDENTITY)
1803 CPP_PUTS (pfile, hp->name, hp->length);
1804 else if (hp->type == T_MCONST)
1805 CPP_PUTS (pfile, hp->value.cpval, strlen (hp->value.cpval));
1806 else if (hp->type == T_MACRO)
1808 /* The first and last two characters of a macro expansion are
1809 always "\r "; this needs to be trimmed out.
1810 So we need length-4 chars of space, plus one for the NUL. */
1811 CPP_RESERVE (pfile, hp->value.defn->length - 4 + 1);
1812 CPP_PUTS_Q (pfile, hp->value.defn->expansion + 2,
1813 hp->value.defn->length - 4);
1815 else
1816 cpp_ice (pfile, "invalid hash type %d in dump_definition", hp->type);
1818 if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
1819 CPP_PUTC (pfile, '\n');
1822 static void
1823 dump_DEFINITION (pfile, defn)
1824 cpp_reader *pfile;
1825 DEFINITION *defn;
1827 struct reflist *r;
1828 unsigned char **argv = (unsigned char **) alloca (defn->nargs *
1829 sizeof(char *));
1830 int *argl = (int *) alloca (defn->nargs * sizeof(int));
1831 unsigned char *x;
1832 int i;
1834 /* First extract the argument list. */
1835 x = defn->argnames;
1836 for (i = 0; i < defn->nargs; i++)
1838 argv[i] = x;
1839 argl[i] = strlen (x);
1840 x += argl[i] + 1;
1843 /* Now print out the argument list. */
1844 CPP_PUTC_Q (pfile, '(');
1845 for (i = 0; i < defn->nargs; i++)
1847 CPP_RESERVE (pfile, argl[i] + 2);
1848 if (!(i == defn->nargs-1 && defn->rest_args
1849 && !strcmp (argv[i], "__VA_ARGS__")))
1850 CPP_PUTS_Q (pfile, argv[i], argl[i]);
1851 if (i < defn->nargs-1)
1852 CPP_PUTS_Q (pfile, ", ", 2);
1854 if (defn->rest_args)
1855 CPP_PUTS (pfile, "...", 3);
1856 CPP_PUTS (pfile, ") ", 2);
1858 /* Now the definition. */
1859 x = defn->expansion;
1860 for (r = defn->pattern; r; r = r->next)
1862 i = r->nchars;
1863 if (*x == '\r') x += 2, i -= 2;
1864 /* i chars for macro text, plus the length of the macro
1865 argument name, plus one for a stringify marker, plus two for
1866 each concatenation marker. */
1867 CPP_RESERVE (pfile,
1868 i + argl[r->argno] + r->stringify
1869 + (r->raw_before + r->raw_after) * 2);
1871 if (i > 0) CPP_PUTS_Q (pfile, x, i);
1872 if (r->raw_before)
1873 CPP_PUTS_Q (pfile, "##", 2);
1874 if (r->stringify)
1875 CPP_PUTC_Q (pfile, '#');
1876 CPP_PUTS_Q (pfile, argv[r->argno], argl[r->argno]);
1877 if (r->raw_after && !(r->next && r->next->nchars == 0
1878 && r->next->raw_before))
1879 CPP_PUTS_Q (pfile, "##", 2);
1881 x += i;
1884 i = defn->length - (x - defn->expansion) - 2;
1885 if (*x == '\r') x += 2, i -= 2;
1886 if (i > 0) CPP_PUTS (pfile, x, i);
1889 /* Dump out the hash table. */
1890 static int
1891 dump_hash_helper (h, p)
1892 void **h;
1893 void *p;
1895 HASHNODE *hp = (HASHNODE *)*h;
1896 cpp_reader *pfile = (cpp_reader *)p;
1898 if (hp->type == T_MACRO)
1899 _cpp_dump_definition (pfile, hp);
1900 return 1;
1903 void
1904 _cpp_dump_macro_hash (pfile)
1905 cpp_reader *pfile;
1907 htab_traverse (pfile->hashtab, dump_hash_helper, pfile);