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 hashf PARAMS ((const U_CHAR *, int));
34 static int comp_def_part PARAMS ((int, U_CHAR *, int, U_CHAR *,
36 static void push_macro_expansion PARAMS ((cpp_reader *,
37 U_CHAR *, int, HASHNODE *));
38 static int unsafe_chars PARAMS ((cpp_reader *, int, int));
39 static int macro_cleanup PARAMS ((cpp_buffer *, cpp_reader *));
40 static enum cpp_token macarg PARAMS ((cpp_reader *, int));
41 static struct tm *timestamp PARAMS ((cpp_reader *));
42 static void special_symbol PARAMS ((HASHNODE *, cpp_reader *));
44 #define CPP_IS_MACRO_BUFFER(PBUF) ((PBUF)->data != NULL)
45 #define FORWARD(N) CPP_FORWARD (CPP_BUFFER (pfile), (N))
46 #define PEEKC() CPP_BUF_PEEK (CPP_BUFFER (pfile))
48 /* The arglist structure is built by create_definition to tell
49 collect_expansion where the argument names begin. That
50 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
51 would contain pointers to the strings x, y, and z.
52 collect_expansion would then build a DEFINITION node,
53 with reflist nodes pointing to the places x, y, and z had
54 appeared. So the arglist is just convenience data passed
55 between these two routines. It is not kept around after
56 the current #define has been processed and entered into the
74 static DEFINITION *collect_expansion PARAMS ((cpp_reader *, struct arglist *));
75 static struct arglist *collect_formal_parameters PARAMS ((cpp_reader *));
77 /* This structure represents one parsed argument in a macro call.
78 `raw' points to the argument text as written (`raw_length' is its length).
79 `expanded' points to the argument's macro-expansion
80 (its length is `expand_length').
81 `stringified_length' is the length the argument would have
84 /* raw and expanded are relative to ARG_BASE */
85 #define ARG_BASE ((pfile)->token_buffer)
89 /* Strings relative to pfile->token_buffer */
90 long raw, expanded, stringified;
91 int raw_length, expand_length;
92 int stringified_length;
96 /* Calculate hash function on a string. */
100 register const U_CHAR *s;
103 unsigned int n = len;
107 r = r * 67 + (*s++ - 113);
112 /* Find the most recent hash node for name "name" (ending with first
113 non-identifier char) installed by cpp_install
115 If LEN is >= 0, it is the length of the name.
116 Otherwise, compute the length by scanning the entire name. */
119 _cpp_lookup (pfile, name, len)
124 register const U_CHAR *bp;
125 register HASHNODE *bucket;
126 register unsigned int hash;
130 for (bp = name; is_idchar (*bp); bp++);
134 hash = hashf (name, len) % HASHSIZE;
136 bucket = pfile->hashtab[hash];
139 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
141 bucket = bucket->next;
143 return (HASHNODE *) 0;
146 /* Free a DEFINITION structure. Used by delete_macro, and by
147 do_define when redefining macros. */
150 _cpp_free_definition (d)
153 struct reflist *ap, *nextap;
155 for (ap = d->pattern; ap != NULL; ap = nextap)
166 * Delete a hash node. Some weirdness to free junk from macros.
167 * More such weirdness will have to be added if you define more hash
168 * types that need it.
172 _cpp_delete_macro (hp)
175 if (hp->prev != NULL)
176 hp->prev->next = hp->next;
177 if (hp->next != NULL)
178 hp->next->prev = hp->prev;
180 /* make sure that the bucket chain header that
181 the deleted guy was on points to the right thing afterwards. */
182 if (hp == *hp->bucket_hdr)
183 *hp->bucket_hdr = hp->next;
185 if (hp->type == T_MACRO)
186 _cpp_free_definition (hp->value.defn);
191 /* Install a name in the main hash table, even if it is already there.
192 Name stops with first non alphanumeric, except leading '#'.
193 Caller must check against redefinition if that is desired.
194 delete_macro () removes things installed by cpp_install () in fifo order.
195 this is important because of the `defined' special symbol used
196 in #if, and also if pushdef/popdef directives are ever implemented.
198 If LEN is >= 0, it is the length of the name.
199 Otherwise, compute the length by scanning the entire name.
201 If HASH is >= 0, it is the precomputed hash code.
202 Otherwise, compute the hash code. */
205 _cpp_install (pfile, name, len, type, value)
212 register HASHNODE *hp;
213 register int i, bucket;
214 register const U_CHAR *p;
220 while (is_idchar(*p))
225 hash = hashf (name, len) % HASHSIZE;
227 i = sizeof (HASHNODE) + len + 1;
228 hp = (HASHNODE *) xmalloc (i);
230 hp->bucket_hdr = &pfile->hashtab[bucket];
231 hp->next = pfile->hashtab[bucket];
232 pfile->hashtab[bucket] = hp;
234 if (hp->next != NULL)
238 hp->value.cpval = value;
239 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
240 bcopy (name, hp->name, len);
246 macro_cleanup (pbuf, pfile)
248 cpp_reader *pfile ATTRIBUTE_UNUSED;
250 HASHNODE *macro = (HASHNODE *) pbuf->data;
251 if (macro->type == T_DISABLED)
252 macro->type = T_MACRO;
253 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
259 /* Read a replacement list for a macro, and build the DEFINITION
260 structure. ARGLIST specifies the formal parameters to look for in
261 the text of the definition. If ARGLIST is null, this is an
262 object-like macro; if it points to an empty arglist, this is a
263 function-like macro with no arguments.
265 A good half of this is devoted to supporting -traditional.
269 collect_expansion (pfile, arglist)
271 struct arglist *arglist;
274 struct reflist *pat = 0, *endpat = 0;
275 enum cpp_token token;
276 long start, here, last;
282 enum { START = 0, NORM, ARG, STRIZE, PASTE } last_token = START;
286 argv = arglist->argv;
287 argc = arglist->argc;
295 last = start = CPP_WRITTEN (pfile);
296 last -= 2; /* two extra chars for the leading escape */
299 /* We use cpp_get_token because get_directive_token would
300 discard whitespace and we can't cope with that yet. Macro
301 expansion is off, so we are guaranteed not to see POP or EOF. */
303 while (PEEKC () == '\r')
306 CPP_BUMP_LINE (pfile);
308 if (PEEKC () == '\n')
310 here = CPP_WRITTEN (pfile);
311 token = cpp_get_token (pfile);
312 tok = pfile->token_buffer + here;
318 cpp_ice (pfile, "EOF or VSPACE in collect_expansion");
322 if (last_token == STRIZE || last_token == PASTE
323 || last_token == START)
324 CPP_SET_WRITTEN (pfile, here);
328 if (last_token == PASTE)
329 /* Not really a stringifier. */
332 CPP_SET_WRITTEN (pfile, here); /* delete from replacement text */
336 /* If the last token was an argument, discard this token and
337 any hspace between it and the argument's position. Then
338 mark the arg raw_after. */
339 if (last_token == ARG)
341 endpat->raw_after = 1;
343 CPP_SET_WRITTEN (pfile, last);
346 else if (last_token == PASTE)
347 /* ## ## - the second ## is ordinary. */
349 else if (last_token == START)
350 cpp_error (pfile, "`##' at start of macro definition");
352 /* Discard the token and any hspace before it. */
353 while (is_hspace (pfile->token_buffer[here-1]))
355 CPP_SET_WRITTEN (pfile, here);
357 if (last_token == STRIZE)
358 /* Oops - that wasn't a stringify operator. */
359 CPP_PUTC (pfile, '#');
364 /* We must be in -traditional mode. Pretend this was a
365 token paste, but only if there was no leading or
367 CPP_SET_WRITTEN (pfile, here);
368 if (is_hspace (pfile->token_buffer[here-1]))
370 if (is_hspace (PEEKC ()))
372 if (last_token == ARG)
373 endpat->raw_after = 1;
379 if (last_token == STRIZE)
380 cpp_error (pfile, "`#' is not followed by a macro argument name");
382 if (CPP_TRADITIONAL (pfile) || CPP_OPTIONS (pfile)->warn_stringify)
383 goto maybe_trad_stringify;
388 for (i = 0; i < argc; i++)
389 if (!strncmp (tok, argv[i].name, argv[i].len)
390 && ! is_idchar (tok[argv[i].len]))
396 if (last_token == STRIZE)
397 cpp_error (pfile, "`#' is not followed by a macro argument name");
405 struct reflist *tpat;
407 /* Make a pat node for this arg and add it to the pat list */
408 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
410 tpat->raw_before = (last_token == PASTE);
412 tpat->stringify = (last_token == STRIZE);
413 tpat->rest_args = argv[i].rest_arg;
415 tpat->nchars = here - last;
424 CPP_SET_WRITTEN (pfile, here); /* discard arg name */
428 maybe_trad_stringify:
431 U_CHAR *base, *p, *limit;
432 struct reflist *tpat;
434 base = p = pfile->token_buffer + here;
435 limit = CPP_PWRITTEN (pfile);
441 for (i = 0; i < argc; i++)
442 if (!strncmp (tok, argv[i].name, argv[i].len)
443 && ! is_idchar (tok[argv[i].len]))
448 if (!CPP_TRADITIONAL (pfile))
450 /* Must have got here because of -Wtraditional. */
452 "macro argument `%.*s' would be stringified with -traditional",
453 (int) argv[i].len, argv[i].name);
456 if (CPP_OPTIONS (pfile)->warn_stringify)
457 cpp_warning (pfile, "macro argument `%.*s' is stringified",
458 (int) argv[i].len, argv[i].name);
460 /* Remove the argument from the string. */
461 memmove (p, p + argv[i].len, limit - (p + argv[i].len));
462 limit -= argv[i].len;
464 /* Make a pat node for this arg and add it to the pat list */
465 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
468 /* Don't attempt to paste this with anything. */
469 tpat->raw_before = 0;
472 tpat->rest_args = argv[i].rest_arg;
474 tpat->nchars = (p - base) + here - last;
481 last = (p - base) + here;
483 CPP_ADJUST_WRITTEN (pfile, CPP_PWRITTEN (pfile) - limit);
488 if (last_token == STRIZE)
489 cpp_error (pfile, "`#' is not followed by a macro argument name");
490 else if (last_token == PASTE)
491 cpp_error (pfile, "`##' at end of macro definition");
493 if (last_token == START)
495 /* Empty macro definition. */
496 exp = xstrdup ("\r \r ");
501 /* Trim trailing white space from definition. */
502 here = CPP_WRITTEN (pfile);
503 while (here > last && is_hspace (pfile->token_buffer [here-1]))
505 CPP_SET_WRITTEN (pfile, here);
507 CPP_NUL_TERMINATE (pfile);
508 len = CPP_WRITTEN (pfile) - start + 1;
509 exp = xmalloc (len + 4); /* space for no-concat markers at either end */
515 memcpy (&exp[2], pfile->token_buffer + start, len - 1);
518 CPP_SET_WRITTEN (pfile, start);
520 defn = (DEFINITION *) xmalloc (sizeof (DEFINITION));
521 defn->length = len + 3;
522 defn->expansion = exp;
528 defn->argnames = arglist->namebuf;
531 defn->rest_args = argv[argc - 1].rest_arg;
545 static struct arglist *
546 collect_formal_parameters (pfile)
549 struct arglist *result = 0;
550 struct arg *argv = 0;
551 U_CHAR *namebuf = (U_CHAR *) xstrdup ("");
558 enum cpp_token token;
561 old_written = CPP_WRITTEN (pfile);
562 token = get_directive_token (pfile);
563 if (token != CPP_LPAREN)
565 cpp_ice (pfile, "first token = %d not %d in collect_formal_parameters",
570 argv = (struct arg *) xmalloc (sizeof (struct arg));
572 argv[argc].rest_arg = 0;
575 CPP_SET_WRITTEN (pfile, old_written);
576 token = get_directive_token (pfile);
580 tok = pfile->token_buffer + old_written;
581 len = CPP_PWRITTEN (pfile) - tok;
583 && (name = strstr (namebuf, tok))
585 && (name == namebuf || name[-1] == ','))
587 cpp_error (pfile, "duplicate macro argument name `%s'", tok);
590 if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->c99
591 && strncmp (tok, "__VA_ARGS__", sizeof "__VA_ARGS__" - 1))
593 "C99 does not permit use of `__VA_ARGS__' as a macro argument name");
594 namebuf = xrealloc (namebuf, argslen + len + 1);
595 name = &namebuf[argslen - 1];
598 memcpy (name, tok, len);
601 argv[argc].len = len;
602 argv[argc].rest_arg = 0;
607 argv = xrealloc (argv, (argc + 1)*sizeof(struct arg));
618 cpp_error (pfile, "missing right paren in macro argument list");
622 cpp_error (pfile, "syntax error in #define");
628 /* There are two possible styles for a vararg macro:
629 the C99 way: #define foo(a, ...) a, __VA_ARGS__
630 the gnu way: #define foo(a, b...) a, b
631 The C99 way can be considered a special case of the gnu way.
632 There are also some constraints to worry about, but we'll handle
634 if (argv[argc].len == 0)
636 if (CPP_PEDANTIC (pfile) && ! CPP_OPTIONS (pfile)->c99)
637 cpp_pedwarn (pfile, "C89 does not permit varargs macros");
639 len = sizeof "__VA_ARGS__" - 1;
640 namebuf = xrealloc (namebuf, argslen + len + 1);
641 name = &namebuf[argslen - 1];
643 memcpy (name, "__VA_ARGS__", len);
644 argv[argc].len = len;
647 if (CPP_PEDANTIC (pfile))
648 cpp_pedwarn (pfile, "ISO C does not permit named varargs macros");
650 argv[argc].rest_arg = 1;
652 token = get_directive_token (pfile);
653 if (token != CPP_RPAREN)
655 cpp_error (pfile, "another parameter follows `...'");
660 /* Go through argv and fix up the pointers. */
662 for (i = 0; i <= argc; i++)
664 argv[i].name = namebuf + len;
665 len += argv[i].len + 1;
666 namebuf[len - 1] = '\0';
669 CPP_SET_WRITTEN (pfile, old_written);
671 result = (struct arglist *) xmalloc (sizeof (struct arglist));
672 if (namebuf[0] != '\0')
674 result->namebuf = namebuf;
675 result->argc = argc + 1;
696 /* Create a DEFINITION node for a macro. The reader's point is just
697 after the macro name. If FUNLIKE is true, this is a function-like
701 _cpp_create_definition (pfile, funlike)
705 struct arglist *args = 0;
710 cpp_buf_line_and_col (CPP_BUFFER (pfile), &line, &col);
711 file = CPP_BUFFER (pfile)->nominal_fname;
713 pfile->no_macro_expand++;
714 pfile->parsing_define_directive++;
715 CPP_OPTIONS (pfile)->discard_comments++;
716 CPP_OPTIONS (pfile)->no_line_commands++;
720 args = collect_formal_parameters (pfile);
725 defn = collect_expansion (pfile, args);
733 pfile->no_macro_expand--;
734 pfile->parsing_define_directive--;
735 CPP_OPTIONS (pfile)->discard_comments--;
736 CPP_OPTIONS (pfile)->no_line_commands--;
740 pfile->no_macro_expand--;
741 pfile->parsing_define_directive--;
742 CPP_OPTIONS (pfile)->discard_comments--;
743 CPP_OPTIONS (pfile)->no_line_commands--;
748 * Parse a macro argument and append the info on PFILE's token_buffer.
749 * REST_ARGS means to absorb the rest of the args.
750 * Return nonzero to indicate a syntax error.
753 static enum cpp_token
754 macarg (pfile, rest_args)
759 enum cpp_token token;
761 /* Try to parse as much of the argument as exists at this
762 input stack level. */
765 token = cpp_get_token (pfile);
771 /* If we've hit end of file, it's an error (reported by caller).
772 Ditto if it's the end of cpp_expand_to_buffer text.
773 If we've hit end of macro, just continue. */
774 if (!CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
785 /* if we've returned to lowest level and
786 we aren't absorbing all args */
787 if (paren == 0 && rest_args == 0)
791 /* Remove ',' or ')' from argument buffer. */
792 CPP_ADJUST_WRITTEN (pfile, -1);
806 time_t t = time ((time_t *) 0);
807 pfile->timebuf = localtime (&t);
809 return pfile->timebuf;
812 static const char * const monthnames[] =
814 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
815 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
819 * expand things like __FILE__. Place the expansion into the output
820 * buffer *without* rescanning.
824 special_symbol (hp, pfile)
837 ip = cpp_file_buffer (pfile);
838 if (hp->type == T_BASE_FILE)
840 while (CPP_PREV_BUFFER (ip) != NULL)
841 ip = CPP_PREV_BUFFER (ip);
844 buf = ip->nominal_fname;
848 CPP_RESERVE (pfile, 3 + 4 * strlen (buf));
849 quote_string (pfile, buf);
853 case T_INCLUDE_LEVEL:
855 int true_indepth = 1;
856 ip = cpp_file_buffer (pfile);
857 while ((ip = CPP_PREV_BUFFER (ip)) != NULL)
860 CPP_RESERVE (pfile, 10);
861 sprintf (CPP_PWRITTEN (pfile), "%d", true_indepth);
862 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
867 len = strlen (version_string);
868 CPP_RESERVE (pfile, 3 + len);
869 CPP_PUTC_Q (pfile, '"');
870 CPP_PUTS_Q (pfile, version_string, len);
871 CPP_PUTC_Q (pfile, '"');
872 CPP_NUL_TERMINATE_Q (pfile);
876 buf = hp->value.cpval;
883 CPP_RESERVE (pfile, len + 1);
884 CPP_PUTS_Q (pfile, buf, len);
885 CPP_NUL_TERMINATE_Q (pfile);
889 CPP_RESERVE (pfile, 2);
890 #ifdef STDC_0_IN_SYSTEM_HEADERS
891 ip = cpp_file_buffer (pfile);
892 if (ip->system_header_p
893 && !cpp_defined (pfile, (const U_CHAR *) "__STRICT_ANSI__", 15))
894 CPP_PUTC_Q (pfile, '0');
897 CPP_PUTC_Q (pfile, '1');
898 CPP_NUL_TERMINATE_Q (pfile);
904 cpp_buf_line_and_col (cpp_file_buffer (pfile), &line, NULL);
906 CPP_RESERVE (pfile, 10);
907 sprintf (CPP_PWRITTEN (pfile), "%ld", line);
908 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
917 CPP_RESERVE (pfile, 20);
918 timebuf = timestamp (pfile);
919 if (hp->type == T_DATE)
920 sprintf (CPP_PWRITTEN (pfile), "\"%s %2d %4d\"",
921 monthnames[timebuf->tm_mon],
922 timebuf->tm_mday, timebuf->tm_year + 1900);
924 sprintf (CPP_PWRITTEN (pfile), "\"%02d:%02d:%02d\"",
925 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
927 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
932 cpp_error (pfile, "attempt to use poisoned `%s'.", hp->name);
933 CPP_RESERVE (pfile, 1);
934 CPP_PUTC_Q (pfile, '0');
935 CPP_NUL_TERMINATE_Q (pfile);
939 cpp_ice (pfile, "invalid special hash type");
944 /* Expand a macro call.
945 HP points to the symbol that is the macro being called.
946 Put the result of expansion onto the input stack
947 so that subsequent input by our caller will use it.
949 If macro wants arguments, caller has already verified that
950 an argument list follows; arguments come from the input stack. */
953 _cpp_macroexpand (pfile, hp)
959 register U_CHAR *xbuf;
960 long start_line, start_column;
962 struct argdata *args = 0;
963 long old_written = CPP_WRITTEN (pfile);
964 int rest_args, rest_zero = 0;
967 cpp_buf_line_and_col (cpp_file_buffer (pfile), &start_line, &start_column);
969 /* Check for and handle special symbols. */
970 if (hp->type != T_MACRO)
972 special_symbol (hp, pfile);
973 xbuf_len = CPP_WRITTEN (pfile) - old_written;
974 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
975 CPP_SET_WRITTEN (pfile, old_written);
976 memcpy (xbuf, CPP_PWRITTEN (pfile), xbuf_len + 1);
977 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
978 CPP_BUFFER (pfile)->has_escapes = 1;
982 defn = hp->value.defn;
984 pfile->output_escapes++;
988 enum cpp_token token;
990 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
992 for (i = 0; i < nargs; i++)
994 args[i].raw = args[i].expanded = 0;
995 args[i].raw_length = 0;
996 args[i].expand_length = args[i].stringified_length = -1;
999 /* Parse all the macro args that are supplied. I counts them.
1000 The first NARGS args are stored in ARGS.
1001 The rest are discarded. If rest_args is set then we assume
1002 macarg absorbed the rest of the args. */
1006 /* Skip over the opening parenthesis. */
1007 CPP_OPTIONS (pfile)->discard_comments++;
1008 CPP_OPTIONS (pfile)->no_line_commands++;
1009 pfile->no_macro_expand++;
1010 pfile->no_directives++;
1012 token = cpp_get_non_space_token (pfile);
1013 if (token != CPP_LPAREN)
1014 cpp_ice (pfile, "macroexpand: unexpected token %d (wanted LPAREN)",
1016 CPP_ADJUST_WRITTEN (pfile, -1);
1023 if (i < nargs || (nargs == 0 && i == 0))
1025 /* if we are working on last arg which absorbs rest of args... */
1026 if (i == nargs - 1 && defn->rest_args)
1028 args[i].raw = CPP_WRITTEN (pfile);
1029 token = macarg (pfile, rest_args);
1030 args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
1033 token = macarg (pfile, 0);
1034 if (token == CPP_EOF || token == CPP_POP)
1035 cpp_error_with_line (pfile, start_line, start_column,
1036 "unterminated macro call");
1039 while (token == CPP_COMMA);
1040 CPP_OPTIONS (pfile)->discard_comments--;
1041 CPP_OPTIONS (pfile)->no_line_commands--;
1042 pfile->no_macro_expand--;
1043 pfile->no_directives--;
1044 if (token != CPP_RPAREN)
1047 /* If we got one arg but it was just whitespace, call that 0 args. */
1050 register U_CHAR *bp = ARG_BASE + args[0].raw;
1051 register U_CHAR *lim = bp + args[0].raw_length;
1052 /* cpp.texi says for foo ( ) we provide one argument.
1053 However, if foo wants just 0 arguments, treat this as 0. */
1055 while (bp != lim && is_space(*bp))
1061 /* Don't output an error message if we have already output one for
1062 a parse error above. */
1064 if (nargs == 0 && i > 0)
1066 cpp_error (pfile, "arguments given to macro `%s'", hp->name);
1070 /* traditional C allows foo() if foo wants one argument. */
1071 if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
1073 /* the rest args token is allowed to absorb 0 tokens */
1074 else if (i == nargs - 1 && defn->rest_args)
1077 cpp_error (pfile, "macro `%s' used without args", hp->name);
1079 cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
1081 cpp_error (pfile, "macro `%s' used with only %d args",
1087 "macro `%s' used with too many (%d) args", hp->name, i);
1091 /* If macro wants zero args, we parsed the arglist for checking only.
1092 Read directly from the macro definition. */
1095 xbuf = defn->expansion;
1096 xbuf_len = defn->length;
1100 register U_CHAR *exp = defn->expansion;
1101 register int offset; /* offset in expansion,
1102 copied a piece at a time */
1103 register int totlen; /* total amount of exp buffer filled so far */
1105 register struct reflist *ap, *last_ap;
1107 /* Macro really takes args. Compute the expansion of this call. */
1109 /* Compute length in characters of the macro's expansion.
1110 Also count number of times each arg is used. */
1111 xbuf_len = defn->length;
1112 for (ap = defn->pattern; ap != NULL; ap = ap->next)
1116 register struct argdata *arg = &args[ap->argno];
1117 /* Stringify if it hasn't already been */
1118 if (arg->stringified_length < 0)
1120 int arglen = arg->raw_length;
1124 /* Initially need_space is -1. Otherwise, 1 means the
1125 previous character was a space, but we suppressed it;
1126 0 means the previous character was a non-space. */
1127 int need_space = -1;
1129 arg->stringified = CPP_WRITTEN (pfile);
1130 if (!CPP_TRADITIONAL (pfile))
1131 CPP_PUTC (pfile, '\"'); /* insert beginning quote */
1132 for (; i < arglen; i++)
1134 c = (ARG_BASE + arg->raw)[i];
1138 /* Delete "\r " and "\r-" escapes. */
1144 /* Internal sequences of whitespace are
1145 replaced by one space except within
1146 a string or char token. */
1147 else if (is_space(c))
1149 if (need_space == 0)
1153 else if (need_space > 0)
1154 CPP_PUTC (pfile, ' ');
1169 else if (c == '\"' || c == '\'')
1173 /* Escape these chars */
1174 if (c == '\"' || (in_string && c == '\\'))
1175 CPP_PUTC (pfile, '\\');
1177 CPP_PUTC (pfile, c);
1180 CPP_RESERVE (pfile, 4);
1181 sprintf ((char *) CPP_PWRITTEN (pfile), "\\%03o",
1183 CPP_ADJUST_WRITTEN (pfile, 4);
1186 if (!CPP_TRADITIONAL (pfile))
1187 CPP_PUTC (pfile, '\"'); /* insert ending quote */
1188 arg->stringified_length
1189 = CPP_WRITTEN (pfile) - arg->stringified;
1191 xbuf_len += args[ap->argno].stringified_length;
1193 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
1194 /* Add 4 for two \r-space markers to prevent
1195 token concatenation. */
1196 xbuf_len += args[ap->argno].raw_length + 4;
1199 /* We have an ordinary (expanded) occurrence of the arg.
1200 So compute its expansion, if we have not already. */
1201 if (args[ap->argno].expand_length < 0)
1203 args[ap->argno].expanded = CPP_WRITTEN (pfile);
1204 cpp_expand_to_buffer (pfile,
1205 ARG_BASE + args[ap->argno].raw,
1206 args[ap->argno].raw_length);
1208 args[ap->argno].expand_length
1209 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
1212 /* Add 4 for two \r-space markers to prevent
1213 token concatenation. */
1214 xbuf_len += args[ap->argno].expand_length + 4;
1218 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
1220 /* Generate in XBUF the complete expansion
1221 with arguments substituted in.
1222 TOTLEN is the total size generated so far.
1223 OFFSET is the index in the definition
1224 of where we are copying from. */
1225 offset = totlen = 0;
1226 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
1227 last_ap = ap, ap = ap->next)
1229 register struct argdata *arg = &args[ap->argno];
1230 int count_before = totlen;
1232 /* Add chars to XBUF. */
1234 memcpy (&xbuf[totlen], &exp[offset], i);
1238 /* If followed by an empty rest arg with concatenation,
1239 delete the last run of nonwhite chars. */
1240 if (rest_zero && totlen > count_before
1241 && ((ap->rest_args && ap->raw_before)
1242 || (last_ap != NULL && last_ap->rest_args
1243 && last_ap->raw_after)))
1245 /* Delete final whitespace. */
1246 while (totlen > count_before && is_space(xbuf[totlen - 1]))
1249 /* Delete the nonwhites before them. */
1250 while (totlen > count_before && !is_space(xbuf[totlen - 1]))
1254 if (ap->stringify != 0)
1256 memcpy (xbuf + totlen, ARG_BASE + arg->stringified,
1257 arg->stringified_length);
1258 totlen += arg->stringified_length;
1260 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
1262 U_CHAR *p1 = ARG_BASE + arg->raw;
1263 U_CHAR *l1 = p1 + arg->raw_length;
1266 /* Arg is concatenated before: delete leading whitespace,
1267 whitespace markers, and no-reexpansion markers. */
1270 if (is_space(p1[0]))
1272 else if (p1[0] == '\r')
1280 /* Arg is concatenated after: delete trailing whitespace,
1281 whitespace markers, and no-reexpansion markers. */
1284 if (is_space(l1[-1]))
1286 else if (l1[-1] == '\r')
1288 else if (l1[-1] == '-')
1290 if (l1 != p1 + 1 && l1[-2] == '\r')
1300 /* Delete any no-reexpansion marker that precedes
1301 an identifier at the beginning of the argument. */
1302 if (p1[0] == '\r' && p1[1] == '-')
1305 memcpy (xbuf + totlen, p1, l1 - p1);
1310 U_CHAR *expanded = ARG_BASE + arg->expanded;
1311 if (!ap->raw_before && totlen > 0 && arg->expand_length
1312 && !CPP_TRADITIONAL (pfile)
1313 && unsafe_chars (pfile, xbuf[totlen - 1], expanded[0]))
1315 xbuf[totlen++] = '\r';
1316 xbuf[totlen++] = ' ';
1319 memcpy (xbuf + totlen, expanded, arg->expand_length);
1320 totlen += arg->expand_length;
1322 if (!ap->raw_after && totlen > 0 && offset < defn->length
1323 && !CPP_TRADITIONAL (pfile)
1324 && unsafe_chars (pfile, xbuf[totlen - 1], exp[offset]))
1326 xbuf[totlen++] = '\r';
1327 xbuf[totlen++] = ' ';
1331 if (totlen > xbuf_len)
1333 cpp_ice (pfile, "buffer overrun in macroexpand");
1338 /* if there is anything left of the definition
1339 after handling the arg list, copy that in too. */
1341 for (i = offset; i < defn->length; i++)
1343 /* if we've reached the end of the macro */
1346 if (!(rest_zero && last_ap != NULL && last_ap->rest_args
1347 && last_ap->raw_after))
1348 xbuf[totlen++] = exp[i];
1356 pfile->output_escapes--;
1358 /* Now put the expansion on the input stack
1359 so our caller will commence reading from it. */
1360 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
1361 CPP_BUFFER (pfile)->has_escapes = 1;
1363 /* Pop the space we've used in the token_buffer for argument expansion. */
1364 CPP_SET_WRITTEN (pfile, old_written);
1366 /* Recursive macro use sometimes works traditionally.
1367 #define foo(x,y) bar (x (y,0), y)
1370 if (!CPP_TRADITIONAL (pfile))
1371 hp->type = T_DISABLED;
1374 /* Return 1 iff a token ending in C1 followed directly by a token C2
1375 could cause mis-tokenization. */
1378 unsafe_chars (pfile, c1, c2)
1385 if (c2 == c1 || c2 == '=')
1389 case 'e': case 'E': case 'p': case 'P':
1390 if (c2 == '-' || c2 == '+')
1391 return 1; /* could extend a pre-processing number */
1395 if (CPP_OPTIONS (pfile)->dollars_in_ident)
1400 if (c2 == '\'' || c2 == '\"')
1401 return 1; /* Could turn into L"xxx" or L'xxx'. */
1404 case '.': case '0': case '1': case '2': case '3':
1405 case '4': case '5': case '6': case '7': case '8': case '9':
1406 case '_': case 'a': case 'b': case 'c': case 'd': case 'f':
1407 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1408 case 'm': case 'n': case 'o': case 'q': case 'r': case 's':
1409 case 't': case 'u': case 'v': case 'w': case 'x': case 'y':
1410 case 'z': case 'A': case 'B': case 'C': case 'D': case 'F':
1411 case 'G': case 'H': case 'I': case 'J': case 'K': case 'M':
1412 case 'N': case 'O': case 'Q': case 'R': case 'S': case 'T':
1413 case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
1415 /* We're in the middle of either a name or a pre-processing number. */
1416 return (is_idchar(c2) || c2 == '.');
1418 case '<': case '>': case '!': case '%': case '#': case ':':
1419 case '^': case '&': case '|': case '*': case '/': case '=':
1420 return (c2 == c1 || c2 == '=');
1426 push_macro_expansion (pfile, xbuf, xbuf_len, hp)
1428 register U_CHAR *xbuf;
1432 register cpp_buffer *mbuf = cpp_push_buffer (pfile, xbuf, xbuf_len);
1435 mbuf->cleanup = macro_cleanup;
1438 /* The first chars of the expansion should be a "\r " added by
1439 collect_expansion. This is to prevent accidental token-pasting
1440 between the text preceding the macro invocation, and the macro
1443 We would like to avoid adding unneeded spaces (for the sake of
1444 tools that use cpp, such as imake). In some common cases we can
1445 tell that it is safe to omit the space.
1447 The character before the macro invocation cannot have been an
1448 idchar (or else it would have been pasted with the idchars of
1449 the macro name). Therefore, if the first non-space character
1450 of the expansion is an idchar, we do not need the extra space
1451 to prevent token pasting.
1453 Also, we don't need the extra space if the first char is '(',
1454 or some other (less common) characters. */
1456 if (xbuf[0] == '\r' && xbuf[1] == ' '
1457 && (is_idchar(xbuf[2]) || xbuf[2] == '(' || xbuf[2] == '\''
1458 || xbuf[2] == '\"'))
1461 /* Likewise, avoid the extra space at the end of the macro expansion
1462 if this is safe. We can do a better job here since we can know
1463 what the next char will be. */
1465 && mbuf->rlimit[-2] == '\r'
1466 && mbuf->rlimit[-1] == ' ')
1468 int c1 = mbuf->rlimit[-3];
1469 int c2 = CPP_BUF_PEEK (CPP_PREV_BUFFER (CPP_BUFFER (pfile)));
1470 if (c2 == EOF || !unsafe_chars (pfile, c1, c2))
1475 /* Return zero if two DEFINITIONs are isomorphic. */
1478 _cpp_compare_defs (pfile, d1, d2)
1480 DEFINITION *d1, *d2;
1482 struct reflist *a1, *a2;
1483 U_CHAR *p1 = d1->expansion;
1484 U_CHAR *p2 = d2->expansion;
1487 if (d1->nargs != d2->nargs)
1489 if (CPP_PEDANTIC (pfile)
1490 && d1->argnames && d2->argnames)
1492 U_CHAR *arg1 = d1->argnames;
1493 U_CHAR *arg2 = d2->argnames;
1498 len = strlen (arg1);
1499 if (strcmp (arg1, arg2))
1505 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1506 a1 = a1->next, a2 = a2->next)
1508 if (!((a1->nchars == a2->nchars && !strncmp (p1, p2, a1->nchars))
1509 || !comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
1510 || a1->argno != a2->argno
1511 || a1->stringify != a2->stringify
1512 || a1->raw_before != a2->raw_before
1513 || a1->raw_after != a2->raw_after)
1522 return comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
1523 p2, d2->length - (p2 - d2->expansion), 1);
1526 /* Return 1 if two parts of two macro definitions are effectively different.
1527 One of the parts starts at BEG1 and has LEN1 chars;
1528 the other has LEN2 chars at BEG2.
1529 Any sequence of whitespace matches any other sequence of whitespace.
1530 FIRST means these parts are the first of a macro definition;
1531 so ignore leading whitespace entirely.
1532 LAST means these parts are the last of a macro definition;
1533 so ignore trailing whitespace entirely. */
1536 comp_def_part (first, beg1, len1, beg2, len2, last)
1538 U_CHAR *beg1, *beg2;
1542 register U_CHAR *end1 = beg1 + len1;
1543 register U_CHAR *end2 = beg2 + len2;
1546 while (beg1 != end1 && is_space(*beg1))
1548 while (beg2 != end2 && is_space(*beg2))
1553 while (beg1 != end1 && is_space(end1[-1]))
1555 while (beg2 != end2 && is_space(end2[-1]))
1558 while (beg1 != end1 && beg2 != end2)
1560 if (is_space(*beg1) && is_space(*beg2))
1562 while (beg1 != end1 && is_space(*beg1))
1564 while (beg2 != end2 && is_space(*beg2))
1567 else if (*beg1 == *beg2)
1575 return (beg1 != end1) || (beg2 != end2);
1578 /* Dump the definition of macro MACRO on stdout. The format is suitable
1579 to be read back in again. */
1582 _cpp_dump_definition (pfile, sym, len, defn)
1588 if (pfile->lineno == 0)
1589 output_line_command (pfile, same_file);
1591 CPP_RESERVE (pfile, len + sizeof "#define ");
1592 CPP_PUTS_Q (pfile, "#define ", sizeof "#define " -1);
1593 CPP_PUTS_Q (pfile, sym, len);
1595 if (defn->nargs == -1)
1597 CPP_PUTC_Q (pfile, ' ');
1599 /* The first and last two characters of a macro expansion are
1600 always "\r "; this needs to be trimmed out.
1601 So we need length-4 chars of space, plus one for the NUL. */
1602 CPP_RESERVE (pfile, defn->length - 4 + 1);
1603 CPP_PUTS_Q (pfile, defn->expansion + 2, defn->length - 4);
1608 unsigned char **argv = (unsigned char **) alloca (defn->nargs *
1610 int *argl = (int *) alloca (defn->nargs * sizeof(int));
1614 /* First extract the argument list. */
1616 for (i = 0; i < defn->nargs; i++)
1619 argl[i] = strlen (x);
1623 /* Now print out the argument list. */
1624 CPP_PUTC_Q (pfile, '(');
1625 for (i = 0; i < defn->nargs; i++)
1627 CPP_RESERVE (pfile, argl[i] + 2);
1628 if (!(i == defn->nargs-1 && defn->rest_args
1629 && !strcmp (argv[i], "__VA_ARGS__")))
1630 CPP_PUTS_Q (pfile, argv[i], argl[i]);
1631 if (i < defn->nargs-1)
1632 CPP_PUTS_Q (pfile, ", ", 2);
1634 if (defn->rest_args)
1635 CPP_PUTS (pfile, "...", 3);
1636 CPP_PUTS (pfile, ") ", 2);
1638 /* Now the definition. */
1639 x = defn->expansion;
1640 for (r = defn->pattern; r; r = r->next)
1643 if (*x == '\r') x += 2, i -= 2;
1644 /* i chars for macro text, plus the length of the macro
1645 argument name, plus one for a stringify marker, plus two for
1646 each concatenation marker. */
1648 i + argl[r->argno] + r->stringify
1649 + (r->raw_before + r->raw_after) * 2);
1651 if (i > 0) CPP_PUTS_Q (pfile, x, i);
1653 CPP_PUTS_Q (pfile, "##", 2);
1655 CPP_PUTC_Q (pfile, '#');
1656 CPP_PUTS_Q (pfile, argv[r->argno], argl[r->argno]);
1657 if (r->raw_after && !(r->next && r->next->nchars == 0
1658 && r->next->raw_before))
1659 CPP_PUTS_Q (pfile, "##", 2);
1664 i = defn->length - (x - defn->expansion) - 2;
1665 if (*x == '\r') x += 2, i -= 2;
1666 if (i > 0) CPP_PUTS (pfile, x, i);
1669 if (pfile->lineno == 0)
1670 CPP_PUTC (pfile, '\n');
1671 CPP_NUL_TERMINATE (pfile);