2 * Copyright (c) 2002 - 2010 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 * unifdef - remove ifdef'ed lines
29 * This code was derived from software contributed to Berkeley by Dave Yost.
30 * It was rewritten to support ANSI C by Tony Finch. The original version
31 * of unifdef carried the 4-clause BSD copyright licence. None of its code
32 * remains in this version (though some of the names remain) so it now
33 * carries a more liberal licence.
36 * provide an option which will append the name of the
37 * appropriate symbol after #else's and #endif's
38 * provide an option which will check symbols after
39 * #else's and #endif's to see that they match their
40 * corresponding #ifdef or #ifndef
42 * The first two items above require better buffer handling, which would
43 * also make it possible to handle all "dodgy" directives correctly.
46 #include <sys/types.h>
60 __IDSTRING(dotat, "$dotat: unifdef/unifdef.c,v 1.193 2010/01/19 18:03:02 fanf2 Exp $");
63 __FBSDID("$FreeBSD$");
66 /* types of input lines: */
68 LT_TRUEI, /* a true #if with ignore flag */
69 LT_FALSEI, /* a false #if with ignore flag */
70 LT_IF, /* an unknown #if */
71 LT_TRUE, /* a true #if */
72 LT_FALSE, /* a false #if */
73 LT_ELIF, /* an unknown #elif */
74 LT_ELTRUE, /* a true #elif */
75 LT_ELFALSE, /* a false #elif */
77 LT_ENDIF, /* #endif */
78 LT_DODGY, /* flag: directive is not on one line */
79 LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
80 LT_PLAIN, /* ordinary line */
81 LT_EOF, /* end of file */
82 LT_ERROR, /* unevaluable #if */
86 static char const * const linetype_name[] = {
87 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
88 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
89 "DODGY TRUEI", "DODGY FALSEI",
90 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
91 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
92 "DODGY ELSE", "DODGY ENDIF",
93 "PLAIN", "EOF", "ERROR"
96 /* state of #if processing */
99 IS_FALSE_PREFIX, /* false #if followed by false #elifs */
100 IS_TRUE_PREFIX, /* first non-false #(el)if is true */
101 IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
102 IS_FALSE_MIDDLE, /* a false #elif after a pass state */
103 IS_TRUE_MIDDLE, /* a true #elif after a pass state */
104 IS_PASS_ELSE, /* an else after a pass state */
105 IS_FALSE_ELSE, /* an else after a true state */
106 IS_TRUE_ELSE, /* an else after only false states */
107 IS_FALSE_TRAILER, /* #elifs after a true are false */
111 static char const * const ifstate_name[] = {
112 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
113 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
114 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
118 /* state of comment parser */
120 NO_COMMENT = false, /* outside a comment */
121 C_COMMENT, /* in a comment like this one */
122 CXX_COMMENT, /* between // and end of line */
123 STARTING_COMMENT, /* just after slash-backslash-newline */
124 FINISHING_COMMENT, /* star-backslash-newline in a C comment */
125 CHAR_LITERAL, /* inside '' */
126 STRING_LITERAL /* inside "" */
129 static char const * const comment_name[] = {
130 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
133 /* state of preprocessor line parser */
135 LS_START, /* only space and comments on this line */
136 LS_HASH, /* only space, comments, and a hash */
137 LS_DIRTY /* this line can't be a preprocessor line */
140 static char const * const linestate_name[] = {
141 "START", "HASH", "DIRTY"
145 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
147 #define MAXDEPTH 64 /* maximum #if nesting */
148 #define MAXLINE 4096 /* maximum length of line */
149 #define MAXSYMS 4096 /* maximum number of symbols */
152 * Sometimes when editing a keyword the replacement text is longer, so
153 * we leave some space at the end of the tline buffer to accommodate this.
158 * For temporary filenames
160 #define TEMPLATE "unifdef.XXXXXX"
166 static bool compblank; /* -B: compress blank lines */
167 static bool lnblank; /* -b: blank deleted lines */
168 static bool complement; /* -c: do the complement */
169 static bool debugging; /* -d: debugging reports */
170 static bool iocccok; /* -e: fewer IOCCC errors */
171 static bool strictlogic; /* -K: keep ambiguous #ifs */
172 static bool killconsts; /* -k: eval constant #ifs */
173 static bool lnnum; /* -n: add #line directives */
174 static bool symlist; /* -s: output symbol list */
175 static bool text; /* -t: this is a text file */
177 static const char *symname[MAXSYMS]; /* symbol name */
178 static const char *value[MAXSYMS]; /* -Dsym=value */
179 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
180 static int nsyms; /* number of symbols */
182 static FILE *input; /* input file pointer */
183 static const char *filename; /* input file name */
184 static int linenum; /* current line number */
185 static FILE *output; /* output file pointer */
186 static const char *ofilename; /* output file name */
187 static bool overwriting; /* output overwrites input */
188 static char tempname[FILENAME_MAX]; /* used when overwriting */
190 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
191 static char *keyword; /* used for editing #elif's */
193 static Comment_state incomment; /* comment parser state */
194 static Line_state linestate; /* #if line parser state */
195 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
196 static bool ignoring[MAXDEPTH]; /* ignore comments state */
197 static int stifline[MAXDEPTH]; /* start of current #if */
198 static int depth; /* current #if nesting */
199 static int delcount; /* count of deleted lines */
200 static unsigned blankcount; /* count of blank lines */
201 static unsigned blankmax; /* maximum recent blankcount */
202 static bool constexpr; /* constant #if expression */
204 static int exitstat; /* program exit status */
206 static void addsym(bool, bool, char *);
207 static void closeout(void);
208 static void debug(const char *, ...);
209 static void done(void);
210 static void error(const char *);
211 static int findsym(const char *);
212 static void flushline(bool);
213 static Linetype parseline(void);
214 static Linetype ifeval(const char **);
215 static void ignoreoff(void);
216 static void ignoreon(void);
217 static void keywordedit(const char *);
218 static void nest(void);
219 static void process(void);
220 static const char *skipargs(const char *);
221 static const char *skipcomment(const char *);
222 static const char *skipsym(const char *);
223 static void state(Ifstate);
224 static int strlcmp(const char *, const char *, size_t);
225 static void unnest(void);
226 static void usage(void);
228 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
234 main(int argc, char *argv[])
238 while ((opt = getopt(argc, argv, "i:D:U:I:o:BbcdeKklnst")) != -1)
240 case 'i': /* treat stuff controlled by these symbols as text */
242 * For strict backwards-compatibility the U or D
243 * should be immediately after the -i but it doesn't
244 * matter much if we relax that requirement.
248 addsym(true, true, optarg);
250 addsym(true, false, optarg);
254 case 'D': /* define a symbol */
255 addsym(false, true, optarg);
257 case 'U': /* undef a symbol */
258 addsym(false, false, optarg);
261 /* no-op for compatibility with cpp */
263 case 'B': /* compress blank lines around removed section */
266 case 'b': /* blank deleted lines instead of omitting them */
267 case 'l': /* backwards compatibility */
270 case 'c': /* treat -D as -U and vice versa */
276 case 'e': /* fewer errors from dodgy lines */
279 case 'K': /* keep ambiguous #ifs */
282 case 'k': /* process constant #ifs */
285 case 'n': /* add #line directive after deleted lines */
288 case 'o': /* output to a file */
291 case 's': /* only output list of symbols that control #ifs */
294 case 't': /* don't parse C comments */
302 if (compblank && lnblank)
303 errx(2, "-B and -b are mutually exclusive");
305 errx(2, "can only do one file");
306 } else if (argc == 1 && strcmp(*argv, "-") != 0) {
308 input = fopen(filename, "r");
310 err(2, "can't open %s", filename);
312 filename = "[stdin]";
315 if (ofilename == NULL) {
318 struct stat ist, ost;
319 memset(&ist, 0, sizeof(ist));
320 memset(&ost, 0, sizeof(ost));
322 if (fstat(fileno(input), &ist) != 0)
323 err(2, "can't fstat %s", filename);
324 if (stat(ofilename, &ost) != 0 && errno != ENOENT)
325 warn("can't stat %s", ofilename);
327 overwriting = (ist.st_dev == ost.st_dev
328 && ist.st_ino == ost.st_ino);
333 dirsep = strrchr(ofilename, '/');
335 snprintf(tempname, sizeof(tempname),
337 dirsep - ofilename, ofilename);
339 strlcpy(tempname, TEMPLATE, sizeof(tempname));
340 ofd = mkstemp(tempname);
342 output = fdopen(ofd, "w+");
344 err(2, "can't create temporary file");
345 fchmod(ofd, ist.st_mode & ACCESSPERMS);
347 output = fopen(ofilename, "w");
349 err(2, "can't open %s", ofilename);
359 fprintf(stderr, "usage: unifdef [-BbcdeKknst] [-Ipath]"
360 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
365 * A state transition function alters the global #if processing state
366 * in a particular way. The table below is indexed by the current
367 * processing state and the type of the current line.
369 * Nesting is handled by keeping a stack of states; some transition
370 * functions increase or decrease the depth. They also maintain the
371 * ignore state on a stack. In some complicated cases they have to
372 * alter the preprocessor directive, as follows.
374 * When we have processed a group that starts off with a known-false
375 * #if/#elif sequence (which has therefore been deleted) followed by a
376 * #elif that we don't understand and therefore must keep, we edit the
377 * latter into a #if to keep the nesting correct.
379 * When we find a true #elif in a group, the following block will
380 * always be kept and the rest of the sequence after the next #elif or
381 * #else will be discarded. We edit the #elif into a #else and the
382 * following directive to #endif since this has the desired behaviour.
384 * "Dodgy" directives are split across multiple lines, the most common
385 * example being a multi-line comment hanging off the right of the
386 * directive. We can handle them correctly only if there is no change
387 * from printing to dropping (or vice versa) caused by that directive.
388 * If the directive is the first of a group we have a choice between
389 * failing with an error, or passing it through unchanged instead of
390 * evaluating it. The latter is not the default to avoid questions from
391 * users about unifdef unexpectedly leaving behind preprocessor directives.
393 typedef void state_fn(void);
395 /* report an error */
396 static void Eelif (void) { error("Inappropriate #elif"); }
397 static void Eelse (void) { error("Inappropriate #else"); }
398 static void Eendif(void) { error("Inappropriate #endif"); }
399 static void Eeof (void) { error("Premature EOF"); }
400 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
401 /* plain line handling */
402 static void print (void) { flushline(true); }
403 static void drop (void) { flushline(false); }
404 /* output lacks group's start line */
405 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
406 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
407 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
408 /* print/pass this block */
409 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
410 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
411 static void Pendif(void) { print(); unnest(); }
412 /* discard this block */
413 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
414 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
415 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
416 static void Dendif(void) { drop(); unnest(); }
417 /* first line of group */
418 static void Fdrop (void) { nest(); Dfalse(); }
419 static void Fpass (void) { nest(); Pelif(); }
420 static void Ftrue (void) { nest(); Strue(); }
421 static void Ffalse(void) { nest(); Sfalse(); }
422 /* variable pedantry for obfuscated lines */
423 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
424 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
425 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
426 /* ignore comments in this block */
427 static void Idrop (void) { Fdrop(); ignoreon(); }
428 static void Itrue (void) { Ftrue(); ignoreon(); }
429 static void Ifalse(void) { Ffalse(); ignoreon(); }
431 static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
432 static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
433 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
434 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
436 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
438 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
439 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
440 print, done, abort },
441 /* IS_FALSE_PREFIX */
442 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
443 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
446 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
447 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
448 print, Eeof, abort },
450 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
451 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
452 print, Eeof, abort },
453 /* IS_FALSE_MIDDLE */
454 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
455 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
458 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
459 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
460 print, Eeof, abort },
462 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
463 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
464 print, Eeof, abort },
466 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
467 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
470 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
471 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
472 print, Eeof, abort },
473 /* IS_FALSE_TRAILER */
474 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
475 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
477 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
478 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
483 * State machine utility functions
490 ignoring[depth] = ignoring[depth-1];
495 ignoring[depth] = true;
498 keywordedit(const char *replacement)
500 strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
506 if (depth > MAXDEPTH-1)
508 if (depth == MAXDEPTH-1)
509 error("Too many levels of nesting");
511 stifline[depth] = linenum;
527 * Write a line to the output or not, according to command line options.
534 if (keep ^ complement) {
535 bool blankline = tline[strspn(tline, " \t\n")] == '\0';
536 if (blankline && compblank && blankcount != blankmax) {
540 if (lnnum && delcount > 0)
541 printf("#line %d\n", linenum);
542 fputs(tline, output);
544 blankmax = blankcount = blankline ? blankcount + 1 : 0;
556 * The driver for the state machine.
563 /* When compressing blank lines, act as if the file
564 is preceded by a large number of blank lines. */
565 blankmax = blankcount = 1000;
568 lineval = parseline();
569 trans_table[ifstate[depth]][lineval]();
570 debug("process %s -> %s depth %d",
571 linetype_name[lineval],
572 ifstate_name[ifstate[depth]], depth);
577 * Flush the output and handle errors.
582 if (fclose(output) == EOF) {
583 warn("couldn't write to output");
586 errx(2, "%s unchanged", filename);
600 error("EOF in comment");
602 if (overwriting && rename(tempname, filename) == -1) {
603 warn("couldn't rename temporary file");
605 errx(2, "%s unchanged", filename);
611 * Parse a line and determine its type. We keep the preprocessor line
612 * parser state between calls in the global variable linestate, with
613 * help from skipcomment().
622 Comment_state wascomment;
624 if (fgets(tline, MAXLINE, input) == NULL)
627 wascomment = incomment;
628 cp = skipcomment(tline);
629 if (linestate == LS_START) {
632 cp = skipcomment(cp + 1);
633 } else if (*cp != '\0')
634 linestate = LS_DIRTY;
636 if (!incomment && linestate == LS_HASH) {
637 keyword = tline + (cp - tline);
639 kwlen = cp - keyword;
640 /* no way can we deal with a continuation inside a keyword */
641 if (strncmp(cp, "\\\n", 2) == 0)
643 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
644 strlcmp("ifndef", keyword, kwlen) == 0) {
645 cp = skipcomment(cp);
646 if ((cursym = findsym(cp)) < 0)
649 retval = (keyword[2] == 'n')
650 ? LT_FALSE : LT_TRUE;
651 if (value[cursym] == NULL)
652 retval = (retval == LT_TRUE)
653 ? LT_FALSE : LT_TRUE;
655 retval = (retval == LT_TRUE)
656 ? LT_TRUEI : LT_FALSEI;
659 } else if (strlcmp("if", keyword, kwlen) == 0)
660 retval = ifeval(&cp);
661 else if (strlcmp("elif", keyword, kwlen) == 0)
662 retval = ifeval(&cp) - LT_IF + LT_ELIF;
663 else if (strlcmp("else", keyword, kwlen) == 0)
665 else if (strlcmp("endif", keyword, kwlen) == 0)
668 linestate = LS_DIRTY;
671 cp = skipcomment(cp);
673 linestate = LS_DIRTY;
674 if (retval == LT_TRUE || retval == LT_FALSE ||
675 retval == LT_TRUEI || retval == LT_FALSEI)
677 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
680 if (retval != LT_PLAIN && (wascomment || incomment)) {
683 linestate = LS_DIRTY;
685 /* skipcomment normally changes the state, except
686 if the last line of the file lacks a newline, or
687 if there is too much whitespace in a directive */
688 if (linestate == LS_HASH) {
689 size_t len = cp - tline;
690 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
691 /* append the missing newline */
695 linestate = LS_START;
697 linestate = LS_DIRTY;
701 if (linestate == LS_DIRTY) {
703 cp = skipcomment(cp + 1);
705 debug("parser %s comment %s line",
706 comment_name[incomment], linestate_name[linestate]);
711 * These are the binary operators that are supported by the expression
714 static Linetype op_strict(int *p, int v, Linetype at, Linetype bt) {
715 if(at == LT_IF || bt == LT_IF) return (LT_IF);
716 return (*p = v, v ? LT_TRUE : LT_FALSE);
718 static Linetype op_lt(int *p, Linetype at, int a, Linetype bt, int b) {
719 return op_strict(p, a < b, at, bt);
721 static Linetype op_gt(int *p, Linetype at, int a, Linetype bt, int b) {
722 return op_strict(p, a > b, at, bt);
724 static Linetype op_le(int *p, Linetype at, int a, Linetype bt, int b) {
725 return op_strict(p, a <= b, at, bt);
727 static Linetype op_ge(int *p, Linetype at, int a, Linetype bt, int b) {
728 return op_strict(p, a >= b, at, bt);
730 static Linetype op_eq(int *p, Linetype at, int a, Linetype bt, int b) {
731 return op_strict(p, a == b, at, bt);
733 static Linetype op_ne(int *p, Linetype at, int a, Linetype bt, int b) {
734 return op_strict(p, a != b, at, bt);
736 static Linetype op_or(int *p, Linetype at, int a, Linetype bt, int b) {
737 if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
738 return (*p = 1, LT_TRUE);
739 return op_strict(p, a || b, at, bt);
741 static Linetype op_and(int *p, Linetype at, int a, Linetype bt, int b) {
742 if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
743 return (*p = 0, LT_FALSE);
744 return op_strict(p, a && b, at, bt);
748 * An evaluation function takes three arguments, as follows: (1) a pointer to
749 * an element of the precedence table which lists the operators at the current
750 * level of precedence; (2) a pointer to an integer which will receive the
751 * value of the expression; and (3) a pointer to a char* that points to the
752 * expression to be evaluated and that is updated to the end of the expression
753 * when evaluation is complete. The function returns LT_FALSE if the value of
754 * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
755 * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
759 typedef Linetype eval_fn(const struct ops *, int *, const char **);
761 static eval_fn eval_table, eval_unary;
764 * The precedence table. Expressions involving binary operators are evaluated
765 * in a table-driven way by eval_table. When it evaluates a subexpression it
766 * calls the inner function with its first argument pointing to the next
767 * element of the table. Innermost expressions have special non-table-driven
770 static const struct ops {
774 Linetype (*fn)(int *, Linetype, int, Linetype, int);
777 { eval_table, { { "||", op_or } } },
778 { eval_table, { { "&&", op_and } } },
779 { eval_table, { { "==", op_eq },
781 { eval_unary, { { "<=", op_le },
788 * Function for evaluating the innermost parts of expressions,
789 * viz. !expr (expr) number defined(symbol) symbol
790 * We reset the constexpr flag in the last two cases.
793 eval_unary(const struct ops *ops, int *valp, const char **cpp)
801 cp = skipcomment(*cpp);
803 debug("eval%d !", ops - eval_ops);
805 lt = eval_unary(ops, valp, &cp);
810 lt = *valp ? LT_TRUE : LT_FALSE;
812 } else if (*cp == '(') {
814 debug("eval%d (", ops - eval_ops);
815 lt = eval_table(eval_ops, valp, &cp);
818 cp = skipcomment(cp);
821 } else if (isdigit((unsigned char)*cp)) {
822 debug("eval%d number", ops - eval_ops);
823 *valp = strtol(cp, &ep, 0);
826 lt = *valp ? LT_TRUE : LT_FALSE;
828 } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
829 cp = skipcomment(cp+7);
830 debug("eval%d defined", ops - eval_ops);
832 cp = skipcomment(cp+1);
841 *valp = (value[sym] != NULL);
842 lt = *valp ? LT_TRUE : LT_FALSE;
845 cp = skipcomment(cp);
846 if (defparen && *cp++ != ')')
849 } else if (!endsym(*cp)) {
850 debug("eval%d symbol", ops - eval_ops);
856 } else if (value[sym] == NULL) {
860 *valp = strtol(value[sym], &ep, 0);
861 if (*ep != '\0' || ep == value[sym])
863 lt = *valp ? LT_TRUE : LT_FALSE;
868 debug("eval%d bad expr", ops - eval_ops);
873 debug("eval%d = %d", ops - eval_ops, *valp);
878 * Table-driven evaluation of binary operators.
881 eval_table(const struct ops *ops, int *valp, const char **cpp)
888 debug("eval%d", ops - eval_ops);
890 lt = ops->inner(ops+1, valp, &cp);
894 cp = skipcomment(cp);
895 for (op = ops->op; op->str != NULL; op++)
896 if (strncmp(cp, op->str, strlen(op->str)) == 0)
900 cp += strlen(op->str);
901 debug("eval%d %s", ops - eval_ops, op->str);
902 rt = ops->inner(ops+1, &val, &cp);
905 lt = op->fn(valp, lt, *valp, rt, val);
909 debug("eval%d = %d", ops - eval_ops, *valp);
910 debug("eval%d lt = %s", ops - eval_ops, linetype_name[lt]);
915 * Evaluate the expression on a #if or #elif line. If we can work out
916 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
917 * return just a generic LT_IF.
920 ifeval(const char **cpp)
925 debug("eval %s", *cpp);
926 constexpr = killconsts ? false : true;
927 ret = eval_table(eval_ops, &val, cpp);
928 debug("eval = %d", val);
929 return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
933 * Skip over comments, strings, and character literals and stop at the
934 * next character position that is not whitespace. Between calls we keep
935 * the comment state in the global variable incomment, and we also adjust
936 * the global variable linestate when we see a newline.
937 * XXX: doesn't cope with the buffer splitting inside a state transition.
940 skipcomment(const char *cp)
942 if (text || ignoring[depth]) {
943 for (; isspace((unsigned char)*cp); cp++)
945 linestate = LS_START;
949 /* don't reset to LS_START after a line continuation */
950 if (strncmp(cp, "\\\n", 2) == 0)
952 else switch (incomment) {
954 if (strncmp(cp, "/\\\n", 3) == 0) {
955 incomment = STARTING_COMMENT;
957 } else if (strncmp(cp, "/*", 2) == 0) {
958 incomment = C_COMMENT;
960 } else if (strncmp(cp, "//", 2) == 0) {
961 incomment = CXX_COMMENT;
963 } else if (strncmp(cp, "\'", 1) == 0) {
964 incomment = CHAR_LITERAL;
965 linestate = LS_DIRTY;
967 } else if (strncmp(cp, "\"", 1) == 0) {
968 incomment = STRING_LITERAL;
969 linestate = LS_DIRTY;
971 } else if (strncmp(cp, "\n", 1) == 0) {
972 linestate = LS_START;
974 } else if (strchr(" \t", *cp) != NULL) {
980 if (strncmp(cp, "\n", 1) == 0) {
981 incomment = NO_COMMENT;
982 linestate = LS_START;
988 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
989 (incomment == STRING_LITERAL && cp[0] == '\"')) {
990 incomment = NO_COMMENT;
992 } else if (cp[0] == '\\') {
997 } else if (strncmp(cp, "\n", 1) == 0) {
998 if (incomment == CHAR_LITERAL)
999 error("unterminated char literal");
1001 error("unterminated string literal");
1006 if (strncmp(cp, "*\\\n", 3) == 0) {
1007 incomment = FINISHING_COMMENT;
1009 } else if (strncmp(cp, "*/", 2) == 0) {
1010 incomment = NO_COMMENT;
1015 case STARTING_COMMENT:
1017 incomment = C_COMMENT;
1019 } else if (*cp == '/') {
1020 incomment = CXX_COMMENT;
1023 incomment = NO_COMMENT;
1024 linestate = LS_DIRTY;
1027 case FINISHING_COMMENT:
1029 incomment = NO_COMMENT;
1032 incomment = C_COMMENT;
1041 * Skip macro arguments.
1044 skipargs(const char *cp)
1046 const char *ocp = cp;
1048 cp = skipcomment(cp);
1056 cp = skipcomment(cp+1);
1057 } while (level != 0 && *cp != '\0');
1061 /* Rewind and re-detect the syntax error later. */
1066 * Skip over an identifier.
1069 skipsym(const char *cp)
1071 while (!endsym(*cp))
1077 * Look for the symbol in the symbol table. If it is found, we return
1078 * the symbol table index, else we return -1.
1081 findsym(const char *str)
1090 printf("%.*s\n", (int)(cp-str), str);
1091 /* we don't care about the value of the symbol */
1094 for (symind = 0; symind < nsyms; ++symind) {
1095 if (strlcmp(symname[symind], str, cp-str) == 0) {
1096 debug("findsym %s %s", symname[symind],
1097 value[symind] ? value[symind] : "");
1105 * Add a symbol to the symbol table.
1108 addsym(bool ignorethis, bool definethis, char *sym)
1113 symind = findsym(sym);
1115 if (nsyms >= MAXSYMS)
1116 errx(2, "too many symbols");
1119 symname[symind] = sym;
1120 ignore[symind] = ignorethis;
1121 val = sym + (skipsym(sym) - sym);
1124 value[symind] = val+1;
1126 } else if (*val == '\0')
1133 value[symind] = NULL;
1138 * Compare s with n characters of t.
1139 * The same as strncmp() except that it checks that s[n] == '\0'.
1142 strlcmp(const char *s, const char *t, size_t n)
1144 while (n-- && *t != '\0')
1146 return ((unsigned char)*s - (unsigned char)*t);
1149 return ((unsigned char)*s);
1156 debug(const char *msg, ...)
1168 error(const char *msg)
1171 warnx("%s: %d: %s", filename, linenum, msg);
1173 warnx("%s: %d: %s (#if line %d depth %d)",
1174 filename, linenum, msg, stifline[depth], depth);
1176 errx(2, "output may be truncated");