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! */
33 static unsigned int hash_HASHNODE PARAMS ((const void *));
34 static int eq_HASHNODE PARAMS ((const void *, const void *));
35 static void del_HASHNODE PARAMS ((void *));
36 static int dump_hash_helper PARAMS ((void **, void *));
38 static int comp_def_part PARAMS ((int, U_CHAR *, int, U_CHAR *,
40 static void push_macro_expansion PARAMS ((cpp_reader *,
41 U_CHAR *, 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 ((HASHNODE *, cpp_reader *));
47 /* Initial hash table size. (It can grow if necessary - see hashtab.c.) */
50 /* The arglist structure is built by create_definition to tell
51 collect_expansion where the argument names begin. That
52 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
53 would contain pointers to the strings x, y, and z.
54 collect_expansion would then build a DEFINITION node,
55 with reflist nodes pointing to the places x, y, and z had
56 appeared. So the arglist is just convenience data passed
57 between these two routines. It is not kept around after
58 the current #define has been processed and entered into the
76 static DEFINITION *collect_expansion PARAMS ((cpp_reader *, struct arglist *));
77 static struct arglist *collect_formal_parameters PARAMS ((cpp_reader *));
79 /* This structure represents one parsed argument in a macro call.
80 `raw' points to the argument text as written (`raw_length' is its length).
81 `expanded' points to the argument's macro-expansion
82 (its length is `expand_length').
83 `stringified_length' is the length the argument would have
86 /* raw and expanded are relative to ARG_BASE */
87 #define ARG_BASE ((pfile)->token_buffer)
91 /* Strings relative to pfile->token_buffer */
92 long raw, expanded, stringified;
93 int raw_length, expand_length;
94 int stringified_length;
97 /* Calculate hash of a string of length LEN. */
99 _cpp_calc_hash (str, len)
107 r = r * 67 + (*str++ - 113);
112 /* Calculate hash of a HASHNODE structure. */
117 const HASHNODE *h = (const HASHNODE *)x;
121 /* Compare two HASHNODE structures. */
127 const HASHNODE *a = (const HASHNODE *)x;
128 const HASHNODE *b = (const HASHNODE *)y;
130 return (a->length == b->length
131 && !strncmp (a->name, b->name, a->length));
134 /* Destroy a HASHNODE. */
139 HASHNODE *h = (HASHNODE *)x;
141 if (h->type == T_MACRO)
142 _cpp_free_definition (h->value.defn);
143 else if (h->type == T_MCONST)
144 free ((void *) h->value.cpval);
145 free ((void *) h->name);
149 /* Allocate and initialize a HASHNODE structure.
150 Caller must fill in the value field. */
153 _cpp_make_hashnode (name, len, type, hash)
159 HASHNODE *hp = (HASHNODE *) xmalloc (sizeof (HASHNODE));
160 U_CHAR *p = xmalloc (len + 1);
167 memcpy (p, name, len);
173 /* Find the hash node for name "name", which ends at the first
176 If LEN is >= 0, it is the length of the name.
177 Otherwise, compute the length now. */
180 _cpp_lookup (pfile, name, len)
190 for (bp = name; is_idchar (*bp); bp++);
196 dummy.hash = _cpp_calc_hash (name, len);
198 return (HASHNODE *) htab_find_with_hash (pfile->hashtab,
199 (void *)&dummy, dummy.hash);
202 /* Find the hashtable slot for name "name". Used to insert or delete. */
204 _cpp_lookup_slot (pfile, name, len, insert, hash)
217 for (bp = name; is_idchar (*bp); bp++);
223 dummy.hash = _cpp_calc_hash (name, len);
225 slot = (HASHNODE **) htab_find_slot_with_hash (pfile->hashtab,
233 /* Init the hash table. In here so it can see the hash and eq functions. */
235 _cpp_init_macro_hash (pfile)
238 pfile->hashtab = htab_create (HASHSIZE, hash_HASHNODE,
239 eq_HASHNODE, del_HASHNODE);
242 /* Free a DEFINITION structure. Used by delete_macro, and by
243 do_define when redefining macros. */
246 _cpp_free_definition (d)
249 struct reflist *ap, *nextap;
251 for (ap = d->pattern; ap != NULL; ap = nextap)
262 macro_cleanup (pbuf, pfile)
264 cpp_reader *pfile ATTRIBUTE_UNUSED;
266 HASHNODE *macro = pbuf->macro;
267 if (macro->type == T_DISABLED)
268 macro->type = T_MACRO;
269 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
270 free ((PTR) pbuf->buf);
274 /* Read a replacement list for a macro, and build the DEFINITION
275 structure. ARGLIST specifies the formal parameters to look for in
276 the text of the definition. If ARGLIST is null, this is an
277 object-like macro; if it points to an empty arglist, this is a
278 function-like macro with no arguments.
280 A good half of this is devoted to supporting -traditional.
284 collect_expansion (pfile, arglist)
286 struct arglist *arglist;
289 struct reflist *pat = 0, *endpat = 0;
290 enum cpp_ttype token;
291 long start, here, last;
297 enum { START = 0, NORM, ARG, STRIZE, PASTE } last_token = START;
301 argv = arglist->argv;
302 argc = arglist->argc;
310 last = start = CPP_WRITTEN (pfile);
311 last -= 2; /* two extra chars for the leading escape */
314 /* Macro expansion is off, so we are guaranteed not to see POP
316 here = CPP_WRITTEN (pfile);
317 token = _cpp_get_define_token (pfile);
318 tok = pfile->token_buffer + here;
323 cpp_ice (pfile, "EOF in collect_expansion");
329 if (last_token == STRIZE || last_token == PASTE
330 || last_token == START)
331 CPP_SET_WRITTEN (pfile, here);
335 /* # is not special in object-like macros. It is special in
336 function-like macros with no args. (6.10.3.2 para 1.) */
339 /* # is not special immediately after PASTE.
340 (Implied by 6.10.3.3 para 4.) */
341 if (last_token == PASTE)
344 CPP_SET_WRITTEN (pfile, here); /* delete from replacement text */
348 /* If the last token was an argument, discard this token and
349 any hspace between it and the argument's position. Then
350 mark the arg raw_after. */
351 if (last_token == ARG)
353 endpat->raw_after = 1;
355 CPP_SET_WRITTEN (pfile, last);
358 else if (last_token == PASTE)
359 /* ## ## - the second ## is ordinary. */
361 else if (last_token == START)
362 cpp_error (pfile, "`##' at start of macro definition");
364 /* Discard the token and any hspace before it. */
365 while (is_hspace (pfile->token_buffer[here-1]))
367 CPP_SET_WRITTEN (pfile, here);
369 if (last_token == STRIZE)
370 /* Oops - that wasn't a stringify operator. */
371 CPP_PUTC (pfile, '#');
376 /* We must be in -traditional mode. Pretend this was a
377 token paste, but only if there was no leading or
378 trailing space and it's in the middle of the line.
379 _cpp_lex_token won't return a COMMENT if there was trailing
381 CPP_SET_WRITTEN (pfile, here);
382 if (last_token == START)
384 if (is_hspace (pfile->token_buffer[here-1]))
386 if (last_token == ARG)
387 endpat->raw_after = 1;
393 if (last_token == STRIZE)
394 cpp_error (pfile, "`#' is not followed by a macro argument name");
396 if (CPP_TRADITIONAL (pfile) || CPP_WTRADITIONAL (pfile))
397 goto maybe_trad_stringify;
402 for (i = 0; i < argc; i++)
403 if (!strncmp (tok, argv[i].name, argv[i].len)
404 && ! is_idchar (tok[argv[i].len]))
410 if (last_token == STRIZE)
411 cpp_error (pfile, "`#' is not followed by a macro argument name");
419 struct reflist *tpat;
421 /* Make a pat node for this arg and add it to the pat list */
422 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
424 tpat->raw_before = (last_token == PASTE);
426 tpat->stringify = (last_token == STRIZE);
427 tpat->rest_args = argv[i].rest_arg;
429 tpat->nchars = here - last;
438 CPP_SET_WRITTEN (pfile, here); /* discard arg name */
442 maybe_trad_stringify:
445 U_CHAR *base, *p, *limit;
446 struct reflist *tpat;
448 base = p = pfile->token_buffer + here;
449 limit = CPP_PWRITTEN (pfile);
455 for (i = 0; i < argc; i++)
456 if (!strncmp (tok, argv[i].name, argv[i].len)
457 && ! is_idchar (tok[argv[i].len]))
462 if (!CPP_TRADITIONAL (pfile))
464 /* Must have got here because of -Wtraditional. */
466 "macro argument `%.*s' would be stringified with -traditional",
467 (int) argv[i].len, argv[i].name);
470 if (CPP_WTRADITIONAL (pfile))
471 cpp_warning (pfile, "macro argument `%.*s' is stringified",
472 (int) argv[i].len, argv[i].name);
474 /* Remove the argument from the string. */
475 memmove (p, p + argv[i].len, limit - (p + argv[i].len));
476 limit -= argv[i].len;
478 /* Make a pat node for this arg and add it to the pat list */
479 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
482 /* Don't attempt to paste this with anything. */
483 tpat->raw_before = 0;
486 tpat->rest_args = argv[i].rest_arg;
488 tpat->nchars = (p - base) + here - last;
495 last = (p - base) + here;
497 CPP_ADJUST_WRITTEN (pfile, CPP_PWRITTEN (pfile) - limit);
502 if (last_token == STRIZE)
503 cpp_error (pfile, "`#' is not followed by a macro argument name");
504 else if (last_token == PASTE)
505 cpp_error (pfile, "`##' at end of macro definition");
507 if (last_token == START)
509 /* Empty macro definition. */
510 exp = (U_CHAR *) xstrdup ("\r \r ");
515 /* Trim trailing white space from definition. */
516 here = CPP_WRITTEN (pfile);
517 while (here > last && is_hspace (pfile->token_buffer [here-1]))
519 CPP_SET_WRITTEN (pfile, here);
520 CPP_NUL_TERMINATE (pfile);
521 len = CPP_WRITTEN (pfile) - start + 1;
522 /* space for no-concat markers at either end */
523 exp = (U_CHAR *) xmalloc (len + 4);
529 memcpy (&exp[2], pfile->token_buffer + start, len - 1);
532 CPP_SET_WRITTEN (pfile, start);
534 defn = (DEFINITION *) xmalloc (sizeof (DEFINITION));
535 defn->length = len + 3;
536 defn->expansion = exp;
542 defn->argnames = arglist->namebuf;
545 defn->rest_args = argv[argc - 1].rest_arg;
559 static struct arglist *
560 collect_formal_parameters (pfile)
563 struct arglist *result = 0;
564 struct arg *argv = 0;
565 U_CHAR *namebuf = (U_CHAR *) xstrdup ("");
572 enum cpp_ttype token;
575 old_written = CPP_WRITTEN (pfile);
576 token = _cpp_get_directive_token (pfile);
577 if (token != CPP_LPAREN)
579 cpp_ice (pfile, "first token = %d not %d in collect_formal_parameters",
584 argv = (struct arg *) xmalloc (sizeof (struct arg));
586 argv[argc].rest_arg = 0;
589 CPP_SET_WRITTEN (pfile, old_written);
590 token = _cpp_get_directive_token (pfile);
594 tok = pfile->token_buffer + old_written;
595 len = CPP_PWRITTEN (pfile) - tok;
597 && (name = (U_CHAR *) strstr (namebuf, tok))
599 && (name == namebuf || name[-1] == ','))
601 cpp_error (pfile, "duplicate macro argument name `%s'", tok);
604 if (CPP_PEDANTIC (pfile) && CPP_OPTION (pfile, c99)
605 && len == sizeof "__VA_ARGS__" - 1
606 && !strncmp (tok, "__VA_ARGS__", len))
608 "C99 does not permit use of `__VA_ARGS__' as a macro argument name");
609 namebuf = (U_CHAR *) xrealloc (namebuf, argslen + len + 1);
610 name = &namebuf[argslen - 1];
613 memcpy (name, tok, len);
616 argv[argc].len = len;
617 argv[argc].rest_arg = 0;
622 argv = (struct arg *) xrealloc (argv, (argc + 1)*sizeof(struct arg));
633 cpp_error (pfile, "missing right paren in macro argument list");
637 cpp_error (pfile, "syntax error in #define");
643 /* There are two possible styles for a vararg macro:
644 the C99 way: #define foo(a, ...) a, __VA_ARGS__
645 the gnu way: #define foo(a, b...) a, b
646 The C99 way can be considered a special case of the gnu way.
647 There are also some constraints to worry about, but we'll handle
649 if (argv[argc].len == 0)
651 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
652 cpp_pedwarn (pfile, "C89 does not permit varargs macros");
654 len = sizeof "__VA_ARGS__" - 1;
655 namebuf = (U_CHAR *) xrealloc (namebuf, argslen + len + 1);
656 name = &namebuf[argslen - 1];
658 memcpy (name, "__VA_ARGS__", len);
659 argv[argc].len = len;
662 if (CPP_PEDANTIC (pfile))
663 cpp_pedwarn (pfile, "ISO C does not permit named varargs macros");
665 argv[argc].rest_arg = 1;
667 token = _cpp_get_directive_token (pfile);
668 if (token != CPP_RPAREN)
670 cpp_error (pfile, "another parameter follows `...'");
675 /* Go through argv and fix up the pointers. */
677 for (i = 0; i <= argc; i++)
679 argv[i].name = namebuf + len;
680 len += argv[i].len + 1;
681 namebuf[len - 1] = '\0';
684 CPP_SET_WRITTEN (pfile, old_written);
686 result = (struct arglist *) xmalloc (sizeof (struct arglist));
687 if (namebuf[0] != '\0')
689 result->namebuf = namebuf;
690 result->argc = argc + 1;
711 /* Create a DEFINITION node for a macro. The reader's point is just
712 after the macro name. If FUNLIKE is true, this is a function-like
716 _cpp_create_definition (pfile, funlike)
720 struct arglist *args = 0;
721 unsigned int line, col;
725 line = CPP_BUF_LINE (CPP_BUFFER (pfile));
726 col = CPP_BUF_COL (CPP_BUFFER (pfile));
727 file = CPP_BUFFER (pfile)->nominal_fname;
731 args = collect_formal_parameters (pfile);
736 defn = collect_expansion (pfile, args);
747 * Parse a macro argument and append the info on PFILE's token_buffer.
748 * REST_ARGS means to absorb the rest of the args.
749 * Return nonzero to indicate a syntax error.
752 static enum cpp_ttype
753 macarg (pfile, rest_args)
758 enum cpp_ttype token;
760 /* Try to parse as much of the argument as exists at this
761 input stack level. */
764 token = cpp_get_token (pfile);
770 /* If we've hit end of file, it's an error (reported by caller).
771 Ditto if it's the end of cpp_expand_to_buffer text.
772 If we've hit end of macro, just continue. */
773 if (!CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
784 /* if we've returned to lowest level and
785 we aren't absorbing all args */
786 if (paren == 0 && rest_args == 0)
790 /* Remove ',' or ')' from argument buffer. */
791 CPP_ADJUST_WRITTEN (pfile, -1);
799 static const char * const monthnames[] =
801 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
802 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
805 /* Place into PFILE a quoted string representing the string SRC.
806 Caller must reserve enough space in pfile->token_buffer. */
809 _cpp_quote_string (pfile, src)
815 CPP_PUTC_Q (pfile, '\"');
817 switch ((c = *src++))
821 CPP_PUTC_Q (pfile, c);
824 sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
825 CPP_ADJUST_WRITTEN (pfile, 4);
831 CPP_PUTC_Q (pfile, '\\');
832 CPP_PUTC_Q (pfile, c);
836 CPP_PUTC_Q (pfile, '\"');
837 CPP_NUL_TERMINATE_Q (pfile);
843 * expand things like __FILE__. Place the expansion into the output
844 * buffer *without* rescanning.
847 #define DSC(str) (const U_CHAR *)str, sizeof str - 1
849 special_symbol (hp, pfile)
861 ip = cpp_file_buffer (pfile);
862 if (hp->type == T_BASE_FILE)
863 while (CPP_PREV_BUFFER (ip) != NULL)
864 ip = CPP_PREV_BUFFER (ip);
866 buf = ip->nominal_fname;
867 CPP_RESERVE (pfile, 3 + 4 * strlen (buf));
868 _cpp_quote_string (pfile, buf);
871 case T_INCLUDE_LEVEL:
873 int true_indepth = 1;
874 ip = cpp_file_buffer (pfile);
875 while ((ip = CPP_PREV_BUFFER (ip)) != NULL)
878 CPP_RESERVE (pfile, 10);
879 sprintf (CPP_PWRITTEN (pfile), "%d", true_indepth);
880 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
885 #ifdef STDC_0_IN_SYSTEM_HEADERS
886 ip = cpp_file_buffer (pfile);
887 if (ip->system_header_p && !cpp_defined (pfile, DSC("__STRICT_ANSI__")))
889 CPP_RESERVE (pfile, 2);
890 CPP_PUTC_Q (pfile, '0');
891 CPP_NUL_TERMINATE_Q (pfile);
895 /* else fall through */
899 buf = hp->value.cpval;
906 CPP_RESERVE (pfile, len + 1);
907 CPP_PUTS_Q (pfile, buf, len);
908 CPP_NUL_TERMINATE_Q (pfile);
912 ip = cpp_file_buffer (pfile);
913 CPP_RESERVE (pfile, 10);
914 sprintf (CPP_PWRITTEN (pfile), "%u", CPP_BUF_LINE (ip));
915 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
920 /* Generate both __DATE__ and __TIME__, stuff them into their
921 respective hash nodes, and mark the nodes T_MCONST so we
922 don't have to do this again. We don't generate these strings
923 at init time because time() and localtime() are very slow on
926 time_t tt = time (NULL);
927 struct tm *tb = localtime (&tt);
930 if (hp->type == T_DATE)
931 d = hp, t = _cpp_lookup (pfile, DSC("__TIME__"));
933 t = hp, d = _cpp_lookup (pfile, DSC("__DATE__"));
935 d->value.cpval = xmalloc (sizeof "'Oct 11 1347'");
936 sprintf ((char *)d->value.cpval, "\"%s %2d %4d\"",
937 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
940 t->value.cpval = xmalloc (sizeof "'12:34:56'");
941 sprintf ((char *)t->value.cpval, "\"%02d:%02d:%02d\"",
942 tb->tm_hour, tb->tm_min, tb->tm_sec);
948 cpp_error (pfile, "attempt to use poisoned `%s'.", hp->name);
949 CPP_RESERVE (pfile, 1);
950 CPP_PUTC_Q (pfile, '0');
951 CPP_NUL_TERMINATE_Q (pfile);
955 cpp_ice (pfile, "invalid special hash type");
961 /* Expand a macro call.
962 HP points to the symbol that is the macro being called.
963 Put the result of expansion onto the input stack
964 so that subsequent input by our caller will use it.
966 If macro wants arguments, caller has already verified that
967 an argument list follows; arguments come from the input stack. */
970 _cpp_macroexpand (pfile, hp)
976 register U_CHAR *xbuf;
977 unsigned int start_line, start_column;
980 struct argdata *args = 0;
981 long old_written = CPP_WRITTEN (pfile);
982 int rest_args, rest_zero = 0;
985 ip = cpp_file_buffer (pfile);
986 start_line = CPP_BUF_LINE (ip);
987 start_column = CPP_BUF_COL (ip);
989 /* Check for and handle special symbols. */
990 if (hp->type != T_MACRO)
992 special_symbol (hp, pfile);
993 xbuf_len = CPP_WRITTEN (pfile) - old_written;
994 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
995 CPP_SET_WRITTEN (pfile, old_written);
996 memcpy (xbuf, CPP_PWRITTEN (pfile), xbuf_len + 1);
997 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
998 CPP_BUFFER (pfile)->has_escapes = 1;
1002 defn = hp->value.defn;
1003 nargs = defn->nargs;
1004 pfile->output_escapes++;
1008 enum cpp_ttype token;
1010 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
1012 for (i = 0; i < nargs; i++)
1014 args[i].raw = args[i].expanded = 0;
1015 args[i].raw_length = 0;
1016 args[i].expand_length = args[i].stringified_length = -1;
1019 /* Parse all the macro args that are supplied. I counts them.
1020 The first NARGS args are stored in ARGS.
1021 The rest are discarded. If rest_args is set then we assume
1022 macarg absorbed the rest of the args. */
1026 /* Skip over the opening parenthesis. */
1027 CPP_OPTION (pfile, discard_comments)++;
1028 pfile->no_macro_expand++;
1029 pfile->no_directives++;
1031 token = cpp_get_non_space_token (pfile);
1032 if (token != CPP_LPAREN)
1033 cpp_ice (pfile, "macroexpand: unexpected token %d (wanted LPAREN)",
1035 CPP_ADJUST_WRITTEN (pfile, -1);
1042 if (i < nargs || (nargs == 0 && i == 0))
1044 /* if we are working on last arg which absorbs rest of args... */
1045 if (i == nargs - 1 && defn->rest_args)
1047 args[i].raw = CPP_WRITTEN (pfile);
1048 token = macarg (pfile, rest_args);
1049 args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
1052 token = macarg (pfile, 0);
1053 if (token == CPP_EOF || token == CPP_POP)
1054 cpp_error_with_line (pfile, start_line, start_column,
1055 "unterminated macro call");
1058 while (token == CPP_COMMA);
1059 CPP_OPTION (pfile, discard_comments)--;
1060 pfile->no_macro_expand--;
1061 pfile->no_directives--;
1062 if (token != CPP_RPAREN)
1065 /* If we got one arg but it was just whitespace, call that 0 args. */
1068 register U_CHAR *bp = ARG_BASE + args[0].raw;
1069 register U_CHAR *lim = bp + args[0].raw_length;
1070 /* cpp.texi says for foo ( ) we provide one argument.
1071 However, if foo wants just 0 arguments, treat this as 0. */
1073 while (bp != lim && is_space(*bp))
1079 /* Don't output an error message if we have already output one for
1080 a parse error above. */
1082 if (nargs == 0 && i > 0)
1084 cpp_error (pfile, "arguments given to macro `%s'", hp->name);
1088 /* traditional C allows foo() if foo wants one argument. */
1089 if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
1091 /* the rest args token is allowed to absorb 0 tokens */
1092 else if (i == nargs - 1 && defn->rest_args)
1095 cpp_error (pfile, "macro `%s' used without args", hp->name);
1097 cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
1099 cpp_error (pfile, "macro `%s' used with only %d args",
1105 "macro `%s' used with too many (%d) args", hp->name, i);
1109 /* If macro wants zero args, we parsed the arglist for checking only.
1110 Read directly from the macro definition. */
1113 xbuf = defn->expansion;
1114 xbuf_len = defn->length;
1118 register U_CHAR *exp = defn->expansion;
1119 register int offset; /* offset in expansion,
1120 copied a piece at a time */
1121 register int totlen; /* total amount of exp buffer filled so far */
1123 register struct reflist *ap, *last_ap;
1125 /* Macro really takes args. Compute the expansion of this call. */
1127 /* Compute length in characters of the macro's expansion.
1128 Also count number of times each arg is used. */
1129 xbuf_len = defn->length;
1130 for (ap = defn->pattern; ap != NULL; ap = ap->next)
1134 register struct argdata *arg = &args[ap->argno];
1135 /* Stringify if it hasn't already been */
1136 if (arg->stringified_length < 0)
1138 int arglen = arg->raw_length;
1142 /* Initially need_space is -1. Otherwise, 1 means the
1143 previous character was a space, but we suppressed it;
1144 0 means the previous character was a non-space. */
1145 int need_space = -1;
1147 arg->stringified = CPP_WRITTEN (pfile);
1148 if (!CPP_TRADITIONAL (pfile))
1149 CPP_PUTC (pfile, '\"'); /* insert beginning quote */
1150 for (; i < arglen; i++)
1152 c = (ARG_BASE + arg->raw)[i];
1156 /* Delete "\r " and "\r-" escapes. */
1162 /* Internal sequences of whitespace are
1163 replaced by one space except within
1164 a string or char token. */
1165 else if (is_space(c))
1167 if (need_space == 0)
1171 else if (need_space > 0)
1172 CPP_PUTC (pfile, ' ');
1187 else if (c == '\"' || c == '\'')
1191 /* Escape these chars */
1192 if (c == '\"' || (in_string && c == '\\'))
1193 CPP_PUTC (pfile, '\\');
1195 CPP_PUTC (pfile, c);
1198 CPP_RESERVE (pfile, 4);
1199 sprintf ((char *) CPP_PWRITTEN (pfile), "\\%03o",
1201 CPP_ADJUST_WRITTEN (pfile, 4);
1204 if (!CPP_TRADITIONAL (pfile))
1205 CPP_PUTC (pfile, '\"'); /* insert ending quote */
1206 arg->stringified_length
1207 = CPP_WRITTEN (pfile) - arg->stringified;
1209 xbuf_len += args[ap->argno].stringified_length;
1211 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
1212 /* Add 4 for two \r-space markers to prevent
1213 token concatenation. */
1214 xbuf_len += args[ap->argno].raw_length + 4;
1217 /* We have an ordinary (expanded) occurrence of the arg.
1218 So compute its expansion, if we have not already. */
1219 if (args[ap->argno].expand_length < 0)
1221 args[ap->argno].expanded = CPP_WRITTEN (pfile);
1222 _cpp_expand_to_buffer (pfile,
1223 ARG_BASE + args[ap->argno].raw,
1224 args[ap->argno].raw_length);
1226 args[ap->argno].expand_length
1227 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
1230 /* Add 4 for two \r-space markers to prevent
1231 token concatenation. */
1232 xbuf_len += args[ap->argno].expand_length + 4;
1236 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1238 /* Generate in XBUF the complete expansion
1239 with arguments substituted in.
1240 TOTLEN is the total size generated so far.
1241 OFFSET is the index in the definition
1242 of where we are copying from. */
1243 offset = totlen = 0;
1244 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
1245 last_ap = ap, ap = ap->next)
1247 register struct argdata *arg = &args[ap->argno];
1248 int count_before = totlen;
1250 /* Add chars to XBUF. */
1252 memcpy (&xbuf[totlen], &exp[offset], i);
1256 /* If followed by an empty rest arg with concatenation,
1257 delete the last run of nonwhite chars. */
1258 if (rest_zero && totlen > count_before
1259 && ((ap->rest_args && ap->raw_before)
1260 || (last_ap != NULL && last_ap->rest_args
1261 && last_ap->raw_after)))
1263 /* Delete final whitespace. */
1264 while (totlen > count_before && is_space(xbuf[totlen - 1]))
1267 /* Delete the nonwhites before them. */
1268 while (totlen > count_before && !is_space(xbuf[totlen - 1]))
1272 if (ap->stringify != 0)
1274 memcpy (xbuf + totlen, ARG_BASE + arg->stringified,
1275 arg->stringified_length);
1276 totlen += arg->stringified_length;
1278 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
1280 U_CHAR *p1 = ARG_BASE + arg->raw;
1281 U_CHAR *l1 = p1 + arg->raw_length;
1284 /* Arg is concatenated before: delete leading whitespace,
1285 whitespace markers, and no-reexpansion markers. */
1288 if (is_space(p1[0]))
1290 else if (p1[0] == '\r')
1298 /* Arg is concatenated after: delete trailing whitespace,
1299 whitespace markers, and no-reexpansion markers. */
1302 if (is_space(l1[-1]))
1304 else if (l1[-1] == '\r')
1306 else if (l1[-1] == '-')
1308 if (l1 != p1 + 1 && l1[-2] == '\r')
1318 /* Delete any no-reexpansion marker that precedes
1319 an identifier at the beginning of the argument. */
1320 if (p1[0] == '\r' && p1[1] == '-')
1323 memcpy (xbuf + totlen, p1, l1 - p1);
1328 U_CHAR *expanded = ARG_BASE + arg->expanded;
1329 if (!ap->raw_before && totlen > 0 && arg->expand_length
1330 && !CPP_TRADITIONAL (pfile)
1331 && unsafe_chars (pfile, xbuf[totlen - 1], expanded[0]))
1333 xbuf[totlen++] = '\r';
1334 xbuf[totlen++] = ' ';
1337 memcpy (xbuf + totlen, expanded, arg->expand_length);
1338 totlen += arg->expand_length;
1340 if (!ap->raw_after && totlen > 0 && offset < defn->length
1341 && !CPP_TRADITIONAL (pfile)
1342 && unsafe_chars (pfile, xbuf[totlen - 1], exp[offset]))
1344 xbuf[totlen++] = '\r';
1345 xbuf[totlen++] = ' ';
1349 if (totlen > xbuf_len)
1351 cpp_ice (pfile, "buffer overrun in macroexpand");
1356 /* if there is anything left of the definition
1357 after handling the arg list, copy that in too. */
1359 for (i = offset; i < defn->length; i++)
1361 /* if we've reached the end of the macro */
1364 if (!(rest_zero && last_ap != NULL && last_ap->rest_args
1365 && last_ap->raw_after))
1366 xbuf[totlen++] = exp[i];
1374 pfile->output_escapes--;
1376 /* Now put the expansion on the input stack
1377 so our caller will commence reading from it. */
1378 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
1379 CPP_BUFFER (pfile)->has_escapes = 1;
1381 /* Pop the space we've used in the token_buffer for argument expansion. */
1382 CPP_SET_WRITTEN (pfile, old_written);
1384 /* Recursive macro use sometimes works traditionally.
1385 #define foo(x,y) bar (x (y,0), y)
1388 if (!CPP_TRADITIONAL (pfile))
1389 hp->type = T_DISABLED;
1392 /* Return 1 iff a token ending in C1 followed directly by a token C2
1393 could cause mis-tokenization. */
1396 unsafe_chars (pfile, c1, c2)
1403 /* We don't know what the previous character was. We do know
1404 that it can't have been an idchar (or else it would have been
1405 pasted with the idchars of the macro name), and there are a
1406 number of second characters for which it doesn't matter what
1408 if (is_idchar (c2) || c2 == '\'' || c2 == '\"'
1409 || c2 == '(' || c2 == '[' || c2 == '{'
1410 || c2 == ')' || c2 == ']' || c2 == '}')
1415 if (c2 == c1 || c2 == '=')
1419 case 'e': case 'E': case 'p': case 'P':
1420 if (c2 == '-' || c2 == '+')
1421 return 1; /* could extend a pre-processing number */
1425 if (CPP_OPTION (pfile, dollars_in_ident))
1430 if (c2 == '\'' || c2 == '\"')
1431 return 1; /* Could turn into L"xxx" or L'xxx'. */
1434 case '.': case '0': case '1': case '2': case '3':
1435 case '4': case '5': case '6': case '7': case '8': case '9':
1436 case '_': case 'a': case 'b': case 'c': case 'd': case 'f':
1437 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1438 case 'm': case 'n': case 'o': case 'q': case 'r': case 's':
1439 case 't': case 'u': case 'v': case 'w': case 'x': case 'y':
1440 case 'z': case 'A': case 'B': case 'C': case 'D': case 'F':
1441 case 'G': case 'H': case 'I': case 'J': case 'K': case 'M':
1442 case 'N': case 'O': case 'Q': case 'R': case 'S': case 'T':
1443 case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
1445 /* We're in the middle of either a name or a pre-processing number. */
1446 return (is_idchar(c2) || c2 == '.');
1448 case '<': case '>': case '!': case '%': case '#': case ':':
1449 case '^': case '&': case '|': case '*': case '/': case '=':
1450 return (c2 == c1 || c2 == '=');
1456 push_macro_expansion (pfile, xbuf, len, hp)
1458 register U_CHAR *xbuf;
1463 int advance_cur = 0;
1465 /* The first chars of the expansion should be a "\r " added by
1466 collect_expansion. This is to prevent accidental token-pasting
1467 between the text preceding the macro invocation, and the macro
1470 We would like to avoid adding unneeded spaces (for the sake of
1471 tools that use cpp, such as imake). In some common cases we can
1472 tell that it is safe to omit the space. */
1474 if (xbuf[0] == '\r' && xbuf[1] == ' '
1475 && !unsafe_chars (pfile, EOF, xbuf[2]))
1478 /* Likewise, avoid the extra space at the end of the macro expansion
1479 if this is safe. We can do a better job here since we can know
1480 what the next char will be. */
1482 && xbuf[len-2] == '\r'
1483 && xbuf[len-1] == ' ')
1485 int c = CPP_BUF_PEEK (CPP_BUFFER (pfile));
1486 if (c == EOF || !unsafe_chars (pfile, xbuf[len-3], c))
1490 mbuf = cpp_push_buffer (pfile, xbuf, len);
1495 mbuf->cleanup = macro_cleanup;
1499 /* Return zero if two DEFINITIONs are isomorphic. */
1502 _cpp_compare_defs (pfile, d1, d2)
1504 DEFINITION *d1, *d2;
1506 struct reflist *a1, *a2;
1507 U_CHAR *p1 = d1->expansion;
1508 U_CHAR *p2 = d2->expansion;
1511 if (d1->nargs != d2->nargs)
1513 if (CPP_PEDANTIC (pfile)
1514 && d1->argnames && d2->argnames)
1516 U_CHAR *arg1 = d1->argnames;
1517 U_CHAR *arg2 = d2->argnames;
1522 len = strlen (arg1) + 1;
1523 if (strcmp (arg1, arg2))
1529 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1530 a1 = a1->next, a2 = a2->next)
1532 if (!((a1->nchars == a2->nchars && !strncmp (p1, p2, a1->nchars))
1533 || !comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
1534 || a1->argno != a2->argno
1535 || a1->stringify != a2->stringify
1536 || a1->raw_before != a2->raw_before
1537 || a1->raw_after != a2->raw_after)
1546 return comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
1547 p2, d2->length - (p2 - d2->expansion), 1);
1550 /* Return 1 if two parts of two macro definitions are effectively different.
1551 One of the parts starts at BEG1 and has LEN1 chars;
1552 the other has LEN2 chars at BEG2.
1553 Any sequence of whitespace matches any other sequence of whitespace.
1554 FIRST means these parts are the first of a macro definition;
1555 so ignore leading whitespace entirely.
1556 LAST means these parts are the last of a macro definition;
1557 so ignore trailing whitespace entirely. */
1560 comp_def_part (first, beg1, len1, beg2, len2, last)
1562 U_CHAR *beg1, *beg2;
1566 register U_CHAR *end1 = beg1 + len1;
1567 register U_CHAR *end2 = beg2 + len2;
1570 while (beg1 != end1 && is_space(*beg1))
1572 while (beg2 != end2 && is_space(*beg2))
1577 while (beg1 != end1 && is_space(end1[-1]))
1579 while (beg2 != end2 && is_space(end2[-1]))
1582 while (beg1 != end1 && beg2 != end2)
1584 if (is_space(*beg1) && is_space(*beg2))
1586 while (beg1 != end1 && is_space(*beg1))
1588 while (beg2 != end2 && is_space(*beg2))
1591 else if (*beg1 == *beg2)
1599 return (beg1 != end1) || (beg2 != end2);
1602 /* Dump the definition of macro MACRO on stdout. The format is suitable
1603 to be read back in again. */
1606 _cpp_dump_definition (pfile, sym, len, defn)
1612 CPP_RESERVE (pfile, len + sizeof "#define ");
1613 CPP_PUTS_Q (pfile, "#define ", sizeof "#define " -1);
1614 CPP_PUTS_Q (pfile, sym, len);
1616 if (defn->nargs == -1)
1618 CPP_PUTC_Q (pfile, ' ');
1620 /* The first and last two characters of a macro expansion are
1621 always "\r "; this needs to be trimmed out.
1622 So we need length-4 chars of space, plus one for the NUL. */
1623 CPP_RESERVE (pfile, defn->length - 4 + 1);
1624 CPP_PUTS_Q (pfile, defn->expansion + 2, defn->length - 4);
1629 unsigned char **argv = (unsigned char **) alloca (defn->nargs *
1631 int *argl = (int *) alloca (defn->nargs * sizeof(int));
1635 /* First extract the argument list. */
1637 for (i = 0; i < defn->nargs; i++)
1640 argl[i] = strlen (x);
1644 /* Now print out the argument list. */
1645 CPP_PUTC_Q (pfile, '(');
1646 for (i = 0; i < defn->nargs; i++)
1648 CPP_RESERVE (pfile, argl[i] + 2);
1649 if (!(i == defn->nargs-1 && defn->rest_args
1650 && !strcmp (argv[i], "__VA_ARGS__")))
1651 CPP_PUTS_Q (pfile, argv[i], argl[i]);
1652 if (i < defn->nargs-1)
1653 CPP_PUTS_Q (pfile, ", ", 2);
1655 if (defn->rest_args)
1656 CPP_PUTS (pfile, "...", 3);
1657 CPP_PUTS (pfile, ") ", 2);
1659 /* Now the definition. */
1660 x = defn->expansion;
1661 for (r = defn->pattern; r; r = r->next)
1664 if (*x == '\r') x += 2, i -= 2;
1665 /* i chars for macro text, plus the length of the macro
1666 argument name, plus one for a stringify marker, plus two for
1667 each concatenation marker. */
1669 i + argl[r->argno] + r->stringify
1670 + (r->raw_before + r->raw_after) * 2);
1672 if (i > 0) CPP_PUTS_Q (pfile, x, i);
1674 CPP_PUTS_Q (pfile, "##", 2);
1676 CPP_PUTC_Q (pfile, '#');
1677 CPP_PUTS_Q (pfile, argv[r->argno], argl[r->argno]);
1678 if (r->raw_after && !(r->next && r->next->nchars == 0
1679 && r->next->raw_before))
1680 CPP_PUTS_Q (pfile, "##", 2);
1685 i = defn->length - (x - defn->expansion) - 2;
1686 if (*x == '\r') x += 2, i -= 2;
1687 if (i > 0) CPP_PUTS (pfile, x, i);
1689 if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
1690 CPP_PUTC (pfile, '\n');
1691 CPP_NUL_TERMINATE (pfile);
1694 /* Dump out the hash table. */
1696 dump_hash_helper (h, p)
1700 HASHNODE *hp = (HASHNODE *)*h;
1701 cpp_reader *pfile = (cpp_reader *)p;
1703 if (hp->type == T_MACRO)
1704 _cpp_dump_definition (pfile, hp->name, hp->length, hp->value.defn);
1709 _cpp_dump_macro_hash (pfile)
1712 htab_traverse (pfile->hashtab, dump_hash_helper, pfile);