2 * Copyright (c) 2002 - 2009 Tony Finch <dot@dotat.at>
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * This code was derived from software contributed to Berkeley by Dave Yost.
28 * It was rewritten to support ANSI C by Tony Finch. The original version
29 * of unifdef carried the 4-clause BSD copyright licence. None of its code
30 * remains in this version (though some of the names remain) so it now
31 * carries a more liberal licence.
33 * The latest version is available from http://dotat.at/prog/unifdef
36 #include <sys/cdefs.h>
39 __IDSTRING(dotat, "$dotat: unifdef/unifdef.c,v 1.190 2009/11/27 17:21:26 fanf2 Exp $");
42 __FBSDID("$FreeBSD$");
46 * unifdef - remove ifdef'ed lines
49 * provide an option which will append the name of the
50 * appropriate symbol after #else's and #endif's
51 * provide an option which will check symbols after
52 * #else's and #endif's to see that they match their
53 * corresponding #ifdef or #ifndef
55 * The first two items above require better buffer handling, which would
56 * also make it possible to handle all "dodgy" directives correctly.
68 /* types of input lines: */
70 LT_TRUEI, /* a true #if with ignore flag */
71 LT_FALSEI, /* a false #if with ignore flag */
72 LT_IF, /* an unknown #if */
73 LT_TRUE, /* a true #if */
74 LT_FALSE, /* a false #if */
75 LT_ELIF, /* an unknown #elif */
76 LT_ELTRUE, /* a true #elif */
77 LT_ELFALSE, /* a false #elif */
79 LT_ENDIF, /* #endif */
80 LT_DODGY, /* flag: directive is not on one line */
81 LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
82 LT_PLAIN, /* ordinary line */
83 LT_EOF, /* end of file */
84 LT_ERROR, /* unevaluable #if */
88 static char const * const linetype_name[] = {
89 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
90 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
91 "DODGY TRUEI", "DODGY FALSEI",
92 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
93 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
94 "DODGY ELSE", "DODGY ENDIF",
95 "PLAIN", "EOF", "ERROR"
98 /* state of #if processing */
101 IS_FALSE_PREFIX, /* false #if followed by false #elifs */
102 IS_TRUE_PREFIX, /* first non-false #(el)if is true */
103 IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
104 IS_FALSE_MIDDLE, /* a false #elif after a pass state */
105 IS_TRUE_MIDDLE, /* a true #elif after a pass state */
106 IS_PASS_ELSE, /* an else after a pass state */
107 IS_FALSE_ELSE, /* an else after a true state */
108 IS_TRUE_ELSE, /* an else after only false states */
109 IS_FALSE_TRAILER, /* #elifs after a true are false */
113 static char const * const ifstate_name[] = {
114 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
115 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
116 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
120 /* state of comment parser */
122 NO_COMMENT = false, /* outside a comment */
123 C_COMMENT, /* in a comment like this one */
124 CXX_COMMENT, /* between // and end of line */
125 STARTING_COMMENT, /* just after slash-backslash-newline */
126 FINISHING_COMMENT, /* star-backslash-newline in a C comment */
127 CHAR_LITERAL, /* inside '' */
128 STRING_LITERAL /* inside "" */
131 static char const * const comment_name[] = {
132 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
135 /* state of preprocessor line parser */
137 LS_START, /* only space and comments on this line */
138 LS_HASH, /* only space, comments, and a hash */
139 LS_DIRTY /* this line can't be a preprocessor line */
142 static char const * const linestate_name[] = {
143 "START", "HASH", "DIRTY"
147 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
149 #define MAXDEPTH 64 /* maximum #if nesting */
150 #define MAXLINE 4096 /* maximum length of line */
151 #define MAXSYMS 4096 /* maximum number of symbols */
154 * Sometimes when editing a keyword the replacement text is longer, so
155 * we leave some space at the end of the tline buffer to accommodate this.
163 static bool compblank; /* -B: compress blank lines */
164 static bool lnblank; /* -b: blank deleted lines */
165 static bool complement; /* -c: do the complement */
166 static bool debugging; /* -d: debugging reports */
167 static bool iocccok; /* -e: fewer IOCCC errors */
168 static bool strictlogic; /* -K: keep ambiguous #ifs */
169 static bool killconsts; /* -k: eval constant #ifs */
170 static bool lnnum; /* -n: add #line directives */
171 static bool symlist; /* -s: output symbol list */
172 static bool text; /* -t: this is a text file */
174 static const char *symname[MAXSYMS]; /* symbol name */
175 static const char *value[MAXSYMS]; /* -Dsym=value */
176 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
177 static int nsyms; /* number of symbols */
179 static FILE *input; /* input file pointer */
180 static const char *filename; /* input file name */
181 static int linenum; /* current line number */
183 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
184 static char *keyword; /* used for editing #elif's */
186 static Comment_state incomment; /* comment parser state */
187 static Line_state linestate; /* #if line parser state */
188 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
189 static bool ignoring[MAXDEPTH]; /* ignore comments state */
190 static int stifline[MAXDEPTH]; /* start of current #if */
191 static int depth; /* current #if nesting */
192 static int delcount; /* count of deleted lines */
193 static unsigned blankcount; /* count of blank lines */
194 static unsigned blankmax; /* maximum recent blankcount */
195 static bool constexpr; /* constant #if expression */
197 static int exitstat; /* program exit status */
199 static void addsym(bool, bool, char *);
200 static void debug(const char *, ...);
201 static void done(void);
202 static void error(const char *);
203 static int findsym(const char *);
204 static void flushline(bool);
205 static Linetype parseline(void);
206 static Linetype ifeval(const char **);
207 static void ignoreoff(void);
208 static void ignoreon(void);
209 static void keywordedit(const char *);
210 static void nest(void);
211 static void process(void);
212 static const char *skipargs(const char *);
213 static const char *skipcomment(const char *);
214 static const char *skipsym(const char *);
215 static void state(Ifstate);
216 static int strlcmp(const char *, const char *, size_t);
217 static void unnest(void);
218 static void usage(void);
220 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
226 main(int argc, char *argv[])
230 while ((opt = getopt(argc, argv, "i:D:U:I:BbcdeKklnst")) != -1)
232 case 'i': /* treat stuff controlled by these symbols as text */
234 * For strict backwards-compatibility the U or D
235 * should be immediately after the -i but it doesn't
236 * matter much if we relax that requirement.
240 addsym(true, true, optarg);
242 addsym(true, false, optarg);
246 case 'D': /* define a symbol */
247 addsym(false, true, optarg);
249 case 'U': /* undef a symbol */
250 addsym(false, false, optarg);
253 /* no-op for compatibility with cpp */
255 case 'B': /* compress blank lines around removed section */
258 case 'b': /* blank deleted lines instead of omitting them */
259 case 'l': /* backwards compatibility */
262 case 'c': /* treat -D as -U and vice versa */
268 case 'e': /* fewer errors from dodgy lines */
271 case 'K': /* keep ambiguous #ifs */
274 case 'k': /* process constant #ifs */
277 case 'n': /* add #line directive after deleted lines */
280 case 's': /* only output list of symbols that control #ifs */
283 case 't': /* don't parse C comments */
291 if (compblank && lnblank)
292 errx(2, "-B and -b are mutually exclusive");
294 errx(2, "can only do one file");
295 } else if (argc == 1 && strcmp(*argv, "-") != 0) {
297 input = fopen(filename, "r");
299 err(2, "can't open %s", filename);
301 filename = "[stdin]";
311 fprintf(stderr, "usage: unifdef [-BbcdeKknst] [-Ipath]"
312 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
317 * A state transition function alters the global #if processing state
318 * in a particular way. The table below is indexed by the current
319 * processing state and the type of the current line.
321 * Nesting is handled by keeping a stack of states; some transition
322 * functions increase or decrease the depth. They also maintain the
323 * ignore state on a stack. In some complicated cases they have to
324 * alter the preprocessor directive, as follows.
326 * When we have processed a group that starts off with a known-false
327 * #if/#elif sequence (which has therefore been deleted) followed by a
328 * #elif that we don't understand and therefore must keep, we edit the
329 * latter into a #if to keep the nesting correct.
331 * When we find a true #elif in a group, the following block will
332 * always be kept and the rest of the sequence after the next #elif or
333 * #else will be discarded. We edit the #elif into a #else and the
334 * following directive to #endif since this has the desired behaviour.
336 * "Dodgy" directives are split across multiple lines, the most common
337 * example being a multi-line comment hanging off the right of the
338 * directive. We can handle them correctly only if there is no change
339 * from printing to dropping (or vice versa) caused by that directive.
340 * If the directive is the first of a group we have a choice between
341 * failing with an error, or passing it through unchanged instead of
342 * evaluating it. The latter is not the default to avoid questions from
343 * users about unifdef unexpectedly leaving behind preprocessor directives.
345 typedef void state_fn(void);
347 /* report an error */
348 static void Eelif (void) { error("Inappropriate #elif"); }
349 static void Eelse (void) { error("Inappropriate #else"); }
350 static void Eendif(void) { error("Inappropriate #endif"); }
351 static void Eeof (void) { error("Premature EOF"); }
352 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
353 /* plain line handling */
354 static void print (void) { flushline(true); }
355 static void drop (void) { flushline(false); }
356 /* output lacks group's start line */
357 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
358 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
359 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
360 /* print/pass this block */
361 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
362 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
363 static void Pendif(void) { print(); unnest(); }
364 /* discard this block */
365 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
366 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
367 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
368 static void Dendif(void) { drop(); unnest(); }
369 /* first line of group */
370 static void Fdrop (void) { nest(); Dfalse(); }
371 static void Fpass (void) { nest(); Pelif(); }
372 static void Ftrue (void) { nest(); Strue(); }
373 static void Ffalse(void) { nest(); Sfalse(); }
374 /* variable pedantry for obfuscated lines */
375 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
376 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
377 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
378 /* ignore comments in this block */
379 static void Idrop (void) { Fdrop(); ignoreon(); }
380 static void Itrue (void) { Ftrue(); ignoreon(); }
381 static void Ifalse(void) { Ffalse(); ignoreon(); }
383 static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
384 static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
385 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
386 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
388 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
390 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
391 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
392 print, done, abort },
393 /* IS_FALSE_PREFIX */
394 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
395 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
398 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
399 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
400 print, Eeof, abort },
402 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
403 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
404 print, Eeof, abort },
405 /* IS_FALSE_MIDDLE */
406 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
407 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
410 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
411 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
412 print, Eeof, abort },
414 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
415 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
416 print, Eeof, abort },
418 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
419 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
422 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
423 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
424 print, Eeof, abort },
425 /* IS_FALSE_TRAILER */
426 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
427 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
429 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
430 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
435 * State machine utility functions
441 error("EOF in comment");
449 ignoring[depth] = ignoring[depth-1];
454 ignoring[depth] = true;
457 keywordedit(const char *replacement)
459 strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
465 if (depth > MAXDEPTH-1)
467 if (depth == MAXDEPTH-1)
468 error("Too many levels of nesting");
470 stifline[depth] = linenum;
486 * Write a line to the output or not, according to command line options.
493 if (keep ^ complement) {
494 bool blankline = tline[strspn(tline, " \t\n")] == '\0';
495 if (blankline && compblank && blankcount != blankmax) {
499 if (lnnum && delcount > 0)
500 printf("#line %d\n", linenum);
501 fputs(tline, stdout);
503 blankmax = blankcount = blankline ? blankcount + 1 : 0;
515 * The driver for the state machine.
522 /* When compressing blank lines, act as if the file
523 is preceded by a large number of blank lines. */
524 blankmax = blankcount = 1000;
527 lineval = parseline();
528 trans_table[ifstate[depth]][lineval]();
529 debug("process %s -> %s depth %d",
530 linetype_name[lineval],
531 ifstate_name[ifstate[depth]], depth);
536 * Parse a line and determine its type. We keep the preprocessor line
537 * parser state between calls in the global variable linestate, with
538 * help from skipcomment().
547 Comment_state wascomment;
549 if (fgets(tline, MAXLINE, input) == NULL)
552 wascomment = incomment;
553 cp = skipcomment(tline);
554 if (linestate == LS_START) {
557 cp = skipcomment(cp + 1);
558 } else if (*cp != '\0')
559 linestate = LS_DIRTY;
561 if (!incomment && linestate == LS_HASH) {
562 keyword = tline + (cp - tline);
564 kwlen = cp - keyword;
565 /* no way can we deal with a continuation inside a keyword */
566 if (strncmp(cp, "\\\n", 2) == 0)
568 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
569 strlcmp("ifndef", keyword, kwlen) == 0) {
570 cp = skipcomment(cp);
571 if ((cursym = findsym(cp)) < 0)
574 retval = (keyword[2] == 'n')
575 ? LT_FALSE : LT_TRUE;
576 if (value[cursym] == NULL)
577 retval = (retval == LT_TRUE)
578 ? LT_FALSE : LT_TRUE;
580 retval = (retval == LT_TRUE)
581 ? LT_TRUEI : LT_FALSEI;
584 } else if (strlcmp("if", keyword, kwlen) == 0)
585 retval = ifeval(&cp);
586 else if (strlcmp("elif", keyword, kwlen) == 0)
587 retval = ifeval(&cp) - LT_IF + LT_ELIF;
588 else if (strlcmp("else", keyword, kwlen) == 0)
590 else if (strlcmp("endif", keyword, kwlen) == 0)
593 linestate = LS_DIRTY;
596 cp = skipcomment(cp);
598 linestate = LS_DIRTY;
599 if (retval == LT_TRUE || retval == LT_FALSE ||
600 retval == LT_TRUEI || retval == LT_FALSEI)
602 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
605 if (retval != LT_PLAIN && (wascomment || incomment)) {
608 linestate = LS_DIRTY;
610 /* skipcomment normally changes the state, except
611 if the last line of the file lacks a newline, or
612 if there is too much whitespace in a directive */
613 if (linestate == LS_HASH) {
614 size_t len = cp - tline;
615 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
616 /* append the missing newline */
620 linestate = LS_START;
622 linestate = LS_DIRTY;
626 if (linestate == LS_DIRTY) {
628 cp = skipcomment(cp + 1);
630 debug("parser %s comment %s line",
631 comment_name[incomment], linestate_name[linestate]);
636 * These are the binary operators that are supported by the expression
639 static Linetype op_strict(int *p, int v, Linetype at, Linetype bt) {
640 if(at == LT_IF || bt == LT_IF) return (LT_IF);
641 return (*p = v, v ? LT_TRUE : LT_FALSE);
643 static Linetype op_lt(int *p, Linetype at, int a, Linetype bt, int b) {
644 return op_strict(p, a < b, at, bt);
646 static Linetype op_gt(int *p, Linetype at, int a, Linetype bt, int b) {
647 return op_strict(p, a > b, at, bt);
649 static Linetype op_le(int *p, Linetype at, int a, Linetype bt, int b) {
650 return op_strict(p, a <= b, at, bt);
652 static Linetype op_ge(int *p, Linetype at, int a, Linetype bt, int b) {
653 return op_strict(p, a >= b, at, bt);
655 static Linetype op_eq(int *p, Linetype at, int a, Linetype bt, int b) {
656 return op_strict(p, a == b, at, bt);
658 static Linetype op_ne(int *p, Linetype at, int a, Linetype bt, int b) {
659 return op_strict(p, a != b, at, bt);
661 static Linetype op_or(int *p, Linetype at, int a, Linetype bt, int b) {
662 if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
663 return (*p = 1, LT_TRUE);
664 return op_strict(p, a || b, at, bt);
666 static Linetype op_and(int *p, Linetype at, int a, Linetype bt, int b) {
667 if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
668 return (*p = 0, LT_FALSE);
669 return op_strict(p, a && b, at, bt);
673 * An evaluation function takes three arguments, as follows: (1) a pointer to
674 * an element of the precedence table which lists the operators at the current
675 * level of precedence; (2) a pointer to an integer which will receive the
676 * value of the expression; and (3) a pointer to a char* that points to the
677 * expression to be evaluated and that is updated to the end of the expression
678 * when evaluation is complete. The function returns LT_FALSE if the value of
679 * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
680 * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
684 typedef Linetype eval_fn(const struct ops *, int *, const char **);
686 static eval_fn eval_table, eval_unary;
689 * The precedence table. Expressions involving binary operators are evaluated
690 * in a table-driven way by eval_table. When it evaluates a subexpression it
691 * calls the inner function with its first argument pointing to the next
692 * element of the table. Innermost expressions have special non-table-driven
695 static const struct ops {
699 Linetype (*fn)(int *, Linetype, int, Linetype, int);
702 { eval_table, { { "||", op_or } } },
703 { eval_table, { { "&&", op_and } } },
704 { eval_table, { { "==", op_eq },
706 { eval_unary, { { "<=", op_le },
713 * Function for evaluating the innermost parts of expressions,
714 * viz. !expr (expr) number defined(symbol) symbol
715 * We reset the constexpr flag in the last two cases.
718 eval_unary(const struct ops *ops, int *valp, const char **cpp)
726 cp = skipcomment(*cpp);
728 debug("eval%d !", ops - eval_ops);
730 lt = eval_unary(ops, valp, &cp);
735 lt = *valp ? LT_TRUE : LT_FALSE;
737 } else if (*cp == '(') {
739 debug("eval%d (", ops - eval_ops);
740 lt = eval_table(eval_ops, valp, &cp);
743 cp = skipcomment(cp);
746 } else if (isdigit((unsigned char)*cp)) {
747 debug("eval%d number", ops - eval_ops);
748 *valp = strtol(cp, &ep, 0);
751 lt = *valp ? LT_TRUE : LT_FALSE;
753 } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
754 cp = skipcomment(cp+7);
755 debug("eval%d defined", ops - eval_ops);
757 cp = skipcomment(cp+1);
766 *valp = (value[sym] != NULL);
767 lt = *valp ? LT_TRUE : LT_FALSE;
770 cp = skipcomment(cp);
771 if (defparen && *cp++ != ')')
774 } else if (!endsym(*cp)) {
775 debug("eval%d symbol", ops - eval_ops);
781 } else if (value[sym] == NULL) {
785 *valp = strtol(value[sym], &ep, 0);
786 if (*ep != '\0' || ep == value[sym])
788 lt = *valp ? LT_TRUE : LT_FALSE;
793 debug("eval%d bad expr", ops - eval_ops);
798 debug("eval%d = %d", ops - eval_ops, *valp);
803 * Table-driven evaluation of binary operators.
806 eval_table(const struct ops *ops, int *valp, const char **cpp)
813 debug("eval%d", ops - eval_ops);
815 lt = ops->inner(ops+1, valp, &cp);
819 cp = skipcomment(cp);
820 for (op = ops->op; op->str != NULL; op++)
821 if (strncmp(cp, op->str, strlen(op->str)) == 0)
825 cp += strlen(op->str);
826 debug("eval%d %s", ops - eval_ops, op->str);
827 rt = ops->inner(ops+1, &val, &cp);
830 lt = op->fn(valp, lt, *valp, rt, val);
834 debug("eval%d = %d", ops - eval_ops, *valp);
835 debug("eval%d lt = %s", ops - eval_ops, linetype_name[lt]);
840 * Evaluate the expression on a #if or #elif line. If we can work out
841 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
842 * return just a generic LT_IF.
845 ifeval(const char **cpp)
850 debug("eval %s", *cpp);
851 constexpr = killconsts ? false : true;
852 ret = eval_table(eval_ops, &val, cpp);
853 debug("eval = %d", val);
854 return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
858 * Skip over comments, strings, and character literals and stop at the
859 * next character position that is not whitespace. Between calls we keep
860 * the comment state in the global variable incomment, and we also adjust
861 * the global variable linestate when we see a newline.
862 * XXX: doesn't cope with the buffer splitting inside a state transition.
865 skipcomment(const char *cp)
867 if (text || ignoring[depth]) {
868 for (; isspace((unsigned char)*cp); cp++)
870 linestate = LS_START;
874 /* don't reset to LS_START after a line continuation */
875 if (strncmp(cp, "\\\n", 2) == 0)
877 else switch (incomment) {
879 if (strncmp(cp, "/\\\n", 3) == 0) {
880 incomment = STARTING_COMMENT;
882 } else if (strncmp(cp, "/*", 2) == 0) {
883 incomment = C_COMMENT;
885 } else if (strncmp(cp, "//", 2) == 0) {
886 incomment = CXX_COMMENT;
888 } else if (strncmp(cp, "\'", 1) == 0) {
889 incomment = CHAR_LITERAL;
890 linestate = LS_DIRTY;
892 } else if (strncmp(cp, "\"", 1) == 0) {
893 incomment = STRING_LITERAL;
894 linestate = LS_DIRTY;
896 } else if (strncmp(cp, "\n", 1) == 0) {
897 linestate = LS_START;
899 } else if (strchr(" \t", *cp) != NULL) {
905 if (strncmp(cp, "\n", 1) == 0) {
906 incomment = NO_COMMENT;
907 linestate = LS_START;
913 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
914 (incomment == STRING_LITERAL && cp[0] == '\"')) {
915 incomment = NO_COMMENT;
917 } else if (cp[0] == '\\') {
922 } else if (strncmp(cp, "\n", 1) == 0) {
923 if (incomment == CHAR_LITERAL)
924 error("unterminated char literal");
926 error("unterminated string literal");
931 if (strncmp(cp, "*\\\n", 3) == 0) {
932 incomment = FINISHING_COMMENT;
934 } else if (strncmp(cp, "*/", 2) == 0) {
935 incomment = NO_COMMENT;
940 case STARTING_COMMENT:
942 incomment = C_COMMENT;
944 } else if (*cp == '/') {
945 incomment = CXX_COMMENT;
948 incomment = NO_COMMENT;
949 linestate = LS_DIRTY;
952 case FINISHING_COMMENT:
954 incomment = NO_COMMENT;
957 incomment = C_COMMENT;
966 * Skip macro arguments.
969 skipargs(const char *cp)
971 const char *ocp = cp;
973 cp = skipcomment(cp);
981 cp = skipcomment(cp+1);
982 } while (level != 0 && *cp != '\0');
986 /* Rewind and re-detect the syntax error later. */
991 * Skip over an identifier.
994 skipsym(const char *cp)
1002 * Look for the symbol in the symbol table. If it is found, we return
1003 * the symbol table index, else we return -1.
1006 findsym(const char *str)
1015 printf("%.*s\n", (int)(cp-str), str);
1016 /* we don't care about the value of the symbol */
1019 for (symind = 0; symind < nsyms; ++symind) {
1020 if (strlcmp(symname[symind], str, cp-str) == 0) {
1021 debug("findsym %s %s", symname[symind],
1022 value[symind] ? value[symind] : "");
1030 * Add a symbol to the symbol table.
1033 addsym(bool ignorethis, bool definethis, char *sym)
1038 symind = findsym(sym);
1040 if (nsyms >= MAXSYMS)
1041 errx(2, "too many symbols");
1044 symname[symind] = sym;
1045 ignore[symind] = ignorethis;
1046 val = sym + (skipsym(sym) - sym);
1049 value[symind] = val+1;
1051 } else if (*val == '\0')
1058 value[symind] = NULL;
1063 * Compare s with n characters of t.
1064 * The same as strncmp() except that it checks that s[n] == '\0'.
1067 strlcmp(const char *s, const char *t, size_t n)
1069 while (n-- && *t != '\0')
1071 return ((unsigned char)*s - (unsigned char)*t);
1074 return ((unsigned char)*s);
1081 debug(const char *msg, ...)
1093 error(const char *msg)
1096 warnx("%s: %d: %s", filename, linenum, msg);
1098 warnx("%s: %d: %s (#if line %d depth %d)",
1099 filename, linenum, msg, stifline[depth], depth);
1100 errx(2, "output may be truncated");