2 * Copyright (c) 2002 - 2011 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 * These require better buffer handling, which would also make
43 * it possible to handle all "dodgy" directives correctly.
46 #include <sys/types.h>
59 const char copyright[] =
60 "@(#) $Version: unifdef-2.5.6.21f1388 $\n"
62 "@(#) $Author: Tony Finch (dot@dotat.at) $\n"
63 "@(#) $URL: http://dotat.at/prog/unifdef $\n"
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 symdepth; /* -S: output symbol depth */
176 static bool text; /* -t: this is a text file */
178 static const char *symname[MAXSYMS]; /* symbol name */
179 static const char *value[MAXSYMS]; /* -Dsym=value */
180 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
181 static int nsyms; /* number of symbols */
183 static FILE *input; /* input file pointer */
184 static const char *filename; /* input file name */
185 static int linenum; /* current line number */
186 static FILE *output; /* output file pointer */
187 static const char *ofilename; /* output file name */
188 static bool overwriting; /* output overwrites input */
189 static char tempname[FILENAME_MAX]; /* used when overwriting */
191 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
192 static char *keyword; /* used for editing #elif's */
194 static const char *newline; /* input file format */
195 static const char newline_unix[] = "\n";
196 static const char newline_crlf[] = "\r\n";
198 static Comment_state incomment; /* comment parser state */
199 static Line_state linestate; /* #if line parser state */
200 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
201 static bool ignoring[MAXDEPTH]; /* ignore comments state */
202 static int stifline[MAXDEPTH]; /* start of current #if */
203 static int depth; /* current #if nesting */
204 static int delcount; /* count of deleted lines */
205 static unsigned blankcount; /* count of blank lines */
206 static unsigned blankmax; /* maximum recent blankcount */
207 static bool constexpr; /* constant #if expression */
208 static bool zerosyms = true; /* to format symdepth output */
209 static bool firstsym; /* ditto */
211 static int exitstat; /* program exit status */
213 static void addsym(bool, bool, char *);
214 static void closeout(void);
215 static void debug(const char *, ...);
216 static void done(void);
217 static void error(const char *);
218 static int findsym(const char *);
219 static void flushline(bool);
220 static Linetype parseline(void);
221 static Linetype ifeval(const char **);
222 static void ignoreoff(void);
223 static void ignoreon(void);
224 static void keywordedit(const char *);
225 static void nest(void);
226 static void process(void);
227 static const char *skipargs(const char *);
228 static const char *skipcomment(const char *);
229 static const char *skipsym(const char *);
230 static void state(Ifstate);
231 static int strlcmp(const char *, const char *, size_t);
232 static void unnest(void);
233 static void usage(void);
234 static void version(void);
236 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
242 main(int argc, char *argv[])
246 while ((opt = getopt(argc, argv, "i:D:U:I:o:bBcdeKklnsStV")) != -1)
248 case 'i': /* treat stuff controlled by these symbols as text */
250 * For strict backwards-compatibility the U or D
251 * should be immediately after the -i but it doesn't
252 * matter much if we relax that requirement.
256 addsym(true, true, optarg);
258 addsym(true, false, optarg);
262 case 'D': /* define a symbol */
263 addsym(false, true, optarg);
265 case 'U': /* undef a symbol */
266 addsym(false, false, optarg);
268 case 'I': /* no-op for compatibility with cpp */
270 case 'b': /* blank deleted lines instead of omitting them */
271 case 'l': /* backwards compatibility */
274 case 'B': /* compress blank lines around removed section */
277 case 'c': /* treat -D as -U and vice versa */
283 case 'e': /* fewer errors from dodgy lines */
286 case 'K': /* keep ambiguous #ifs */
289 case 'k': /* process constant #ifs */
292 case 'n': /* add #line directive after deleted lines */
295 case 'o': /* output to a file */
298 case 's': /* only output list of symbols that control #ifs */
301 case 'S': /* list symbols with their nesting depth */
302 symlist = symdepth = true;
304 case 't': /* don't parse C comments */
307 case 'V': /* print version */
314 if (compblank && lnblank)
315 errx(2, "-B and -b are mutually exclusive");
317 errx(2, "can only do one file");
318 } else if (argc == 1 && strcmp(*argv, "-") != 0) {
320 input = fopen(filename, "rb");
322 err(2, "can't open %s", filename);
324 filename = "[stdin]";
327 if (ofilename == NULL) {
328 ofilename = "[stdout]";
331 struct stat ist, ost;
332 if (stat(ofilename, &ost) == 0 &&
333 fstat(fileno(input), &ist) == 0)
334 overwriting = (ist.st_dev == ost.st_dev
335 && ist.st_ino == ost.st_ino);
340 dirsep = strrchr(ofilename, '/');
342 snprintf(tempname, sizeof(tempname),
344 (int)(dirsep - ofilename), ofilename);
346 snprintf(tempname, sizeof(tempname),
348 ofd = mkstemp(tempname);
350 output = fdopen(ofd, "wb+");
352 err(2, "can't create temporary file");
353 fchmod(ofd, ist.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO));
355 output = fopen(ofilename, "wb");
357 err(2, "can't open %s", ofilename);
367 const char *c = copyright;
381 fprintf(stderr, "usage: unifdef [-bBcdeKknsStV] [-Ipath]"
382 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
387 * A state transition function alters the global #if processing state
388 * in a particular way. The table below is indexed by the current
389 * processing state and the type of the current line.
391 * Nesting is handled by keeping a stack of states; some transition
392 * functions increase or decrease the depth. They also maintain the
393 * ignore state on a stack. In some complicated cases they have to
394 * alter the preprocessor directive, as follows.
396 * When we have processed a group that starts off with a known-false
397 * #if/#elif sequence (which has therefore been deleted) followed by a
398 * #elif that we don't understand and therefore must keep, we edit the
399 * latter into a #if to keep the nesting correct. We use strncpy() to
400 * overwrite the 4 byte token "elif" with "if " without a '\0' byte.
402 * When we find a true #elif in a group, the following block will
403 * always be kept and the rest of the sequence after the next #elif or
404 * #else will be discarded. We edit the #elif into a #else and the
405 * following directive to #endif since this has the desired behaviour.
407 * "Dodgy" directives are split across multiple lines, the most common
408 * example being a multi-line comment hanging off the right of the
409 * directive. We can handle them correctly only if there is no change
410 * from printing to dropping (or vice versa) caused by that directive.
411 * If the directive is the first of a group we have a choice between
412 * failing with an error, or passing it through unchanged instead of
413 * evaluating it. The latter is not the default to avoid questions from
414 * users about unifdef unexpectedly leaving behind preprocessor directives.
416 typedef void state_fn(void);
418 /* report an error */
419 static void Eelif (void) { error("Inappropriate #elif"); }
420 static void Eelse (void) { error("Inappropriate #else"); }
421 static void Eendif(void) { error("Inappropriate #endif"); }
422 static void Eeof (void) { error("Premature EOF"); }
423 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
424 /* plain line handling */
425 static void print (void) { flushline(true); }
426 static void drop (void) { flushline(false); }
427 /* output lacks group's start line */
428 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
429 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
430 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
431 /* print/pass this block */
432 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
433 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
434 static void Pendif(void) { print(); unnest(); }
435 /* discard this block */
436 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
437 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
438 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
439 static void Dendif(void) { drop(); unnest(); }
440 /* first line of group */
441 static void Fdrop (void) { nest(); Dfalse(); }
442 static void Fpass (void) { nest(); Pelif(); }
443 static void Ftrue (void) { nest(); Strue(); }
444 static void Ffalse(void) { nest(); Sfalse(); }
445 /* variable pedantry for obfuscated lines */
446 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
447 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
448 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
449 /* ignore comments in this block */
450 static void Idrop (void) { Fdrop(); ignoreon(); }
451 static void Itrue (void) { Ftrue(); ignoreon(); }
452 static void Ifalse(void) { Ffalse(); ignoreon(); }
453 /* modify this line */
454 static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
455 static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); }
456 static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
457 static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
459 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
461 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
462 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
463 print, done, abort },
464 /* IS_FALSE_PREFIX */
465 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
466 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
469 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
470 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
471 print, Eeof, abort },
473 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
474 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
475 print, Eeof, abort },
476 /* IS_FALSE_MIDDLE */
477 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
478 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
481 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
482 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
483 print, Eeof, abort },
485 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
486 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
487 print, Eeof, abort },
489 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
490 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
493 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
494 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
495 print, Eeof, abort },
496 /* IS_FALSE_TRAILER */
497 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
498 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
500 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
501 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
506 * State machine utility functions
513 ignoring[depth] = ignoring[depth-1];
518 ignoring[depth] = true;
521 keywordedit(const char *replacement)
523 snprintf(keyword, tline + sizeof(tline) - keyword,
524 "%s%s", replacement, newline);
530 if (depth > MAXDEPTH-1)
532 if (depth == MAXDEPTH-1)
533 error("Too many levels of nesting");
535 stifline[depth] = linenum;
551 * Write a line to the output or not, according to command line options.
552 * If writing fails, closeout() will print the error and exit.
559 if (keep ^ complement) {
560 bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
561 if (blankline && compblank && blankcount != blankmax) {
565 if (lnnum && delcount > 0 &&
566 fprintf(output, "#line %d%s", linenum, newline) < 0)
568 if (fputs(tline, output) == EOF)
571 blankmax = blankcount = blankline ? blankcount + 1 : 0;
574 if (lnblank && fputs(newline, output) == EOF)
580 if (debugging && fflush(output) == EOF)
585 * The driver for the state machine.
590 /* When compressing blank lines, act as if the file
591 is preceded by a large number of blank lines. */
592 blankmax = blankcount = 1000;
594 Linetype lineval = parseline();
595 trans_table[ifstate[depth]][lineval]();
596 debug("process line %d %s -> %s depth %d",
597 linenum, linetype_name[lineval],
598 ifstate_name[ifstate[depth]], depth);
603 * Flush the output and handle errors.
608 if (symdepth && !zerosyms)
610 if (ferror(output) || fclose(output) == EOF) {
612 warn("couldn't write to temporary file");
614 errx(2, "%s unchanged", ofilename);
616 err(2, "couldn't write to %s", ofilename);
628 error("EOF in comment");
630 if (overwriting && rename(tempname, ofilename) == -1) {
631 warn("couldn't rename temporary file");
633 errx(2, "%s unchanged", ofilename);
639 * Parse a line and determine its type. We keep the preprocessor line
640 * parser state between calls in the global variable linestate, with
641 * help from skipcomment().
650 Comment_state wascomment;
653 if (fgets(tline, MAXLINE, input) == NULL) {
655 error(strerror(errno));
659 if (newline == NULL) {
660 if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
661 newline = newline_crlf;
663 newline = newline_unix;
666 wascomment = incomment;
667 cp = skipcomment(tline);
668 if (linestate == LS_START) {
672 cp = skipcomment(cp + 1);
673 } else if (*cp != '\0')
674 linestate = LS_DIRTY;
676 if (!incomment && linestate == LS_HASH) {
677 keyword = tline + (cp - tline);
679 kwlen = cp - keyword;
680 /* no way can we deal with a continuation inside a keyword */
681 if (strncmp(cp, "\\\r\n", 3) == 0 ||
682 strncmp(cp, "\\\n", 2) == 0)
684 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
685 strlcmp("ifndef", keyword, kwlen) == 0) {
686 cp = skipcomment(cp);
687 if ((cursym = findsym(cp)) < 0)
690 retval = (keyword[2] == 'n')
691 ? LT_FALSE : LT_TRUE;
692 if (value[cursym] == NULL)
693 retval = (retval == LT_TRUE)
694 ? LT_FALSE : LT_TRUE;
696 retval = (retval == LT_TRUE)
697 ? LT_TRUEI : LT_FALSEI;
700 } else if (strlcmp("if", keyword, kwlen) == 0)
701 retval = ifeval(&cp);
702 else if (strlcmp("elif", keyword, kwlen) == 0)
703 retval = ifeval(&cp) - LT_IF + LT_ELIF;
704 else if (strlcmp("else", keyword, kwlen) == 0)
706 else if (strlcmp("endif", keyword, kwlen) == 0)
709 linestate = LS_DIRTY;
712 cp = skipcomment(cp);
714 linestate = LS_DIRTY;
715 if (retval == LT_TRUE || retval == LT_FALSE ||
716 retval == LT_TRUEI || retval == LT_FALSEI)
718 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
721 if (retval != LT_PLAIN && (wascomment || incomment)) {
724 linestate = LS_DIRTY;
726 /* skipcomment normally changes the state, except
727 if the last line of the file lacks a newline, or
728 if there is too much whitespace in a directive */
729 if (linestate == LS_HASH) {
730 size_t len = cp - tline;
731 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
733 error(strerror(errno));
734 /* append the missing newline at eof */
735 strcpy(tline + len, newline);
736 cp += strlen(newline);
737 linestate = LS_START;
739 linestate = LS_DIRTY;
743 if (linestate == LS_DIRTY) {
745 cp = skipcomment(cp + 1);
747 debug("parser line %d state %s comment %s line", linenum,
748 comment_name[incomment], linestate_name[linestate]);
753 * These are the binary operators that are supported by the expression
756 static Linetype op_strict(int *p, int v, Linetype at, Linetype bt) {
757 if(at == LT_IF || bt == LT_IF) return (LT_IF);
758 return (*p = v, v ? LT_TRUE : LT_FALSE);
760 static Linetype op_lt(int *p, Linetype at, int a, Linetype bt, int b) {
761 return op_strict(p, a < b, at, bt);
763 static Linetype op_gt(int *p, Linetype at, int a, Linetype bt, int b) {
764 return op_strict(p, a > b, at, bt);
766 static Linetype op_le(int *p, Linetype at, int a, Linetype bt, int b) {
767 return op_strict(p, a <= b, at, bt);
769 static Linetype op_ge(int *p, Linetype at, int a, Linetype bt, int b) {
770 return op_strict(p, a >= b, at, bt);
772 static Linetype op_eq(int *p, Linetype at, int a, Linetype bt, int b) {
773 return op_strict(p, a == b, at, bt);
775 static Linetype op_ne(int *p, Linetype at, int a, Linetype bt, int b) {
776 return op_strict(p, a != b, at, bt);
778 static Linetype op_or(int *p, Linetype at, int a, Linetype bt, int b) {
779 if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
780 return (*p = 1, LT_TRUE);
781 return op_strict(p, a || b, at, bt);
783 static Linetype op_and(int *p, Linetype at, int a, Linetype bt, int b) {
784 if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
785 return (*p = 0, LT_FALSE);
786 return op_strict(p, a && b, at, bt);
790 * An evaluation function takes three arguments, as follows: (1) a pointer to
791 * an element of the precedence table which lists the operators at the current
792 * level of precedence; (2) a pointer to an integer which will receive the
793 * value of the expression; and (3) a pointer to a char* that points to the
794 * expression to be evaluated and that is updated to the end of the expression
795 * when evaluation is complete. The function returns LT_FALSE if the value of
796 * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
797 * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
801 typedef Linetype eval_fn(const struct ops *, int *, const char **);
803 static eval_fn eval_table, eval_unary;
806 * The precedence table. Expressions involving binary operators are evaluated
807 * in a table-driven way by eval_table. When it evaluates a subexpression it
808 * calls the inner function with its first argument pointing to the next
809 * element of the table. Innermost expressions have special non-table-driven
812 static const struct ops {
816 Linetype (*fn)(int *, Linetype, int, Linetype, int);
819 { eval_table, { { "||", op_or } } },
820 { eval_table, { { "&&", op_and } } },
821 { eval_table, { { "==", op_eq },
823 { eval_unary, { { "<=", op_le },
830 * Function for evaluating the innermost parts of expressions,
831 * viz. !expr (expr) number defined(symbol) symbol
832 * We reset the constexpr flag in the last two cases.
835 eval_unary(const struct ops *ops, int *valp, const char **cpp)
843 cp = skipcomment(*cpp);
845 debug("eval%d !", ops - eval_ops);
847 lt = eval_unary(ops, valp, &cp);
852 lt = *valp ? LT_TRUE : LT_FALSE;
854 } else if (*cp == '(') {
856 debug("eval%d (", ops - eval_ops);
857 lt = eval_table(eval_ops, valp, &cp);
860 cp = skipcomment(cp);
863 } else if (isdigit((unsigned char)*cp)) {
864 debug("eval%d number", ops - eval_ops);
865 *valp = strtol(cp, &ep, 0);
868 lt = *valp ? LT_TRUE : LT_FALSE;
870 } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
871 cp = skipcomment(cp+7);
872 debug("eval%d defined", ops - eval_ops);
874 cp = skipcomment(cp+1);
883 *valp = (value[sym] != NULL);
884 lt = *valp ? LT_TRUE : LT_FALSE;
887 cp = skipcomment(cp);
888 if (defparen && *cp++ != ')')
891 } else if (!endsym(*cp)) {
892 debug("eval%d symbol", ops - eval_ops);
898 } else if (value[sym] == NULL) {
902 *valp = strtol(value[sym], &ep, 0);
903 if (*ep != '\0' || ep == value[sym])
905 lt = *valp ? LT_TRUE : LT_FALSE;
910 debug("eval%d bad expr", ops - eval_ops);
915 debug("eval%d = %d", ops - eval_ops, *valp);
920 * Table-driven evaluation of binary operators.
923 eval_table(const struct ops *ops, int *valp, const char **cpp)
930 debug("eval%d", ops - eval_ops);
932 lt = ops->inner(ops+1, valp, &cp);
936 cp = skipcomment(cp);
937 for (op = ops->op; op->str != NULL; op++)
938 if (strncmp(cp, op->str, strlen(op->str)) == 0)
942 cp += strlen(op->str);
943 debug("eval%d %s", ops - eval_ops, op->str);
944 rt = ops->inner(ops+1, &val, &cp);
947 lt = op->fn(valp, lt, *valp, rt, val);
951 debug("eval%d = %d", ops - eval_ops, *valp);
952 debug("eval%d lt = %s", ops - eval_ops, linetype_name[lt]);
957 * Evaluate the expression on a #if or #elif line. If we can work out
958 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
959 * return just a generic LT_IF.
962 ifeval(const char **cpp)
967 debug("eval %s", *cpp);
968 constexpr = killconsts ? false : true;
969 ret = eval_table(eval_ops, &val, cpp);
970 debug("eval = %d", val);
971 return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
975 * Skip over comments, strings, and character literals and stop at the
976 * next character position that is not whitespace. Between calls we keep
977 * the comment state in the global variable incomment, and we also adjust
978 * the global variable linestate when we see a newline.
979 * XXX: doesn't cope with the buffer splitting inside a state transition.
982 skipcomment(const char *cp)
984 if (text || ignoring[depth]) {
985 for (; isspace((unsigned char)*cp); cp++)
987 linestate = LS_START;
991 /* don't reset to LS_START after a line continuation */
992 if (strncmp(cp, "\\\r\n", 3) == 0)
994 else if (strncmp(cp, "\\\n", 2) == 0)
996 else switch (incomment) {
998 if (strncmp(cp, "/\\\r\n", 4) == 0) {
999 incomment = STARTING_COMMENT;
1001 } else if (strncmp(cp, "/\\\n", 3) == 0) {
1002 incomment = STARTING_COMMENT;
1004 } else if (strncmp(cp, "/*", 2) == 0) {
1005 incomment = C_COMMENT;
1007 } else if (strncmp(cp, "//", 2) == 0) {
1008 incomment = CXX_COMMENT;
1010 } else if (strncmp(cp, "\'", 1) == 0) {
1011 incomment = CHAR_LITERAL;
1012 linestate = LS_DIRTY;
1014 } else if (strncmp(cp, "\"", 1) == 0) {
1015 incomment = STRING_LITERAL;
1016 linestate = LS_DIRTY;
1018 } else if (strncmp(cp, "\n", 1) == 0) {
1019 linestate = LS_START;
1021 } else if (strchr(" \r\t", *cp) != NULL) {
1027 if (strncmp(cp, "\n", 1) == 0) {
1028 incomment = NO_COMMENT;
1029 linestate = LS_START;
1034 case STRING_LITERAL:
1035 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
1036 (incomment == STRING_LITERAL && cp[0] == '\"')) {
1037 incomment = NO_COMMENT;
1039 } else if (cp[0] == '\\') {
1044 } else if (strncmp(cp, "\n", 1) == 0) {
1045 if (incomment == CHAR_LITERAL)
1046 error("unterminated char literal");
1048 error("unterminated string literal");
1053 if (strncmp(cp, "*\\\r\n", 4) == 0) {
1054 incomment = FINISHING_COMMENT;
1056 } else if (strncmp(cp, "*\\\n", 3) == 0) {
1057 incomment = FINISHING_COMMENT;
1059 } else if (strncmp(cp, "*/", 2) == 0) {
1060 incomment = NO_COMMENT;
1065 case STARTING_COMMENT:
1067 incomment = C_COMMENT;
1069 } else if (*cp == '/') {
1070 incomment = CXX_COMMENT;
1073 incomment = NO_COMMENT;
1074 linestate = LS_DIRTY;
1077 case FINISHING_COMMENT:
1079 incomment = NO_COMMENT;
1082 incomment = C_COMMENT;
1091 * Skip macro arguments.
1094 skipargs(const char *cp)
1096 const char *ocp = cp;
1098 cp = skipcomment(cp);
1106 cp = skipcomment(cp+1);
1107 } while (level != 0 && *cp != '\0');
1111 /* Rewind and re-detect the syntax error later. */
1116 * Skip over an identifier.
1119 skipsym(const char *cp)
1121 while (!endsym(*cp))
1127 * Look for the symbol in the symbol table. If it is found, we return
1128 * the symbol table index, else we return -1.
1131 findsym(const char *str)
1140 if (symdepth && firstsym)
1141 printf("%s%3d", zerosyms ? "" : "\n", depth);
1142 firstsym = zerosyms = false;
1144 symdepth ? " " : "",
1146 symdepth ? "" : "\n");
1147 /* we don't care about the value of the symbol */
1150 for (symind = 0; symind < nsyms; ++symind) {
1151 if (strlcmp(symname[symind], str, cp-str) == 0) {
1152 debug("findsym %s %s", symname[symind],
1153 value[symind] ? value[symind] : "");
1161 * Add a symbol to the symbol table.
1164 addsym(bool ignorethis, bool definethis, char *sym)
1169 symind = findsym(sym);
1171 if (nsyms >= MAXSYMS)
1172 errx(2, "too many symbols");
1175 symname[symind] = sym;
1176 ignore[symind] = ignorethis;
1177 val = sym + (skipsym(sym) - sym);
1180 value[symind] = val+1;
1182 } else if (*val == '\0')
1183 value[symind] = "1";
1189 value[symind] = NULL;
1191 debug("addsym %s=%s", symname[symind],
1192 value[symind] ? value[symind] : "undef");
1196 * Compare s with n characters of t.
1197 * The same as strncmp() except that it checks that s[n] == '\0'.
1200 strlcmp(const char *s, const char *t, size_t n)
1202 while (n-- && *t != '\0')
1204 return ((unsigned char)*s - (unsigned char)*t);
1207 return ((unsigned char)*s);
1214 debug(const char *msg, ...)
1226 error(const char *msg)
1229 warnx("%s: %d: %s", filename, linenum, msg);
1231 warnx("%s: %d: %s (#if line %d depth %d)",
1232 filename, linenum, msg, stifline[depth], depth);
1234 errx(2, "output may be truncated");