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 void push_macro_expansion PARAMS ((cpp_reader *,
40 U_CHAR *, int, HASHNODE *));
41 static int unsafe_chars PARAMS ((cpp_reader *, int, int));
42 static int macro_cleanup PARAMS ((cpp_buffer *, cpp_reader *));
43 static enum cpp_ttype macarg PARAMS ((cpp_reader *, int));
44 static void special_symbol PARAMS ((HASHNODE *, cpp_reader *));
46 /* Initial hash table size. (It can grow if necessary - see hashtab.c.) */
49 /* The arglist structure is built by create_definition to tell
50 collect_expansion where the argument names begin. That
51 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
52 would contain pointers to the strings x, y, and z.
53 collect_expansion would then build a DEFINITION node,
54 with reflist nodes pointing to the places x, y, and z had
55 appeared. So the arglist is just convenience data passed
56 between these two routines. It is not kept around after
57 the current #define has been processed and entered into the
70 const struct arg *argv;
75 static DEFINITION *collect_expansion PARAMS ((cpp_reader *, cpp_toklist *,
76 struct arglist *, unsigned int));
77 static unsigned int collect_params PARAMS ((cpp_reader *, cpp_toklist *,
80 static void warn_trad_stringify PARAMS ((cpp_reader *, U_CHAR *, size_t,
81 unsigned int, const struct arg *));
82 static int duplicate_arg_p PARAMS ((U_CHAR *, U_CHAR *));
84 /* This structure represents one parsed argument in a macro call.
85 `raw' points to the argument text as written (`raw_length' is its length).
86 `expanded' points to the argument's macro-expansion
87 (its length is `expand_length').
88 `stringified_length' is the length the argument would have
91 /* raw and expanded are relative to ARG_BASE */
92 #define ARG_BASE ((pfile)->token_buffer)
96 /* Strings relative to pfile->token_buffer */
97 long raw, expanded, stringified;
98 int raw_length, expand_length;
99 int stringified_length;
102 /* Calculate hash of a string of length LEN. */
104 _cpp_calc_hash (str, len)
112 r = r * 67 + (*str++ - 113);
117 /* Calculate hash of a HASHNODE structure. */
122 const HASHNODE *h = (const HASHNODE *)x;
126 /* Compare two HASHNODE structures. */
132 const HASHNODE *a = (const HASHNODE *)x;
133 const HASHNODE *b = (const HASHNODE *)y;
135 return (a->length == b->length
136 && !strncmp (a->name, b->name, a->length));
139 /* Destroy a HASHNODE. */
144 HASHNODE *h = (HASHNODE *)x;
146 if (h->type == T_MACRO)
147 _cpp_free_definition (h->value.defn);
148 else if (h->type == T_MCONST)
149 free ((void *) h->value.cpval);
150 free ((void *) h->name);
154 /* Allocate and initialize a HASHNODE structure.
155 Caller must fill in the value field. */
158 _cpp_make_hashnode (name, len, type, hash)
164 HASHNODE *hp = (HASHNODE *) xmalloc (sizeof (HASHNODE));
165 U_CHAR *p = xmalloc (len + 1);
172 memcpy (p, name, len);
178 /* Find the hash node for name "name", which ends at the first
181 If LEN is >= 0, it is the length of the name.
182 Otherwise, compute the length now. */
185 _cpp_lookup (pfile, name, len)
195 for (bp = name; is_idchar (*bp); bp++);
201 dummy.hash = _cpp_calc_hash (name, len);
203 return (HASHNODE *) htab_find_with_hash (pfile->hashtab,
204 (void *)&dummy, dummy.hash);
207 /* Find the hashtable slot for name "name". Used to insert or delete. */
210 _cpp_lookup_slot (pfile, name, len, insert, hash)
214 enum insert_option insert;
223 for (bp = name; is_idchar (*bp); bp++)
231 dummy.hash = _cpp_calc_hash (name, len);
233 slot = (HASHNODE **) htab_find_slot_with_hash (pfile->hashtab,
241 /* Init the hash table. In here so it can see the hash and eq functions. */
243 _cpp_init_macro_hash (pfile)
246 pfile->hashtab = htab_create (HASHSIZE, hash_HASHNODE,
247 eq_HASHNODE, del_HASHNODE);
250 /* Free a DEFINITION structure. Used by delete_macro, and by
251 do_define when redefining macros. */
254 _cpp_free_definition (d)
257 struct reflist *ap, *nextap;
259 for (ap = d->pattern; ap != NULL; ap = nextap)
270 macro_cleanup (pbuf, pfile)
272 cpp_reader *pfile ATTRIBUTE_UNUSED;
274 HASHNODE *macro = pbuf->macro;
275 if (macro->type == T_DISABLED)
276 macro->type = T_MACRO;
277 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
278 free ((PTR) pbuf->buf);
282 /* Issue warnings for macro argument names seen inside strings. */
284 warn_trad_stringify (pfile, p, len, argc, argv)
289 const struct arg *argv;
298 while (p < limit && !is_idstart (*p)) p++;
302 for (i = 0; i < argc; i++)
303 if (!strncmp (p, argv[i].name, argv[i].len)
304 && ! is_idchar (p[argv[i].len]))
307 "macro argument \"%s\" would be stringified in traditional C",
312 while (p < limit && is_idchar (*p)) p++;
318 /* Read a replacement list for a macro, and build the DEFINITION
319 structure. LIST contains the replacement list, beginning at
320 REPLACEMENT. ARGLIST specifies the formal parameters to look for
321 in the text of the definition. If ARGLIST is null, this is an
322 object-like macro; if it points to an empty arglist, this is a
323 function-like macro with no arguments. */
326 collect_expansion (pfile, list, arglist, replacement)
329 struct arglist *arglist;
330 unsigned int replacement;
333 struct reflist *pat = 0, *endpat = 0;
334 enum cpp_ttype token;
339 const struct arg *argv;
341 enum { START = 0, NORM, ARG, STRIZE, PASTE } last_token = START;
345 argv = arglist->argv;
346 argc = arglist->argc;
354 /* We copy the expansion text into the token_buffer, then out to
356 last = start = CPP_WRITTEN (pfile);
357 CPP_PUTS (pfile, "\r ", 2);
359 for (i = replacement; i < list->tokens_used; i++)
361 token = list->tokens[i].type;
362 tok = list->tokens[i].val.name.offset + list->namebuf;
363 len = list->tokens[i].val.name.len;
368 cpp_ice (pfile, "EOF in collect_expansion");
374 /* # is not special in object-like macros. It is special in
375 function-like macros with no args. (6.10.3.2 para 1.)
376 However, it is not special after PASTE. (Implied by
378 if (arglist == NULL || last_token == PASTE)
384 if (last_token == PASTE)
385 /* ## ## - the second ## is ordinary. */
387 else if (last_token == START)
388 cpp_error (pfile, "`##' at start of macro definition");
390 else if (last_token == ARG)
391 /* If the last token was an argument, mark it raw_after. */
392 endpat->raw_after = 1;
393 else if (last_token == STRIZE)
394 /* Oops - that wasn't a stringify operator. */
395 CPP_PUTC (pfile, '#');
402 if (argc && CPP_WTRADITIONAL (pfile))
403 warn_trad_stringify (pfile, tok, len, argc, argv);
407 for (j = 0; j < argc; j++)
408 if (argv[j].len == len
409 && !strncmp (tok, argv[j].name, argv[j].len))
415 if (last_token == STRIZE)
416 cpp_error (pfile, "# is not followed by a macro argument name");
417 if (last_token != PASTE && last_token != START
418 && (list->tokens[i].flags & HSPACE_BEFORE))
419 CPP_PUTC (pfile, ' ');
420 CPP_PUTS (pfile, tok, len);
428 struct reflist *tpat;
429 if (last_token != PASTE && (list->tokens[i].flags & HSPACE_BEFORE))
430 CPP_PUTC (pfile, ' ');
432 /* Make a pat node for this arg and add it to the pat list */
433 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
435 tpat->raw_before = (last_token == PASTE);
437 tpat->stringify = (last_token == STRIZE);
438 tpat->rest_args = argv[j].rest_arg;
440 tpat->nchars = CPP_WRITTEN (pfile) - last;
447 last = CPP_WRITTEN (pfile);
453 if (last_token == STRIZE)
454 cpp_error (pfile, "`#' is not followed by a macro argument name");
455 else if (last_token == PASTE)
456 cpp_error (pfile, "`##' at end of macro definition");
458 CPP_PUTS (pfile, "\r ", 2);
459 len = CPP_WRITTEN (pfile) - start;
460 CPP_SET_WRITTEN (pfile, start);
462 exp = (U_CHAR *) xmalloc (len + 1);
463 memcpy (exp, pfile->token_buffer + start, len);
466 defn = (DEFINITION *) xmalloc (sizeof (DEFINITION));
468 defn->expansion = exp;
470 defn->rest_args = argv && argv[argc - 1].rest_arg;
474 defn->argnames = arglist->namebuf;
486 /* Is argument NEW, which has just been added to the argument list,
487 a duplicate of a previous argument name? */
489 duplicate_arg_p (args, new)
492 size_t newlen = strlen (new) + 1;
497 oldlen = strlen (args) + 1;
498 if (!memcmp (args, new, MIN (oldlen, newlen)))
506 collect_params (pfile, list, arglist)
509 struct arglist *arglist;
511 struct arg *argv = 0;
512 U_CHAR *namebuf, *p, *tok;
513 unsigned int len, argslen;
514 unsigned int argc, a, i, j;
516 /* The formal parameters list starts at token 1. */
517 if (list->tokens[1].type != CPP_OPEN_PAREN)
519 cpp_ice (pfile, "first token = %d not %d in collect_formal_parameters",
520 list->tokens[1].type, CPP_OPEN_PAREN);
524 /* Scan once and count the number of parameters; also check for
525 syntax errors here. */
528 for (i = 2; i < list->tokens_used; i++)
529 switch (list->tokens[i].type)
532 argslen += list->tokens[i].val.name.len + 1;
537 case CPP_CLOSE_PAREN:
540 cpp_error_with_line (pfile, list->line, list->tokens[i].col,
541 "missing right paren in macro argument list");
545 cpp_error_with_line (pfile, list->line, list->tokens[i].col,
546 "syntax error in #define");
550 if (list->tokens[i-1].type != CPP_NAME)
552 argslen += sizeof "__VA_ARGS__";
556 if (list->tokens[i].type != CPP_CLOSE_PAREN)
558 cpp_error_with_line (pfile, list->line, list->tokens[i].col,
559 "another parameter follows \"...\"");
565 cpp_ice (pfile, "collect_params: unreachable - i=%d, ntokens=%d, type=%d",
566 i, list->tokens_used, list->tokens[i-1].type);
570 if (argc == 0) /* function-like macro, no arguments */
574 arglist->namebuf = 0;
579 cpp_ice (pfile, "collect_params: argc=%d argslen=0", argc);
583 /* Now allocate space and copy the suckers. */
584 argv = (struct arg *) xmalloc (argc * sizeof (struct arg));
585 namebuf = (U_CHAR *) xmalloc (argslen);
588 for (j = 2; j < i; j++)
589 switch (list->tokens[j].type)
592 tok = list->tokens[j].val.name.offset + list->namebuf;
593 len = list->tokens[j].val.name.len;
594 memcpy (p, tok, len);
596 if (duplicate_arg_p (namebuf, p))
598 cpp_error (pfile, "duplicate macro argument name \"%s\"", tok);
602 if (CPP_PEDANTIC (pfile) && CPP_OPTION (pfile, c99)
603 && len == sizeof "__VA_ARGS__" - 1
604 && !strcmp (p, "__VA_ARGS__"))
606 "C99 does not permit use of __VA_ARGS__ as a macro argument name");
609 argv[a].rest_arg = 0;
618 if (list->tokens[j-1].type != CPP_NAME)
620 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
621 cpp_pedwarn (pfile, "C89 does not permit varargs macros");
623 argv[a].len = sizeof "__VA_ARGS__" - 1;
625 argv[a].rest_arg = 1;
626 strcpy (p, "__VA_ARGS__");
630 if (CPP_PEDANTIC (pfile))
632 "ISO C does not permit named varargs macros");
633 argv[a-1].rest_arg = 1;
638 cpp_ice (pfile, "collect_params: impossible token type %d",
639 list->tokens[j].type);
642 arglist->argc = argc;
643 arglist->argv = argv;
644 arglist->namebuf = namebuf;
648 /* Create a DEFINITION node for a macro. The replacement text
649 (including formal parameters if present) is in LIST. If FUNLIKE is
650 true, this is a function-like macro. */
653 _cpp_create_definition (pfile, list, funlike)
660 int replacement = 1; /* replacement begins at this token */
664 replacement = collect_params (pfile, list, &args);
665 if (replacement == 0)
669 defn = collect_expansion (pfile, list, funlike ? &args : 0, replacement);
673 defn->file = CPP_BUFFER (pfile)->nominal_fname;
674 defn->line = list->line;
675 defn->col = list->tokens[0].col;
680 * Parse a macro argument and append the info on PFILE's token_buffer.
681 * REST_ARGS means to absorb the rest of the args.
682 * Return nonzero to indicate a syntax error.
685 static enum cpp_ttype
686 macarg (pfile, rest_args)
691 enum cpp_ttype token;
693 /* Try to parse as much of the argument as exists at this
694 input stack level. */
697 token = cpp_get_token (pfile);
703 /* If we've hit end of file, it's an error (reported by caller).
704 Ditto if it's the end of cpp_expand_to_buffer text.
705 If we've hit end of macro, just continue. */
706 if (!CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
712 case CPP_CLOSE_PAREN:
717 /* if we've returned to lowest level and
718 we aren't absorbing all args */
719 if (paren == 0 && rest_args == 0)
723 /* Remove ',' or ')' from argument buffer. */
724 CPP_ADJUST_WRITTEN (pfile, -1);
732 static const char * const monthnames[] =
734 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
735 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
738 /* Place into PFILE a quoted string representing the string SRC.
739 Caller must reserve enough space in pfile->token_buffer. */
742 _cpp_quote_string (pfile, src)
748 CPP_PUTC_Q (pfile, '\"');
750 switch ((c = *src++))
754 CPP_PUTC_Q (pfile, c);
757 sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
758 CPP_ADJUST_WRITTEN (pfile, 4);
764 CPP_PUTC_Q (pfile, '\\');
765 CPP_PUTC_Q (pfile, c);
769 CPP_PUTC_Q (pfile, '\"');
775 * expand things like __FILE__. Place the expansion into the output
776 * buffer *without* rescanning.
779 #define DSC(str) (const U_CHAR *)str, sizeof str - 1
781 special_symbol (hp, pfile)
792 ip = cpp_file_buffer (pfile);
795 CPP_PUTS (pfile, "\"\"", 2);
798 if (hp->type == T_BASE_FILE)
799 while (CPP_PREV_BUFFER (ip) != NULL)
800 ip = CPP_PREV_BUFFER (ip);
802 buf = ip->nominal_fname;
803 CPP_RESERVE (pfile, 3 + 4 * strlen (buf));
804 _cpp_quote_string (pfile, buf);
807 case T_INCLUDE_LEVEL:
809 int true_indepth = 0;
810 ip = cpp_file_buffer (pfile);
814 ip = CPP_PREV_BUFFER (ip);
817 CPP_RESERVE (pfile, 10);
818 sprintf (CPP_PWRITTEN (pfile), "%d", true_indepth);
819 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
824 #ifdef STDC_0_IN_SYSTEM_HEADERS
825 ip = cpp_file_buffer (pfile);
826 if (ip && ip->system_header_p
827 && !cpp_defined (pfile, DSC("__STRICT_ANSI__")))
829 CPP_PUTC (pfile, '0');
833 /* else fall through */
837 buf = hp->value.cpval;
843 CPP_PUTS (pfile, buf, strlen (buf));
847 ip = cpp_file_buffer (pfile);
850 CPP_PUTC (pfile, '0');
853 CPP_RESERVE (pfile, 10);
854 sprintf (CPP_PWRITTEN (pfile), "%u", CPP_BUF_LINE (ip));
855 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
860 /* Generate both __DATE__ and __TIME__, stuff them into their
861 respective hash nodes, and mark the nodes T_MCONST so we
862 don't have to do this again. We don't generate these strings
863 at init time because time() and localtime() are very slow on
866 time_t tt = time (NULL);
867 struct tm *tb = localtime (&tt);
870 if (hp->type == T_DATE)
871 d = hp, t = _cpp_lookup (pfile, DSC("__TIME__"));
873 t = hp, d = _cpp_lookup (pfile, DSC("__DATE__"));
875 d->value.cpval = xmalloc (sizeof "'Oct 11 1347'");
876 sprintf ((char *)d->value.cpval, "\"%s %2d %4d\"",
877 monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
880 t->value.cpval = xmalloc (sizeof "'12:34:56'");
881 sprintf ((char *)t->value.cpval, "\"%02d:%02d:%02d\"",
882 tb->tm_hour, tb->tm_min, tb->tm_sec);
888 cpp_error (pfile, "attempt to use poisoned `%s'.", hp->name);
889 CPP_PUTC (pfile, '0');
893 cpp_ice (pfile, "invalid special hash type");
899 /* Expand a macro call.
900 HP points to the symbol that is the macro being called.
901 Put the result of expansion onto the input stack
902 so that subsequent input by our caller will use it.
904 If macro wants arguments, caller has already verified that
905 an argument list follows; arguments come from the input stack. */
908 _cpp_macroexpand (pfile, hp)
914 register U_CHAR *xbuf;
915 unsigned int start_line, start_column;
918 struct argdata *args = 0;
919 long old_written = CPP_WRITTEN (pfile);
920 int rest_args, rest_zero = 0;
923 ip = cpp_file_buffer (pfile);
926 start_line = CPP_BUF_LINE (ip);
927 start_column = CPP_BUF_COL (ip);
930 start_line = start_column = 0;
932 /* Check for and handle special symbols. */
933 if (hp->type != T_MACRO)
935 special_symbol (hp, pfile);
936 xbuf_len = CPP_WRITTEN (pfile) - old_written;
937 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
938 CPP_SET_WRITTEN (pfile, old_written);
939 memcpy (xbuf, CPP_PWRITTEN (pfile), xbuf_len + 1);
940 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
941 CPP_BUFFER (pfile)->has_escapes = 1;
945 defn = hp->value.defn;
947 pfile->output_escapes++;
951 enum cpp_ttype token;
953 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
955 for (i = 0; i < nargs; i++)
957 args[i].raw = args[i].expanded = 0;
958 args[i].raw_length = 0;
959 args[i].expand_length = args[i].stringified_length = -1;
962 /* Parse all the macro args that are supplied. I counts them.
963 The first NARGS args are stored in ARGS.
964 The rest are discarded. If rest_args is set then we assume
965 macarg absorbed the rest of the args. */
969 /* Skip over the opening parenthesis. */
970 CPP_OPTION (pfile, discard_comments)++;
971 pfile->no_macro_expand++;
972 pfile->no_directives++;
974 token = cpp_get_non_space_token (pfile);
975 if (token != CPP_OPEN_PAREN)
976 cpp_ice (pfile, "macroexpand: unexpected token %d (wanted LPAREN)",
978 CPP_ADJUST_WRITTEN (pfile, -1);
985 if (i < nargs || (nargs == 0 && i == 0))
987 /* if we are working on last arg which absorbs rest of args... */
988 if (i == nargs - 1 && defn->rest_args)
990 args[i].raw = CPP_WRITTEN (pfile);
991 token = macarg (pfile, rest_args);
992 args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
995 token = macarg (pfile, 0);
996 if (token == CPP_EOF || token == CPP_POP)
997 cpp_error_with_line (pfile, start_line, start_column,
998 "unterminated macro call");
1001 while (token == CPP_COMMA);
1002 CPP_OPTION (pfile, discard_comments)--;
1003 pfile->no_macro_expand--;
1004 pfile->no_directives--;
1005 if (token != CPP_CLOSE_PAREN)
1008 /* foo ( ) is equivalent to foo () unless foo takes exactly one
1009 argument, in which case the former is allowed and the latter
1010 is not. XXX C99 is silent on this rule, but it seems
1011 inconsistent to me. */
1012 if (i == 1 && nargs != 1)
1014 register U_CHAR *bp = ARG_BASE + args[0].raw;
1015 register U_CHAR *lim = bp + args[0].raw_length;
1016 while (bp != lim && is_space(*bp))
1022 /* Don't output an error message if we have already output one for
1023 a parse error above. */
1025 if (nargs == 0 && i > 0)
1027 cpp_error (pfile, "arguments given to macro `%s'", hp->name);
1031 /* the rest args token is allowed to absorb 0 tokens */
1032 if (i == nargs - 1 && defn->rest_args)
1035 cpp_error (pfile, "macro `%s' used without args", hp->name);
1037 cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
1039 cpp_error (pfile, "macro `%s' used with only %d args",
1045 "macro `%s' used with too many (%d) args", hp->name, i);
1049 /* If macro wants zero args, we parsed the arglist for checking only.
1050 Read directly from the macro definition. */
1053 xbuf = defn->expansion;
1054 xbuf_len = defn->length;
1058 register U_CHAR *exp = defn->expansion;
1059 register int offset; /* offset in expansion,
1060 copied a piece at a time */
1061 register int totlen; /* total amount of exp buffer filled so far */
1063 register struct reflist *ap, *last_ap;
1065 /* Macro really takes args. Compute the expansion of this call. */
1067 /* Compute length in characters of the macro's expansion.
1068 Also count number of times each arg is used. */
1069 xbuf_len = defn->length;
1070 for (ap = defn->pattern; ap != NULL; ap = ap->next)
1074 register struct argdata *arg = &args[ap->argno];
1075 /* Stringify if it hasn't already been */
1076 if (arg->stringified_length < 0)
1078 int arglen = arg->raw_length;
1082 /* Initially need_space is -1. Otherwise, 1 means the
1083 previous character was a space, but we suppressed it;
1084 0 means the previous character was a non-space. */
1085 int need_space = -1;
1087 arg->stringified = CPP_WRITTEN (pfile);
1088 CPP_PUTC (pfile, '\"'); /* insert beginning quote */
1089 for (; i < arglen; i++)
1091 c = (ARG_BASE + arg->raw)[i];
1095 /* Delete "\r " and "\r-" escapes. */
1101 /* Internal sequences of whitespace are
1102 replaced by one space except within
1103 a string or char token. */
1104 else if (is_space(c))
1106 if (need_space == 0)
1110 else if (need_space > 0)
1111 CPP_PUTC (pfile, ' ');
1126 else if (c == '\"' || c == '\'')
1130 /* Escape these chars */
1131 if (c == '\"' || (in_string && c == '\\'))
1132 CPP_PUTC (pfile, '\\');
1134 CPP_PUTC (pfile, c);
1137 CPP_RESERVE (pfile, 4);
1138 sprintf ((char *) CPP_PWRITTEN (pfile), "\\%03o",
1140 CPP_ADJUST_WRITTEN (pfile, 4);
1143 CPP_PUTC (pfile, '\"'); /* insert ending quote */
1144 arg->stringified_length
1145 = CPP_WRITTEN (pfile) - arg->stringified;
1147 xbuf_len += args[ap->argno].stringified_length;
1149 else if (ap->raw_before || ap->raw_after)
1150 /* Add 4 for two \r-space markers to prevent
1151 token concatenation. */
1152 xbuf_len += args[ap->argno].raw_length + 4;
1155 /* We have an ordinary (expanded) occurrence of the arg.
1156 So compute its expansion, if we have not already. */
1157 if (args[ap->argno].expand_length < 0)
1159 args[ap->argno].expanded = CPP_WRITTEN (pfile);
1160 _cpp_expand_to_buffer (pfile,
1161 ARG_BASE + args[ap->argno].raw,
1162 args[ap->argno].raw_length);
1164 args[ap->argno].expand_length
1165 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
1168 /* Add 4 for two \r-space markers to prevent
1169 token concatenation. */
1170 xbuf_len += args[ap->argno].expand_length + 4;
1174 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1176 /* Generate in XBUF the complete expansion
1177 with arguments substituted in.
1178 TOTLEN is the total size generated so far.
1179 OFFSET is the index in the definition
1180 of where we are copying from. */
1181 offset = totlen = 0;
1182 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
1183 last_ap = ap, ap = ap->next)
1185 register struct argdata *arg = &args[ap->argno];
1186 int count_before = totlen;
1188 /* Add chars to XBUF. */
1190 memcpy (&xbuf[totlen], &exp[offset], i);
1194 /* If followed by an empty rest arg with concatenation,
1195 delete the last run of nonwhite chars. */
1196 if (rest_zero && totlen > count_before
1197 && ((ap->rest_args && ap->raw_before)
1198 || (last_ap != NULL && last_ap->rest_args
1199 && last_ap->raw_after)))
1201 /* Delete final whitespace. */
1202 while (totlen > count_before && is_space(xbuf[totlen - 1]))
1205 /* Delete the nonwhites before them. */
1206 while (totlen > count_before && !is_space(xbuf[totlen - 1]))
1210 if (ap->stringify != 0)
1212 memcpy (xbuf + totlen, ARG_BASE + arg->stringified,
1213 arg->stringified_length);
1214 totlen += arg->stringified_length;
1216 else if (ap->raw_before || ap->raw_after)
1218 U_CHAR *p1 = ARG_BASE + arg->raw;
1219 U_CHAR *l1 = p1 + arg->raw_length;
1222 /* Arg is concatenated before: delete leading whitespace,
1223 whitespace markers, and no-reexpansion markers. */
1226 if (is_space(p1[0]))
1228 else if (p1[0] == '\r')
1236 /* Arg is concatenated after: delete trailing whitespace,
1237 whitespace markers, and no-reexpansion markers. */
1240 if (is_space(l1[-1]))
1242 else if (l1[-1] == '\r')
1244 else if (l1[-1] == '-')
1246 if (l1 != p1 + 1 && l1[-2] == '\r')
1256 /* Delete any no-reexpansion marker that precedes
1257 an identifier at the beginning of the argument. */
1258 if (p1[0] == '\r' && p1[1] == '-')
1261 memcpy (xbuf + totlen, p1, l1 - p1);
1266 U_CHAR *expanded = ARG_BASE + arg->expanded;
1267 if (!ap->raw_before && totlen > 0 && arg->expand_length
1268 && unsafe_chars (pfile, xbuf[totlen - 1], expanded[0]))
1270 xbuf[totlen++] = '\r';
1271 xbuf[totlen++] = ' ';
1274 memcpy (xbuf + totlen, expanded, arg->expand_length);
1275 totlen += arg->expand_length;
1277 if (!ap->raw_after && totlen > 0 && offset < defn->length
1278 && unsafe_chars (pfile, xbuf[totlen - 1], exp[offset]))
1280 xbuf[totlen++] = '\r';
1281 xbuf[totlen++] = ' ';
1285 if (totlen > xbuf_len)
1287 cpp_ice (pfile, "buffer overrun in macroexpand");
1292 /* if there is anything left of the definition
1293 after handling the arg list, copy that in too. */
1295 for (i = offset; i < defn->length; i++)
1297 /* if we've reached the end of the macro */
1300 if (!(rest_zero && last_ap != NULL && last_ap->rest_args
1301 && last_ap->raw_after))
1302 xbuf[totlen++] = exp[i];
1310 pfile->output_escapes--;
1312 /* Now put the expansion on the input stack
1313 so our caller will commence reading from it. */
1314 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
1315 CPP_BUFFER (pfile)->has_escapes = 1;
1317 /* Pop the space we've used in the token_buffer for argument expansion. */
1318 CPP_SET_WRITTEN (pfile, old_written);
1320 /* Per C89, a macro cannot be expanded recursively. */
1321 hp->type = T_DISABLED;
1324 /* Return 1 iff a token ending in C1 followed directly by a token C2
1325 could cause mis-tokenization. */
1328 unsafe_chars (pfile, c1, c2)
1332 /* If c2 is EOF, that's always safe. */
1339 /* We don't know what the previous character was. We do know
1340 that it can't have been an idchar (or else it would have been
1341 pasted with the idchars of the macro name), and there are a
1342 number of second characters for which it doesn't matter what
1344 if (is_idchar (c2) || c2 == '\'' || c2 == '\"'
1345 || c2 == '(' || c2 == '[' || c2 == '{'
1346 || c2 == ')' || c2 == ']' || c2 == '}')
1351 if (c2 == c1 || c2 == '=')
1355 case 'e': case 'E': case 'p': case 'P':
1356 if (c2 == '-' || c2 == '+')
1357 return 1; /* could extend a pre-processing number */
1361 if (CPP_OPTION (pfile, dollars_in_ident))
1366 if (c2 == '\'' || c2 == '\"')
1367 return 1; /* Could turn into L"xxx" or L'xxx'. */
1370 case '.': case '0': case '1': case '2': case '3':
1371 case '4': case '5': case '6': case '7': case '8': case '9':
1372 case '_': case 'a': case 'b': case 'c': case 'd': case 'f':
1373 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1374 case 'm': case 'n': case 'o': case 'q': case 'r': case 's':
1375 case 't': case 'u': case 'v': case 'w': case 'x': case 'y':
1376 case 'z': case 'A': case 'B': case 'C': case 'D': case 'F':
1377 case 'G': case 'H': case 'I': case 'J': case 'K': case 'M':
1378 case 'N': case 'O': case 'Q': case 'R': case 'S': case 'T':
1379 case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
1381 /* We're in the middle of either a name or a pre-processing number. */
1382 return (is_idchar(c2) || c2 == '.');
1384 case '<': case '>': case '!': case '%': case '#': case ':':
1385 case '^': case '&': case '|': case '*': case '/': case '=':
1386 return (c2 == c1 || c2 == '=');
1392 push_macro_expansion (pfile, xbuf, len, hp)
1394 register U_CHAR *xbuf;
1399 int advance_cur = 0;
1401 /* The first chars of the expansion should be a "\r " added by
1402 collect_expansion. This is to prevent accidental token-pasting
1403 between the text preceding the macro invocation, and the macro
1406 We would like to avoid adding unneeded spaces (for the sake of
1407 tools that use cpp, such as imake). In some common cases we can
1408 tell that it is safe to omit the space. */
1410 if (xbuf[0] == '\r' && xbuf[1] == ' '
1411 && !unsafe_chars (pfile, EOF, xbuf[2]))
1414 /* Likewise, avoid the extra space at the end of the macro expansion
1415 if this is safe. We can do a better job here since we can know
1416 what the next char will be. */
1417 if (len >= 3 && xbuf[len-2] == '\r' && xbuf[len-1] == ' '
1418 && !unsafe_chars (pfile, xbuf[len-3], CPP_BUF_PEEK (CPP_BUFFER (pfile))))
1421 /* If the total expansion is "\r \r", we must not trim both escapes. */
1422 if (len == 2 && advance_cur)
1425 mbuf = cpp_push_buffer (pfile, xbuf, len);
1430 mbuf->cleanup = macro_cleanup;
1434 /* Return zero if two DEFINITIONs are isomorphic. */
1437 _cpp_compare_defs (pfile, d1, d2)
1439 DEFINITION *d1, *d2;
1441 struct reflist *a1, *a2;
1443 if (d1->nargs != d2->nargs)
1445 if (strcmp (d1->expansion, d2->expansion))
1447 if (CPP_PEDANTIC (pfile)
1448 && d1->argnames && d2->argnames)
1450 U_CHAR *arg1 = d1->argnames;
1451 U_CHAR *arg2 = d2->argnames;
1456 len = strlen (arg1) + 1;
1457 if (strcmp (arg1, arg2))
1463 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1464 a1 = a1->next, a2 = a2->next)
1466 if (a1->nchars != a2->nchars
1467 || a1->argno != a2->argno
1468 || a1->stringify != a2->stringify
1469 || a1->raw_before != a2->raw_before
1470 || a1->raw_after != a2->raw_after)
1479 /* Dump the definition of macro MACRO on stdout. The format is suitable
1480 to be read back in again. */
1483 _cpp_dump_definition (pfile, sym, len, defn)
1489 CPP_RESERVE (pfile, len + sizeof "#define ");
1490 CPP_PUTS_Q (pfile, "#define ", sizeof "#define " -1);
1491 CPP_PUTS_Q (pfile, sym, len);
1493 if (defn->nargs == -1)
1495 CPP_PUTC_Q (pfile, ' ');
1497 /* The first and last two characters of a macro expansion are
1498 always "\r "; this needs to be trimmed out.
1499 So we need length-4 chars of space, plus one for the NUL. */
1500 CPP_RESERVE (pfile, defn->length - 4 + 1);
1501 CPP_PUTS_Q (pfile, defn->expansion + 2, defn->length - 4);
1506 unsigned char **argv = (unsigned char **) alloca (defn->nargs *
1508 int *argl = (int *) alloca (defn->nargs * sizeof(int));
1512 /* First extract the argument list. */
1514 for (i = 0; i < defn->nargs; i++)
1517 argl[i] = strlen (x);
1521 /* Now print out the argument list. */
1522 CPP_PUTC_Q (pfile, '(');
1523 for (i = 0; i < defn->nargs; i++)
1525 CPP_RESERVE (pfile, argl[i] + 2);
1526 if (!(i == defn->nargs-1 && defn->rest_args
1527 && !strcmp (argv[i], "__VA_ARGS__")))
1528 CPP_PUTS_Q (pfile, argv[i], argl[i]);
1529 if (i < defn->nargs-1)
1530 CPP_PUTS_Q (pfile, ", ", 2);
1532 if (defn->rest_args)
1533 CPP_PUTS (pfile, "...", 3);
1534 CPP_PUTS (pfile, ") ", 2);
1536 /* Now the definition. */
1537 x = defn->expansion;
1538 for (r = defn->pattern; r; r = r->next)
1541 if (*x == '\r') x += 2, i -= 2;
1542 /* i chars for macro text, plus the length of the macro
1543 argument name, plus one for a stringify marker, plus two for
1544 each concatenation marker. */
1546 i + argl[r->argno] + r->stringify
1547 + (r->raw_before + r->raw_after) * 2);
1549 if (i > 0) CPP_PUTS_Q (pfile, x, i);
1551 CPP_PUTS_Q (pfile, "##", 2);
1553 CPP_PUTC_Q (pfile, '#');
1554 CPP_PUTS_Q (pfile, argv[r->argno], argl[r->argno]);
1555 if (r->raw_after && !(r->next && r->next->nchars == 0
1556 && r->next->raw_before))
1557 CPP_PUTS_Q (pfile, "##", 2);
1562 i = defn->length - (x - defn->expansion) - 2;
1563 if (*x == '\r') x += 2, i -= 2;
1564 if (i > 0) CPP_PUTS (pfile, x, i);
1566 if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
1567 CPP_PUTC (pfile, '\n');
1570 /* Dump out the hash table. */
1572 dump_hash_helper (h, p)
1576 HASHNODE *hp = (HASHNODE *)*h;
1577 cpp_reader *pfile = (cpp_reader *)p;
1579 if (hp->type == T_MACRO)
1580 _cpp_dump_definition (pfile, hp->name, hp->length, hp->value.defn);
1585 _cpp_dump_macro_hash (pfile)
1588 htab_traverse (pfile->hashtab, dump_hash_helper, pfile);