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
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! */
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 int dump_hash_helper PARAMS ((void **, void *));
39 static int comp_def_part PARAMS ((int, U_CHAR *, int, U_CHAR *,
41 static void push_macro_expansion PARAMS ((cpp_reader *,
42 U_CHAR *, int, HASHNODE *));
43 static int unsafe_chars PARAMS ((cpp_reader *, int, int));
44 static int macro_cleanup PARAMS ((cpp_buffer *, cpp_reader *));
45 static enum cpp_ttype macarg PARAMS ((cpp_reader *, int));
46 static void special_symbol PARAMS ((HASHNODE *, cpp_reader *));
48 /* Initial hash table size. (It can grow if necessary - see hashtab.c.) */
51 /* The arglist structure is built by create_definition to tell
52 collect_expansion where the argument names begin. That
53 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
54 would contain pointers to the strings x, y, and z.
55 collect_expansion would then build a DEFINITION node,
56 with reflist nodes pointing to the places x, y, and z had
57 appeared. So the arglist is just convenience data passed
58 between these two routines. It is not kept around after
59 the current #define has been processed and entered into the
77 static DEFINITION *collect_expansion PARAMS ((cpp_reader *, struct arglist *));
78 static struct arglist *collect_formal_parameters PARAMS ((cpp_reader *));
80 /* This structure represents one parsed argument in a macro call.
81 `raw' points to the argument text as written (`raw_length' is its length).
82 `expanded' points to the argument's macro-expansion
83 (its length is `expand_length').
84 `stringified_length' is the length the argument would have
87 /* raw and expanded are relative to ARG_BASE */
88 #define ARG_BASE ((pfile)->token_buffer)
92 /* Strings relative to pfile->token_buffer */
93 long raw, expanded, stringified;
94 int raw_length, expand_length;
95 int stringified_length;
98 /* Calculate hash of a string of length LEN. */
100 _cpp_calc_hash (str, len)
108 r = r * 67 + (*str++ - 113);
113 /* Calculate hash of a HASHNODE structure. */
118 const HASHNODE *h = (const HASHNODE *)x;
122 /* Compare two HASHNODE structures. */
128 const HASHNODE *a = (const HASHNODE *)x;
129 const HASHNODE *b = (const HASHNODE *)y;
131 return (a->length == b->length
132 && !strncmp (a->name, b->name, a->length));
135 /* Destroy a HASHNODE. */
140 HASHNODE *h = (HASHNODE *)x;
142 if (h->type == T_MACRO)
143 _cpp_free_definition (h->value.defn);
144 else if (h->type == T_MCONST)
145 free ((void *) h->value.cpval);
146 free ((void *) h->name);
150 /* Allocate and initialize a HASHNODE structure.
151 Caller must fill in the value field. */
154 _cpp_make_hashnode (name, len, type, hash)
160 HASHNODE *hp = (HASHNODE *) xmalloc (sizeof (HASHNODE));
161 U_CHAR *p = xmalloc (len + 1);
168 memcpy (p, name, len);
174 /* Find the hash node for name "name", which ends at the first
177 If LEN is >= 0, it is the length of the name.
178 Otherwise, compute the length now. */
181 _cpp_lookup (pfile, name, len)
191 for (bp = name; is_idchar (*bp); bp++);
197 dummy.hash = _cpp_calc_hash (name, len);
199 return (HASHNODE *) htab_find_with_hash (pfile->hashtab,
200 (void *)&dummy, dummy.hash);
203 /* Find the hashtable slot for name "name". Used to insert or delete. */
206 _cpp_lookup_slot (pfile, name, len, insert, hash)
210 enum insert_option insert;
219 for (bp = name; is_idchar (*bp); bp++)
227 dummy.hash = _cpp_calc_hash (name, len);
229 slot = (HASHNODE **) htab_find_slot_with_hash (pfile->hashtab,
237 /* Init the hash table. In here so it can see the hash and eq functions. */
239 _cpp_init_macro_hash (pfile)
242 pfile->hashtab = htab_create (HASHSIZE, hash_HASHNODE,
243 eq_HASHNODE, del_HASHNODE);
246 /* Free a DEFINITION structure. Used by delete_macro, and by
247 do_define when redefining macros. */
250 _cpp_free_definition (d)
253 struct reflist *ap, *nextap;
255 for (ap = d->pattern; ap != NULL; ap = nextap)
266 macro_cleanup (pbuf, pfile)
268 cpp_reader *pfile ATTRIBUTE_UNUSED;
270 HASHNODE *macro = pbuf->macro;
271 if (macro->type == T_DISABLED)
272 macro->type = T_MACRO;
273 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
274 free ((PTR) pbuf->buf);
278 /* Read a replacement list for a macro, and build the DEFINITION
279 structure. ARGLIST specifies the formal parameters to look for in
280 the text of the definition. If ARGLIST is null, this is an
281 object-like macro; if it points to an empty arglist, this is a
282 function-like macro with no arguments.
284 A good half of this is devoted to supporting -traditional.
288 collect_expansion (pfile, arglist)
290 struct arglist *arglist;
293 struct reflist *pat = 0, *endpat = 0;
294 enum cpp_ttype token;
295 long start, here, last;
301 enum { START = 0, NORM, ARG, STRIZE, PASTE } last_token = START;
305 argv = arglist->argv;
306 argc = arglist->argc;
314 last = start = CPP_WRITTEN (pfile);
315 last -= 2; /* two extra chars for the leading escape */
318 /* Macro expansion is off, so we are guaranteed not to see POP
320 here = CPP_WRITTEN (pfile);
321 token = _cpp_get_define_token (pfile);
322 tok = pfile->token_buffer + here;
327 cpp_ice (pfile, "EOF in collect_expansion");
333 if (last_token == STRIZE || last_token == PASTE
334 || last_token == START)
335 CPP_SET_WRITTEN (pfile, here);
339 /* # is not special in object-like macros. It is special in
340 function-like macros with no args. (6.10.3.2 para 1.) */
343 /* # is not special immediately after PASTE.
344 (Implied by 6.10.3.3 para 4.) */
345 if (last_token == PASTE)
348 CPP_SET_WRITTEN (pfile, here); /* delete from replacement text */
352 /* If the last token was an argument, discard this token and
353 any hspace between it and the argument's position. Then
354 mark the arg raw_after. */
355 if (last_token == ARG)
357 endpat->raw_after = 1;
359 CPP_SET_WRITTEN (pfile, last);
362 else if (last_token == PASTE)
363 /* ## ## - the second ## is ordinary. */
365 else if (last_token == START)
366 cpp_error (pfile, "`##' at start of macro definition");
368 /* Discard the token and any hspace before it. */
369 while (is_hspace (pfile->token_buffer[here-1]))
371 CPP_SET_WRITTEN (pfile, here);
373 if (last_token == STRIZE)
374 /* Oops - that wasn't a stringify operator. */
375 CPP_PUTC (pfile, '#');
380 /* We must be in -traditional mode. Pretend this was a
381 token paste, but only if there was no leading or
382 trailing space and it's in the middle of the line.
383 _cpp_lex_token won't return a COMMENT if there was trailing
385 CPP_SET_WRITTEN (pfile, here);
386 if (last_token == START)
388 if (is_hspace (pfile->token_buffer[here-1]))
390 if (last_token == ARG)
391 endpat->raw_after = 1;
397 if (last_token == STRIZE)
398 cpp_error (pfile, "`#' is not followed by a macro argument name");
400 if (CPP_TRADITIONAL (pfile) || CPP_WTRADITIONAL (pfile))
401 goto maybe_trad_stringify;
406 for (i = 0; i < argc; i++)
407 if (!strncmp (tok, argv[i].name, argv[i].len)
408 && tok + argv[i].len == CPP_PWRITTEN (pfile))
414 if (last_token == STRIZE)
415 cpp_error (pfile, "`#' is not followed by a macro argument name");
423 struct reflist *tpat;
425 /* Make a pat node for this arg and add it to the pat list */
426 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
428 tpat->raw_before = (last_token == PASTE);
430 tpat->stringify = (last_token == STRIZE);
431 tpat->rest_args = argv[i].rest_arg;
433 tpat->nchars = here - last;
442 CPP_SET_WRITTEN (pfile, here); /* discard arg name */
446 maybe_trad_stringify:
449 U_CHAR *base, *p, *limit;
450 struct reflist *tpat;
452 base = p = pfile->token_buffer + here;
453 limit = CPP_PWRITTEN (pfile);
459 for (i = 0; i < argc; i++)
460 if (!strncmp (tok, argv[i].name, argv[i].len)
461 && ! is_idchar (tok[argv[i].len]))
466 if (!CPP_TRADITIONAL (pfile))
468 /* Must have got here because of -Wtraditional. */
470 "macro argument `%.*s' would be stringified with -traditional",
471 (int) argv[i].len, argv[i].name);
474 if (CPP_WTRADITIONAL (pfile))
475 cpp_warning (pfile, "macro argument `%.*s' is stringified",
476 (int) argv[i].len, argv[i].name);
478 /* Remove the argument from the string. */
479 memmove (p, p + argv[i].len, limit - (p + argv[i].len));
480 limit -= argv[i].len;
482 /* Make a pat node for this arg and add it to the pat list */
483 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
486 /* Don't attempt to paste this with anything. */
487 tpat->raw_before = 0;
490 tpat->rest_args = argv[i].rest_arg;
492 tpat->nchars = (p - base) + here - last;
499 last = (p - base) + here;
501 CPP_ADJUST_WRITTEN (pfile, CPP_PWRITTEN (pfile) - limit);
506 if (last_token == STRIZE)
507 cpp_error (pfile, "`#' is not followed by a macro argument name");
508 else if (last_token == PASTE)
509 cpp_error (pfile, "`##' at end of macro definition");
511 if (last_token == START)
513 /* Empty macro definition. */
514 exp = (U_CHAR *) xstrdup ("\r \r ");
519 /* Trim trailing white space from definition. */
520 here = CPP_WRITTEN (pfile);
521 while (here > last && is_hspace (pfile->token_buffer [here-1]))
523 CPP_SET_WRITTEN (pfile, here);
524 len = CPP_WRITTEN (pfile) - start + 1;
525 /* space for no-concat markers at either end */
526 exp = (U_CHAR *) xmalloc (len + 4);
532 memcpy (&exp[2], pfile->token_buffer + start, len - 1);
535 CPP_SET_WRITTEN (pfile, start);
537 defn = (DEFINITION *) xmalloc (sizeof (DEFINITION));
538 defn->length = len + 3;
539 defn->expansion = exp;
545 defn->argnames = arglist->namebuf;
548 defn->rest_args = argv[argc - 1].rest_arg;
562 static struct arglist *
563 collect_formal_parameters (pfile)
566 struct arglist *result = 0;
567 struct arg *argv = 0;
568 U_CHAR *namebuf = (U_CHAR *) xstrdup ("");
575 enum cpp_ttype token;
578 old_written = CPP_WRITTEN (pfile);
579 token = _cpp_get_directive_token (pfile);
580 if (token != CPP_LPAREN)
582 cpp_ice (pfile, "first token = %d not %d in collect_formal_parameters",
587 argv = (struct arg *) xmalloc (sizeof (struct arg));
589 argv[argc].rest_arg = 0;
592 CPP_SET_WRITTEN (pfile, old_written);
593 token = _cpp_get_directive_token (pfile);
597 tok = pfile->token_buffer + old_written;
598 len = CPP_PWRITTEN (pfile) - tok;
600 && (name = (U_CHAR *) strstr (namebuf, tok))
602 && (name == namebuf || name[-1] == ','))
604 cpp_error (pfile, "duplicate macro argument name `%s'", tok);
607 if (CPP_PEDANTIC (pfile) && CPP_OPTION (pfile, c99)
608 && len == sizeof "__VA_ARGS__" - 1
609 && !strncmp (tok, "__VA_ARGS__", len))
611 "C99 does not permit use of `__VA_ARGS__' as a macro argument name");
612 namebuf = (U_CHAR *) xrealloc (namebuf, argslen + len + 1);
613 name = &namebuf[argslen - 1];
616 memcpy (name, tok, len);
619 argv[argc].len = len;
620 argv[argc].rest_arg = 0;
625 argv = (struct arg *) xrealloc (argv, (argc + 1)*sizeof(struct arg));
636 cpp_error (pfile, "missing right paren in macro argument list");
640 cpp_error (pfile, "syntax error in #define");
646 /* There are two possible styles for a vararg macro:
647 the C99 way: #define foo(a, ...) a, __VA_ARGS__
648 the gnu way: #define foo(a, b...) a, b
649 The C99 way can be considered a special case of the gnu way.
650 There are also some constraints to worry about, but we'll handle
652 if (argv[argc].len == 0)
654 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
655 cpp_pedwarn (pfile, "C89 does not permit varargs macros");
657 len = sizeof "__VA_ARGS__" - 1;
658 namebuf = (U_CHAR *) xrealloc (namebuf, argslen + len + 1);
659 name = &namebuf[argslen - 1];
661 memcpy (name, "__VA_ARGS__", len);
662 argv[argc].len = len;
665 if (CPP_PEDANTIC (pfile))
666 cpp_pedwarn (pfile, "ISO C does not permit named varargs macros");
668 argv[argc].rest_arg = 1;
670 token = _cpp_get_directive_token (pfile);
671 if (token != CPP_RPAREN)
673 cpp_error (pfile, "another parameter follows `...'");
678 /* Go through argv and fix up the pointers. */
680 for (i = 0; i <= argc; i++)
682 argv[i].name = namebuf + len;
683 len += argv[i].len + 1;
684 namebuf[len - 1] = '\0';
687 CPP_SET_WRITTEN (pfile, old_written);
689 result = (struct arglist *) xmalloc (sizeof (struct arglist));
690 if (namebuf[0] != '\0')
692 result->namebuf = namebuf;
693 result->argc = argc + 1;
714 /* Create a DEFINITION node for a macro. The reader's point is just
715 after the macro name. If FUNLIKE is true, this is a function-like
719 _cpp_create_definition (pfile, funlike)
723 struct arglist *args = 0;
724 unsigned int line, col;
728 line = CPP_BUF_LINE (CPP_BUFFER (pfile));
729 col = CPP_BUF_COL (CPP_BUFFER (pfile));
730 file = CPP_BUFFER (pfile)->nominal_fname;
734 args = collect_formal_parameters (pfile);
739 defn = collect_expansion (pfile, args);
750 * Parse a macro argument and append the info on PFILE's token_buffer.
751 * REST_ARGS means to absorb the rest of the args.
752 * Return nonzero to indicate a syntax error.
755 static enum cpp_ttype
756 macarg (pfile, rest_args)
761 enum cpp_ttype token;
763 /* Try to parse as much of the argument as exists at this
764 input stack level. */
767 token = cpp_get_token (pfile);
773 /* If we've hit end of file, it's an error (reported by caller).
774 Ditto if it's the end of cpp_expand_to_buffer text.
775 If we've hit end of macro, just continue. */
776 if (!CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
787 /* if we've returned to lowest level and
788 we aren't absorbing all args */
789 if (paren == 0 && rest_args == 0)
793 /* Remove ',' or ')' from argument buffer. */
794 CPP_ADJUST_WRITTEN (pfile, -1);
802 static const char * const monthnames[] =
804 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
805 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
808 /* Place into PFILE a quoted string representing the string SRC.
809 Caller must reserve enough space in pfile->token_buffer. */
812 _cpp_quote_string (pfile, src)
818 CPP_PUTC_Q (pfile, '\"');
820 switch ((c = *src++))
824 CPP_PUTC_Q (pfile, c);
827 sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
828 CPP_ADJUST_WRITTEN (pfile, 4);
834 CPP_PUTC_Q (pfile, '\\');
835 CPP_PUTC_Q (pfile, c);
839 CPP_PUTC_Q (pfile, '\"');
845 * expand things like __FILE__. Place the expansion into the output
846 * buffer *without* rescanning.
849 #define DSC(str) (const U_CHAR *)str, sizeof str - 1
851 special_symbol (hp, pfile)
862 ip = cpp_file_buffer (pfile);
865 CPP_PUTS (pfile, "\"\"", 2);
868 if (hp->type == T_BASE_FILE)
869 while (CPP_PREV_BUFFER (ip) != NULL)
870 ip = CPP_PREV_BUFFER (ip);
872 buf = ip->nominal_fname;
873 CPP_RESERVE (pfile, 3 + 4 * strlen (buf));
874 _cpp_quote_string (pfile, buf);
877 case T_INCLUDE_LEVEL:
879 int true_indepth = 0;
880 ip = cpp_file_buffer (pfile);
884 ip = CPP_PREV_BUFFER (ip);
887 CPP_RESERVE (pfile, 10);
888 sprintf (CPP_PWRITTEN (pfile), "%d", true_indepth);
889 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
894 #ifdef STDC_0_IN_SYSTEM_HEADERS
895 ip = cpp_file_buffer (pfile);
896 if (ip && ip->system_header_p
897 && !cpp_defined (pfile, DSC("__STRICT_ANSI__")))
899 CPP_PUTC (pfile, '0');
903 /* else fall through */
907 buf = hp->value.cpval;
913 CPP_PUTS (pfile, buf, strlen (buf));
917 ip = cpp_file_buffer (pfile);
920 CPP_PUTC (pfile, '0');
923 CPP_RESERVE (pfile, 10);
924 sprintf (CPP_PWRITTEN (pfile), "%u", CPP_BUF_LINE (ip));
925 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
930 /* Generate both __DATE__ and __TIME__, stuff them into their
931 respective hash nodes, and mark the nodes T_MCONST so we
932 don't have to do this again. We don't generate these strings
933 at init time because time() and localtime() are very slow on
936 time_t tt = time (NULL);
937 struct tm *tb = localtime (&tt);
940 if (hp->type == T_DATE)
941 d = hp, t = _cpp_lookup (pfile, DSC("__TIME__"));
943 t = hp, d = _cpp_lookup (pfile, DSC("__DATE__"));
945 d->value.cpval = xmalloc (sizeof "'Oct 11 1347'");
946 sprintf ((char *)d->value.cpval, "\"%s %2d %4d\"",
947 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
950 t->value.cpval = xmalloc (sizeof "'12:34:56'");
951 sprintf ((char *)t->value.cpval, "\"%02d:%02d:%02d\"",
952 tb->tm_hour, tb->tm_min, tb->tm_sec);
958 cpp_error (pfile, "attempt to use poisoned `%s'.", hp->name);
959 CPP_PUTC (pfile, '0');
963 cpp_ice (pfile, "invalid special hash type");
969 /* Expand a macro call.
970 HP points to the symbol that is the macro being called.
971 Put the result of expansion onto the input stack
972 so that subsequent input by our caller will use it.
974 If macro wants arguments, caller has already verified that
975 an argument list follows; arguments come from the input stack. */
978 _cpp_macroexpand (pfile, hp)
984 register U_CHAR *xbuf;
985 unsigned int start_line, start_column;
988 struct argdata *args = 0;
989 long old_written = CPP_WRITTEN (pfile);
990 int rest_args, rest_zero = 0;
993 ip = cpp_file_buffer (pfile);
996 start_line = CPP_BUF_LINE (ip);
997 start_column = CPP_BUF_COL (ip);
1000 start_line = start_column = 0;
1002 /* Check for and handle special symbols. */
1003 if (hp->type != T_MACRO)
1005 special_symbol (hp, pfile);
1006 xbuf_len = CPP_WRITTEN (pfile) - old_written;
1007 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1008 CPP_SET_WRITTEN (pfile, old_written);
1009 memcpy (xbuf, CPP_PWRITTEN (pfile), xbuf_len + 1);
1010 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
1011 CPP_BUFFER (pfile)->has_escapes = 1;
1015 defn = hp->value.defn;
1016 nargs = defn->nargs;
1017 pfile->output_escapes++;
1021 enum cpp_ttype token;
1023 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
1025 for (i = 0; i < nargs; i++)
1027 args[i].raw = args[i].expanded = 0;
1028 args[i].raw_length = 0;
1029 args[i].expand_length = args[i].stringified_length = -1;
1032 /* Parse all the macro args that are supplied. I counts them.
1033 The first NARGS args are stored in ARGS.
1034 The rest are discarded. If rest_args is set then we assume
1035 macarg absorbed the rest of the args. */
1039 /* Skip over the opening parenthesis. */
1040 CPP_OPTION (pfile, discard_comments)++;
1041 pfile->no_macro_expand++;
1042 pfile->no_directives++;
1044 token = cpp_get_non_space_token (pfile);
1045 if (token != CPP_LPAREN)
1046 cpp_ice (pfile, "macroexpand: unexpected token %d (wanted LPAREN)",
1048 CPP_ADJUST_WRITTEN (pfile, -1);
1055 if (i < nargs || (nargs == 0 && i == 0))
1057 /* if we are working on last arg which absorbs rest of args... */
1058 if (i == nargs - 1 && defn->rest_args)
1060 args[i].raw = CPP_WRITTEN (pfile);
1061 token = macarg (pfile, rest_args);
1062 args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
1065 token = macarg (pfile, 0);
1066 if (token == CPP_EOF || token == CPP_POP)
1067 cpp_error_with_line (pfile, start_line, start_column,
1068 "unterminated macro call");
1071 while (token == CPP_COMMA);
1072 CPP_OPTION (pfile, discard_comments)--;
1073 pfile->no_macro_expand--;
1074 pfile->no_directives--;
1075 if (token != CPP_RPAREN)
1078 /* foo ( ) is equivalent to foo () unless foo takes exactly one
1079 argument, in which case the former is allowed and the latter
1080 is not. XXX C99 is silent on this rule, but it seems
1081 inconsistent to me. */
1082 if (i == 1 && nargs != 1)
1084 register U_CHAR *bp = ARG_BASE + args[0].raw;
1085 register U_CHAR *lim = bp + args[0].raw_length;
1086 while (bp != lim && is_space(*bp))
1092 /* Don't output an error message if we have already output one for
1093 a parse error above. */
1095 if (nargs == 0 && i > 0)
1097 cpp_error (pfile, "arguments given to macro `%s'", hp->name);
1101 /* traditional C allows foo() if foo wants one argument. */
1102 if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
1104 /* the rest args token is allowed to absorb 0 tokens */
1105 else if (i == nargs - 1 && defn->rest_args)
1108 cpp_error (pfile, "macro `%s' used without args", hp->name);
1110 cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
1112 cpp_error (pfile, "macro `%s' used with only %d args",
1118 "macro `%s' used with too many (%d) args", hp->name, i);
1122 /* If macro wants zero args, we parsed the arglist for checking only.
1123 Read directly from the macro definition. */
1126 xbuf = defn->expansion;
1127 xbuf_len = defn->length;
1131 register U_CHAR *exp = defn->expansion;
1132 register int offset; /* offset in expansion,
1133 copied a piece at a time */
1134 register int totlen; /* total amount of exp buffer filled so far */
1136 register struct reflist *ap, *last_ap;
1138 /* Macro really takes args. Compute the expansion of this call. */
1140 /* Compute length in characters of the macro's expansion.
1141 Also count number of times each arg is used. */
1142 xbuf_len = defn->length;
1143 for (ap = defn->pattern; ap != NULL; ap = ap->next)
1147 register struct argdata *arg = &args[ap->argno];
1148 /* Stringify if it hasn't already been */
1149 if (arg->stringified_length < 0)
1151 int arglen = arg->raw_length;
1155 /* Initially need_space is -1. Otherwise, 1 means the
1156 previous character was a space, but we suppressed it;
1157 0 means the previous character was a non-space. */
1158 int need_space = -1;
1160 arg->stringified = CPP_WRITTEN (pfile);
1161 if (!CPP_TRADITIONAL (pfile))
1162 CPP_PUTC (pfile, '\"'); /* insert beginning quote */
1163 for (; i < arglen; i++)
1165 c = (ARG_BASE + arg->raw)[i];
1169 /* Delete "\r " and "\r-" escapes. */
1175 /* Internal sequences of whitespace are
1176 replaced by one space except within
1177 a string or char token. */
1178 else if (is_space(c))
1180 if (need_space == 0)
1184 else if (need_space > 0)
1185 CPP_PUTC (pfile, ' ');
1200 else if (c == '\"' || c == '\'')
1204 /* Escape these chars */
1205 if (c == '\"' || (in_string && c == '\\'))
1206 CPP_PUTC (pfile, '\\');
1208 CPP_PUTC (pfile, c);
1211 CPP_RESERVE (pfile, 4);
1212 sprintf ((char *) CPP_PWRITTEN (pfile), "\\%03o",
1214 CPP_ADJUST_WRITTEN (pfile, 4);
1217 if (!CPP_TRADITIONAL (pfile))
1218 CPP_PUTC (pfile, '\"'); /* insert ending quote */
1219 arg->stringified_length
1220 = CPP_WRITTEN (pfile) - arg->stringified;
1222 xbuf_len += args[ap->argno].stringified_length;
1224 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
1225 /* Add 4 for two \r-space markers to prevent
1226 token concatenation. */
1227 xbuf_len += args[ap->argno].raw_length + 4;
1230 /* We have an ordinary (expanded) occurrence of the arg.
1231 So compute its expansion, if we have not already. */
1232 if (args[ap->argno].expand_length < 0)
1234 args[ap->argno].expanded = CPP_WRITTEN (pfile);
1235 _cpp_expand_to_buffer (pfile,
1236 ARG_BASE + args[ap->argno].raw,
1237 args[ap->argno].raw_length);
1239 args[ap->argno].expand_length
1240 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
1243 /* Add 4 for two \r-space markers to prevent
1244 token concatenation. */
1245 xbuf_len += args[ap->argno].expand_length + 4;
1249 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1251 /* Generate in XBUF the complete expansion
1252 with arguments substituted in.
1253 TOTLEN is the total size generated so far.
1254 OFFSET is the index in the definition
1255 of where we are copying from. */
1256 offset = totlen = 0;
1257 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
1258 last_ap = ap, ap = ap->next)
1260 register struct argdata *arg = &args[ap->argno];
1261 int count_before = totlen;
1263 /* Add chars to XBUF. */
1265 memcpy (&xbuf[totlen], &exp[offset], i);
1269 /* If followed by an empty rest arg with concatenation,
1270 delete the last run of nonwhite chars. */
1271 if (rest_zero && totlen > count_before
1272 && ((ap->rest_args && ap->raw_before)
1273 || (last_ap != NULL && last_ap->rest_args
1274 && last_ap->raw_after)))
1276 /* Delete final whitespace. */
1277 while (totlen > count_before && is_space(xbuf[totlen - 1]))
1280 /* Delete the nonwhites before them. */
1281 while (totlen > count_before && !is_space(xbuf[totlen - 1]))
1285 if (ap->stringify != 0)
1287 memcpy (xbuf + totlen, ARG_BASE + arg->stringified,
1288 arg->stringified_length);
1289 totlen += arg->stringified_length;
1291 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
1293 U_CHAR *p1 = ARG_BASE + arg->raw;
1294 U_CHAR *l1 = p1 + arg->raw_length;
1297 /* Arg is concatenated before: delete leading whitespace,
1298 whitespace markers, and no-reexpansion markers. */
1301 if (is_space(p1[0]))
1303 else if (p1[0] == '\r')
1311 /* Arg is concatenated after: delete trailing whitespace,
1312 whitespace markers, and no-reexpansion markers. */
1315 if (is_space(l1[-1]))
1317 else if (l1[-1] == '\r')
1319 else if (l1[-1] == '-')
1321 if (l1 != p1 + 1 && l1[-2] == '\r')
1331 /* Delete any no-reexpansion marker that precedes
1332 an identifier at the beginning of the argument. */
1333 if (p1[0] == '\r' && p1[1] == '-')
1336 memcpy (xbuf + totlen, p1, l1 - p1);
1341 U_CHAR *expanded = ARG_BASE + arg->expanded;
1342 if (!ap->raw_before && totlen > 0 && arg->expand_length
1343 && !CPP_TRADITIONAL (pfile)
1344 && unsafe_chars (pfile, xbuf[totlen - 1], expanded[0]))
1346 xbuf[totlen++] = '\r';
1347 xbuf[totlen++] = ' ';
1350 memcpy (xbuf + totlen, expanded, arg->expand_length);
1351 totlen += arg->expand_length;
1353 if (!ap->raw_after && totlen > 0 && offset < defn->length
1354 && !CPP_TRADITIONAL (pfile)
1355 && unsafe_chars (pfile, xbuf[totlen - 1], exp[offset]))
1357 xbuf[totlen++] = '\r';
1358 xbuf[totlen++] = ' ';
1362 if (totlen > xbuf_len)
1364 cpp_ice (pfile, "buffer overrun in macroexpand");
1369 /* if there is anything left of the definition
1370 after handling the arg list, copy that in too. */
1372 for (i = offset; i < defn->length; i++)
1374 /* if we've reached the end of the macro */
1377 if (!(rest_zero && last_ap != NULL && last_ap->rest_args
1378 && last_ap->raw_after))
1379 xbuf[totlen++] = exp[i];
1387 pfile->output_escapes--;
1389 /* Now put the expansion on the input stack
1390 so our caller will commence reading from it. */
1391 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
1392 CPP_BUFFER (pfile)->has_escapes = 1;
1394 /* Pop the space we've used in the token_buffer for argument expansion. */
1395 CPP_SET_WRITTEN (pfile, old_written);
1397 /* Recursive macro use sometimes works traditionally.
1398 #define foo(x,y) bar (x (y,0), y)
1401 if (!CPP_TRADITIONAL (pfile))
1402 hp->type = T_DISABLED;
1405 /* Return 1 iff a token ending in C1 followed directly by a token C2
1406 could cause mis-tokenization. */
1409 unsafe_chars (pfile, c1, c2)
1413 /* If c2 is EOF, that's always safe. */
1420 /* We don't know what the previous character was. We do know
1421 that it can't have been an idchar (or else it would have been
1422 pasted with the idchars of the macro name), and there are a
1423 number of second characters for which it doesn't matter what
1425 if (is_idchar (c2) || c2 == '\'' || c2 == '\"'
1426 || c2 == '(' || c2 == '[' || c2 == '{'
1427 || c2 == ')' || c2 == ']' || c2 == '}')
1432 if (c2 == c1 || c2 == '=')
1436 case 'e': case 'E': case 'p': case 'P':
1437 if (c2 == '-' || c2 == '+')
1438 return 1; /* could extend a pre-processing number */
1442 if (CPP_OPTION (pfile, dollars_in_ident))
1447 if (c2 == '\'' || c2 == '\"')
1448 return 1; /* Could turn into L"xxx" or L'xxx'. */
1451 case '.': case '0': case '1': case '2': case '3':
1452 case '4': case '5': case '6': case '7': case '8': case '9':
1453 case '_': case 'a': case 'b': case 'c': case 'd': case 'f':
1454 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1455 case 'm': case 'n': case 'o': case 'q': case 'r': case 's':
1456 case 't': case 'u': case 'v': case 'w': case 'x': case 'y':
1457 case 'z': case 'A': case 'B': case 'C': case 'D': case 'F':
1458 case 'G': case 'H': case 'I': case 'J': case 'K': case 'M':
1459 case 'N': case 'O': case 'Q': case 'R': case 'S': case 'T':
1460 case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
1462 /* We're in the middle of either a name or a pre-processing number. */
1463 return (is_idchar(c2) || c2 == '.');
1465 case '<': case '>': case '!': case '%': case '#': case ':':
1466 case '^': case '&': case '|': case '*': case '/': case '=':
1467 return (c2 == c1 || c2 == '=');
1473 push_macro_expansion (pfile, xbuf, len, hp)
1475 register U_CHAR *xbuf;
1480 int advance_cur = 0;
1482 /* The first chars of the expansion should be a "\r " added by
1483 collect_expansion. This is to prevent accidental token-pasting
1484 between the text preceding the macro invocation, and the macro
1487 We would like to avoid adding unneeded spaces (for the sake of
1488 tools that use cpp, such as imake). In some common cases we can
1489 tell that it is safe to omit the space. */
1491 if (xbuf[0] == '\r' && xbuf[1] == ' '
1492 && !unsafe_chars (pfile, EOF, xbuf[2]))
1495 /* Likewise, avoid the extra space at the end of the macro expansion
1496 if this is safe. We can do a better job here since we can know
1497 what the next char will be. */
1498 if (len >= 3 && xbuf[len-2] == '\r' && xbuf[len-1] == ' '
1499 && !unsafe_chars (pfile, xbuf[len-3], CPP_BUF_PEEK (CPP_BUFFER (pfile))))
1502 /* If the total expansion is "\r \r", we must not trim both escapes. */
1503 if (len == 2 && advance_cur)
1506 mbuf = cpp_push_buffer (pfile, xbuf, len);
1511 mbuf->cleanup = macro_cleanup;
1515 /* Return zero if two DEFINITIONs are isomorphic. */
1518 _cpp_compare_defs (pfile, d1, d2)
1520 DEFINITION *d1, *d2;
1522 struct reflist *a1, *a2;
1523 U_CHAR *p1 = d1->expansion;
1524 U_CHAR *p2 = d2->expansion;
1527 if (d1->nargs != d2->nargs)
1529 if (CPP_PEDANTIC (pfile)
1530 && d1->argnames && d2->argnames)
1532 U_CHAR *arg1 = d1->argnames;
1533 U_CHAR *arg2 = d2->argnames;
1538 len = strlen (arg1) + 1;
1539 if (strcmp (arg1, arg2))
1545 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1546 a1 = a1->next, a2 = a2->next)
1548 if (!((a1->nchars == a2->nchars && !strncmp (p1, p2, a1->nchars))
1549 || !comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
1550 || a1->argno != a2->argno
1551 || a1->stringify != a2->stringify
1552 || a1->raw_before != a2->raw_before
1553 || a1->raw_after != a2->raw_after)
1562 return comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
1563 p2, d2->length - (p2 - d2->expansion), 1);
1566 /* Return 1 if two parts of two macro definitions are effectively different.
1567 One of the parts starts at BEG1 and has LEN1 chars;
1568 the other has LEN2 chars at BEG2.
1569 Any sequence of whitespace matches any other sequence of whitespace.
1570 FIRST means these parts are the first of a macro definition;
1571 so ignore leading whitespace entirely.
1572 LAST means these parts are the last of a macro definition;
1573 so ignore trailing whitespace entirely. */
1576 comp_def_part (first, beg1, len1, beg2, len2, last)
1578 U_CHAR *beg1, *beg2;
1582 register U_CHAR *end1 = beg1 + len1;
1583 register U_CHAR *end2 = beg2 + len2;
1586 while (beg1 != end1 && is_space(*beg1))
1588 while (beg2 != end2 && is_space(*beg2))
1593 while (beg1 != end1 && is_space(end1[-1]))
1595 while (beg2 != end2 && is_space(end2[-1]))
1598 while (beg1 != end1 && beg2 != end2)
1600 if (is_space(*beg1) && is_space(*beg2))
1602 while (beg1 != end1 && is_space(*beg1))
1604 while (beg2 != end2 && is_space(*beg2))
1607 else if (*beg1 == *beg2)
1615 return (beg1 != end1) || (beg2 != end2);
1618 /* Dump the definition of macro MACRO on stdout. The format is suitable
1619 to be read back in again. */
1622 _cpp_dump_definition (pfile, sym, len, defn)
1628 CPP_RESERVE (pfile, len + sizeof "#define ");
1629 CPP_PUTS_Q (pfile, "#define ", sizeof "#define " -1);
1630 CPP_PUTS_Q (pfile, sym, len);
1632 if (defn->nargs == -1)
1634 CPP_PUTC_Q (pfile, ' ');
1636 /* The first and last two characters of a macro expansion are
1637 always "\r "; this needs to be trimmed out.
1638 So we need length-4 chars of space, plus one for the NUL. */
1639 CPP_RESERVE (pfile, defn->length - 4 + 1);
1640 CPP_PUTS_Q (pfile, defn->expansion + 2, defn->length - 4);
1645 unsigned char **argv = (unsigned char **) alloca (defn->nargs *
1647 int *argl = (int *) alloca (defn->nargs * sizeof(int));
1651 /* First extract the argument list. */
1653 for (i = 0; i < defn->nargs; i++)
1656 argl[i] = strlen (x);
1660 /* Now print out the argument list. */
1661 CPP_PUTC_Q (pfile, '(');
1662 for (i = 0; i < defn->nargs; i++)
1664 CPP_RESERVE (pfile, argl[i] + 2);
1665 if (!(i == defn->nargs-1 && defn->rest_args
1666 && !strcmp (argv[i], "__VA_ARGS__")))
1667 CPP_PUTS_Q (pfile, argv[i], argl[i]);
1668 if (i < defn->nargs-1)
1669 CPP_PUTS_Q (pfile, ", ", 2);
1671 if (defn->rest_args)
1672 CPP_PUTS (pfile, "...", 3);
1673 CPP_PUTS (pfile, ") ", 2);
1675 /* Now the definition. */
1676 x = defn->expansion;
1677 for (r = defn->pattern; r; r = r->next)
1680 if (*x == '\r') x += 2, i -= 2;
1681 /* i chars for macro text, plus the length of the macro
1682 argument name, plus one for a stringify marker, plus two for
1683 each concatenation marker. */
1685 i + argl[r->argno] + r->stringify
1686 + (r->raw_before + r->raw_after) * 2);
1688 if (i > 0) CPP_PUTS_Q (pfile, x, i);
1690 CPP_PUTS_Q (pfile, "##", 2);
1692 CPP_PUTC_Q (pfile, '#');
1693 CPP_PUTS_Q (pfile, argv[r->argno], argl[r->argno]);
1694 if (r->raw_after && !(r->next && r->next->nchars == 0
1695 && r->next->raw_before))
1696 CPP_PUTS_Q (pfile, "##", 2);
1701 i = defn->length - (x - defn->expansion) - 2;
1702 if (*x == '\r') x += 2, i -= 2;
1703 if (i > 0) CPP_PUTS (pfile, x, i);
1705 if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
1706 CPP_PUTC (pfile, '\n');
1709 /* Dump out the hash table. */
1711 dump_hash_helper (h, p)
1715 HASHNODE *hp = (HASHNODE *)*h;
1716 cpp_reader *pfile = (cpp_reader *)p;
1718 if (hp->type == T_MACRO)
1719 _cpp_dump_definition (pfile, hp->name, hp->length, hp->value.defn);
1724 _cpp_dump_macro_hash (pfile)
1727 htab_traverse (pfile->hashtab, dump_hash_helper, pfile);