2 * Copyright (c) 2002 - 2014 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.
48 static const char copyright[] =
50 "@(#) $Author: Tony Finch (dot@dotat.at) $\n"
51 "@(#) $URL: http://dotat.at/prog/unifdef $\n"
54 /* types of input lines: */
56 LT_TRUEI, /* a true #if with ignore flag */
57 LT_FALSEI, /* a false #if with ignore flag */
58 LT_IF, /* an unknown #if */
59 LT_TRUE, /* a true #if */
60 LT_FALSE, /* a false #if */
61 LT_ELIF, /* an unknown #elif */
62 LT_ELTRUE, /* a true #elif */
63 LT_ELFALSE, /* a false #elif */
65 LT_ENDIF, /* #endif */
66 LT_DODGY, /* flag: directive is not on one line */
67 LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
68 LT_PLAIN, /* ordinary line */
69 LT_EOF, /* end of file */
70 LT_ERROR, /* unevaluable #if */
74 static char const * const linetype_name[] = {
75 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
76 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
77 "DODGY TRUEI", "DODGY FALSEI",
78 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
79 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
80 "DODGY ELSE", "DODGY ENDIF",
81 "PLAIN", "EOF", "ERROR"
84 #define linetype_if2elif(lt) ((Linetype)(lt - LT_IF + LT_ELIF))
85 #define linetype_2dodgy(lt) ((Linetype)(lt + LT_DODGY))
87 /* state of #if processing */
90 IS_FALSE_PREFIX, /* false #if followed by false #elifs */
91 IS_TRUE_PREFIX, /* first non-false #(el)if is true */
92 IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
93 IS_FALSE_MIDDLE, /* a false #elif after a pass state */
94 IS_TRUE_MIDDLE, /* a true #elif after a pass state */
95 IS_PASS_ELSE, /* an else after a pass state */
96 IS_FALSE_ELSE, /* an else after a true state */
97 IS_TRUE_ELSE, /* an else after only false states */
98 IS_FALSE_TRAILER, /* #elifs after a true are false */
102 static char const * const ifstate_name[] = {
103 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
104 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
105 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
109 /* state of comment parser */
111 NO_COMMENT = false, /* outside a comment */
112 C_COMMENT, /* in a comment like this one */
113 CXX_COMMENT, /* between // and end of line */
114 STARTING_COMMENT, /* just after slash-backslash-newline */
115 FINISHING_COMMENT, /* star-backslash-newline in a C comment */
116 CHAR_LITERAL, /* inside '' */
117 STRING_LITERAL /* inside "" */
120 static char const * const comment_name[] = {
121 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
124 /* state of preprocessor line parser */
126 LS_START, /* only space and comments on this line */
127 LS_HASH, /* only space, comments, and a hash */
128 LS_DIRTY /* this line can't be a preprocessor line */
131 static char const * const linestate_name[] = {
132 "START", "HASH", "DIRTY"
136 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
138 #define MAXDEPTH 64 /* maximum #if nesting */
139 #define MAXLINE 4096 /* maximum length of line */
140 #define MAXSYMS 16384 /* maximum number of symbols */
143 * Sometimes when editing a keyword the replacement text is longer, so
144 * we leave some space at the end of the tline buffer to accommodate this.
152 static bool compblank; /* -B: compress blank lines */
153 static bool lnblank; /* -b: blank deleted lines */
154 static bool complement; /* -c: do the complement */
155 static bool debugging; /* -d: debugging reports */
156 static bool inplace; /* -m: modify in place */
157 static bool iocccok; /* -e: fewer IOCCC errors */
158 static bool strictlogic; /* -K: keep ambiguous #ifs */
159 static bool killconsts; /* -k: eval constant #ifs */
160 static bool lnnum; /* -n: add #line directives */
161 static bool symlist; /* -s: output symbol list */
162 static bool symdepth; /* -S: output symbol depth */
163 static bool text; /* -t: this is a text file */
165 static const char *symname[MAXSYMS]; /* symbol name */
166 static const char *value[MAXSYMS]; /* -Dsym=value */
167 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
168 static int nsyms; /* number of symbols */
170 static FILE *input; /* input file pointer */
171 static const char *filename; /* input file name */
172 static int linenum; /* current line number */
173 static const char *linefile; /* file name for #line */
174 static FILE *output; /* output file pointer */
175 static const char *ofilename; /* output file name */
176 static const char *backext; /* backup extension */
177 static char *tempname; /* avoid splatting input */
179 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
180 static char *keyword; /* used for editing #elif's */
183 * When processing a file, the output's newline style will match the
184 * input's, and unifdef correctly handles CRLF or LF endings whatever
185 * the platform's native style. The stdio streams are opened in binary
186 * mode to accommodate platforms whose native newline style is CRLF.
187 * When the output isn't a processed input file (when it is error /
188 * debug / diagnostic messages) then unifdef uses native line endings.
191 static const char *newline; /* input file format */
192 static const char newline_unix[] = "\n";
193 static const char newline_crlf[] = "\r\n";
195 static Comment_state incomment; /* comment parser state */
196 static Line_state linestate; /* #if line parser state */
197 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
198 static bool ignoring[MAXDEPTH]; /* ignore comments state */
199 static int stifline[MAXDEPTH]; /* start of current #if */
200 static int depth; /* current #if nesting */
201 static int delcount; /* count of deleted lines */
202 static unsigned blankcount; /* count of blank lines */
203 static unsigned blankmax; /* maximum recent blankcount */
204 static bool constexpr; /* constant #if expression */
205 static bool zerosyms; /* to format symdepth output */
206 static bool firstsym; /* ditto */
208 static int exitmode; /* exit status mode */
209 static int exitstat; /* program exit status */
210 static bool altered; /* was this file modified? */
212 static void addsym1(bool, bool, char *);
213 static void addsym2(bool, const char *, const char *);
214 static char *astrcat(const char *, const char *);
215 static void cleantemp(void);
216 static void closeio(void);
217 static void debug(const char *, ...) __printflike(1, 2);
218 static void debugsym(const char *, int);
219 static bool defundef(void);
220 static void defundefile(const char *);
221 static void done(void);
222 static void error(const char *);
223 static int findsym(const char **);
224 static void flushline(bool);
225 static void hashline(void);
226 static void help(void);
227 static Linetype ifeval(const char **);
228 static void ignoreoff(void);
229 static void ignoreon(void);
230 static void indirectsym(void);
231 static void keywordedit(const char *);
232 static const char *matchsym(const char *, const char *);
233 static void nest(void);
234 static Linetype parseline(void);
235 static void process(void);
236 static void processinout(const char *, const char *);
237 static const char *skipargs(const char *);
238 static const char *skipcomment(const char *);
239 static const char *skiphash(void);
240 static const char *skipline(const char *);
241 static const char *skipsym(const char *);
242 static void state(Ifstate);
243 static void unnest(void);
244 static void usage(void);
245 static void version(void);
246 static const char *xstrdup(const char *, const char *);
248 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
254 main(int argc, char *argv[])
258 while ((opt = getopt(argc, argv, "i:D:U:f:I:M:o:x:bBcdehKklmnsStV")) != -1)
260 case 'i': /* treat stuff controlled by these symbols as text */
262 * For strict backwards-compatibility the U or D
263 * should be immediately after the -i but it doesn't
264 * matter much if we relax that requirement.
268 addsym1(true, true, optarg);
270 addsym1(true, false, optarg);
274 case 'D': /* define a symbol */
275 addsym1(false, true, optarg);
277 case 'U': /* undef a symbol */
278 addsym1(false, false, optarg);
280 case 'I': /* no-op for compatibility with cpp */
282 case 'b': /* blank deleted lines instead of omitting them */
283 case 'l': /* backwards compatibility */
286 case 'B': /* compress blank lines around removed section */
289 case 'c': /* treat -D as -U and vice versa */
295 case 'e': /* fewer errors from dodgy lines */
298 case 'f': /* definitions file */
304 case 'K': /* keep ambiguous #ifs */
307 case 'k': /* process constant #ifs */
310 case 'm': /* modify in place */
313 case 'M': /* modify in place and keep backup */
317 case 'n': /* add #line directive after deleted lines */
320 case 'o': /* output to a file */
323 case 's': /* only output list of symbols that control #ifs */
326 case 'S': /* list symbols with their nesting depth */
327 symlist = symdepth = true;
329 case 't': /* don't parse C comments */
336 exitmode = atoi(optarg);
337 if(exitmode < 0 || exitmode > 2)
345 if (compblank && lnblank)
346 errx(2, "-B and -b are mutually exclusive");
347 if (symlist && (ofilename != NULL || inplace || argc > 1))
348 errx(2, "-s only works with one input file");
349 if (argc > 1 && ofilename != NULL)
350 errx(2, "-o cannot be used with multiple input files");
351 if (argc > 1 && !inplace)
352 errx(2, "multiple input files require -m or -M");
355 if (argc == 1 && !inplace && ofilename == NULL)
360 if (ofilename != NULL)
361 processinout(*argv, ofilename);
362 else while (argc-- > 0) {
363 processinout(*argv, *argv);
367 case(0): exit(exitstat);
368 case(1): exit(!exitstat);
370 default: abort(); /* bug */
378 processinout(const char *ifn, const char *ofn)
382 if (ifn == NULL || strcmp(ifn, "-") == 0) {
383 filename = "[stdin]";
385 input = fbinmode(stdin);
389 input = fopen(ifn, "rb");
391 err(2, "can't open %s", ifn);
393 if (strcmp(ofn, "-") == 0) {
394 output = fbinmode(stdout);
398 if (stat(ofn, &st) < 0) {
399 output = fopen(ofn, "wb");
401 err(2, "can't create %s", ofn);
406 tempname = astrcat(ofn, ".XXXXXX");
407 output = mktempmode(tempname, st.st_mode);
409 err(2, "can't create %s", tempname);
413 if (backext != NULL) {
414 char *backname = astrcat(ofn, backext);
415 if (rename(ofn, backname) < 0)
416 err(2, "can't rename \"%s\" to \"%s\"", ofn, backname);
419 /* leave file unmodified if unifdef made no changes */
420 if (!altered && backext == NULL) {
421 if (remove(tempname) < 0)
422 warn("can't remove \"%s\"", tempname);
423 } else if (replace(tempname, ofn) < 0)
424 err(2, "can't rename \"%s\" to \"%s\"", tempname, ofn);
430 * For cleaning up if there is an error.
435 if (tempname != NULL)
440 * Self-identification functions.
446 const char *c = copyright;
461 "usage: unifdef [-bBcdehKkmnsStV] [-x{012}] [-Mext] [-opath] \\\n"
462 " [-[i]Dsym[=val]] [-[i]Usym] [-fpath] ... [file] ...\n");
477 " -Dsym=val define preprocessor symbol with given value\n"
478 " -Dsym define preprocessor symbol with value 1\n"
479 " -Usym preprocessor symbol is undefined\n"
480 " -iDsym=val \\ ignore C strings and comments\n"
481 " -iDsym ) in sections controlled by these\n"
482 " -iUsym / preprocessor symbols\n"
483 " -fpath file containing #define and #undef directives\n"
484 " -b blank lines instead of deleting them\n"
485 " -B compress blank lines around deleted section\n"
486 " -c complement (invert) keep vs. delete\n"
487 " -d debugging mode\n"
488 " -e ignore multiline preprocessor directives\n"
490 " -Ipath extra include file path (ignored)\n"
491 " -K disable && and || short-circuiting\n"
492 " -k process constant #if expressions\n"
493 " -Mext modify in place and keep backups\n"
494 " -m modify input files in place\n"
495 " -n add #line directives to output\n"
496 " -opath output file name\n"
497 " -S list #if control symbols with nesting\n"
498 " -s list #if control symbols\n"
499 " -t ignore C strings and comments\n"
500 " -V print version\n"
501 " -x{012} exit status mode\n"
507 * A state transition function alters the global #if processing state
508 * in a particular way. The table below is indexed by the current
509 * processing state and the type of the current line.
511 * Nesting is handled by keeping a stack of states; some transition
512 * functions increase or decrease the depth. They also maintain the
513 * ignore state on a stack. In some complicated cases they have to
514 * alter the preprocessor directive, as follows.
516 * When we have processed a group that starts off with a known-false
517 * #if/#elif sequence (which has therefore been deleted) followed by a
518 * #elif that we don't understand and therefore must keep, we edit the
519 * latter into a #if to keep the nesting correct. We use memcpy() to
520 * overwrite the 4 byte token "elif" with "if " without a '\0' byte.
522 * When we find a true #elif in a group, the following block will
523 * always be kept and the rest of the sequence after the next #elif or
524 * #else will be discarded. We edit the #elif into a #else and the
525 * following directive to #endif since this has the desired behaviour.
527 * "Dodgy" directives are split across multiple lines, the most common
528 * example being a multi-line comment hanging off the right of the
529 * directive. We can handle them correctly only if there is no change
530 * from printing to dropping (or vice versa) caused by that directive.
531 * If the directive is the first of a group we have a choice between
532 * failing with an error, or passing it through unchanged instead of
533 * evaluating it. The latter is not the default to avoid questions from
534 * users about unifdef unexpectedly leaving behind preprocessor directives.
536 typedef void state_fn(void);
538 /* report an error */
539 static void Eelif (void) { error("Inappropriate #elif"); }
540 static void Eelse (void) { error("Inappropriate #else"); }
541 static void Eendif(void) { error("Inappropriate #endif"); }
542 static void Eeof (void) { error("Premature EOF"); }
543 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
544 /* plain line handling */
545 static void print (void) { flushline(true); }
546 static void drop (void) { flushline(false); }
547 /* output lacks group's start line */
548 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
549 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
550 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
551 /* print/pass this block */
552 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
553 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
554 static void Pendif(void) { print(); unnest(); }
555 /* discard this block */
556 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
557 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
558 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
559 static void Dendif(void) { drop(); unnest(); }
560 /* first line of group */
561 static void Fdrop (void) { nest(); Dfalse(); }
562 static void Fpass (void) { nest(); Pelif(); }
563 static void Ftrue (void) { nest(); Strue(); }
564 static void Ffalse(void) { nest(); Sfalse(); }
565 /* variable pedantry for obfuscated lines */
566 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
567 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
568 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
569 /* ignore comments in this block */
570 static void Idrop (void) { Fdrop(); ignoreon(); }
571 static void Itrue (void) { Ftrue(); ignoreon(); }
572 static void Ifalse(void) { Ffalse(); ignoreon(); }
573 /* modify this line */
574 static void Mpass (void) { memcpy(keyword, "if ", 4); Pelif(); }
575 static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); }
576 static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
577 static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
579 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
581 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
582 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
583 print, done, abort },
584 /* IS_FALSE_PREFIX */
585 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
586 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
589 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
590 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
591 print, Eeof, abort },
593 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
594 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
595 print, Eeof, abort },
596 /* IS_FALSE_MIDDLE */
597 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
598 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
601 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
602 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
603 print, Eeof, abort },
605 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
606 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
607 print, Eeof, abort },
609 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
610 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
613 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
614 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
615 print, Eeof, abort },
616 /* IS_FALSE_TRAILER */
617 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
618 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
620 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
621 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
626 * State machine utility functions
633 ignoring[depth] = ignoring[depth-1];
638 ignoring[depth] = true;
641 keywordedit(const char *replacement)
643 snprintf(keyword, tline + sizeof(tline) - keyword,
644 "%s%s", replacement, newline);
651 if (depth > MAXDEPTH-1)
653 if (depth == MAXDEPTH-1)
654 error("Too many levels of nesting");
656 stifline[depth] = linenum;
672 * The last state transition function. When this is called,
673 * lineval == LT_EOF, so the process() loop will terminate.
679 error("EOF in comment");
684 * Write a line to the output or not, according to command line options.
685 * If writing fails, closeio() will print the error and exit.
692 if (keep ^ complement) {
693 bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
694 if (blankline && compblank && blankcount != blankmax) {
698 if (lnnum && delcount > 0)
700 if (fputs(tline, output) == EOF)
703 blankmax = blankcount = blankline ? blankcount + 1 : 0;
706 if (lnblank && fputs(newline, output) == EOF)
712 if (debugging && fflush(output) == EOF)
717 * Format of #line directives depends on whether we know the input filename.
724 if (linefile == NULL)
725 e = fprintf(output, "#line %d%s", linenum, newline);
727 e = fprintf(output, "#line %d \"%s\"%s",
728 linenum, linefile, newline);
734 * Flush the output and handle errors.
739 /* Tidy up after findsym(). */
740 if (symdepth && !zerosyms)
742 if (output != NULL && (ferror(output) || fclose(output) == EOF))
743 err(2, "%s: can't write to output", filename);
748 * The driver for the state machine.
753 Linetype lineval = LT_PLAIN;
754 /* When compressing blank lines, act as if the file
755 is preceded by a large number of blank lines. */
756 blankmax = blankcount = 1000;
761 while (lineval != LT_EOF) {
762 lineval = parseline();
763 trans_table[ifstate[depth]][lineval]();
764 debug("process line %d %s -> %s depth %d",
765 linenum, linetype_name[lineval],
766 ifstate_name[ifstate[depth]], depth);
772 * Parse a line and determine its type. We keep the preprocessor line
773 * parser state between calls in the global variable linestate, with
774 * help from skipcomment().
782 Comment_state wascomment;
784 wascomment = incomment;
788 if (newline == NULL) {
789 if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
790 newline = newline_crlf;
792 newline = newline_unix;
798 keyword = tline + (cp - tline);
799 if ((cp = matchsym("ifdef", keyword)) != NULL ||
800 (cp = matchsym("ifndef", keyword)) != NULL) {
801 cp = skipcomment(cp);
802 if ((cursym = findsym(&cp)) < 0)
805 retval = (keyword[2] == 'n')
806 ? LT_FALSE : LT_TRUE;
807 if (value[cursym] == NULL)
808 retval = (retval == LT_TRUE)
809 ? LT_FALSE : LT_TRUE;
811 retval = (retval == LT_TRUE)
812 ? LT_TRUEI : LT_FALSEI;
814 } else if ((cp = matchsym("if", keyword)) != NULL)
815 retval = ifeval(&cp);
816 else if ((cp = matchsym("elif", keyword)) != NULL)
817 retval = linetype_if2elif(ifeval(&cp));
818 else if ((cp = matchsym("else", keyword)) != NULL)
820 else if ((cp = matchsym("endif", keyword)) != NULL)
823 cp = skipsym(keyword);
824 /* no way can we deal with a continuation inside a keyword */
825 if (strncmp(cp, "\\\r\n", 3) == 0 ||
826 strncmp(cp, "\\\n", 2) == 0)
832 cp = skipcomment(cp);
835 if (retval == LT_TRUE || retval == LT_FALSE ||
836 retval == LT_TRUEI || retval == LT_FALSEI)
838 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
841 /* the following can happen if the last line of the file lacks a
842 newline or if there is too much whitespace in a directive */
843 if (linestate == LS_HASH) {
844 long len = cp - tline;
845 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
847 err(2, "can't read %s", filename);
848 /* append the missing newline at eof */
849 strcpy(tline + len, newline);
850 cp += strlen(newline);
851 linestate = LS_START;
853 linestate = LS_DIRTY;
856 if (retval != LT_PLAIN && (wascomment || linestate != LS_START)) {
857 retval = linetype_2dodgy(retval);
858 linestate = LS_DIRTY;
861 debug("parser line %d state %s comment %s line", linenum,
862 comment_name[incomment], linestate_name[linestate]);
867 * These are the binary operators that are supported by the expression
870 static Linetype op_strict(long *p, long v, Linetype at, Linetype bt) {
871 if(at == LT_IF || bt == LT_IF) return (LT_IF);
872 return (*p = v, v ? LT_TRUE : LT_FALSE);
874 static Linetype op_lt(long *p, Linetype at, long a, Linetype bt, long b) {
875 return op_strict(p, a < b, at, bt);
877 static Linetype op_gt(long *p, Linetype at, long a, Linetype bt, long b) {
878 return op_strict(p, a > b, at, bt);
880 static Linetype op_le(long *p, Linetype at, long a, Linetype bt, long b) {
881 return op_strict(p, a <= b, at, bt);
883 static Linetype op_ge(long *p, Linetype at, long a, Linetype bt, long b) {
884 return op_strict(p, a >= b, at, bt);
886 static Linetype op_eq(long *p, Linetype at, long a, Linetype bt, long b) {
887 return op_strict(p, a == b, at, bt);
889 static Linetype op_ne(long *p, Linetype at, long a, Linetype bt, long b) {
890 return op_strict(p, a != b, at, bt);
892 static Linetype op_or(long *p, Linetype at, long a, Linetype bt, long b) {
893 if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
894 return (*p = 1, LT_TRUE);
895 return op_strict(p, a || b, at, bt);
897 static Linetype op_and(long *p, Linetype at, long a, Linetype bt, long b) {
898 if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
899 return (*p = 0, LT_FALSE);
900 return op_strict(p, a && b, at, bt);
904 * An evaluation function takes three arguments, as follows: (1) a pointer to
905 * an element of the precedence table which lists the operators at the current
906 * level of precedence; (2) a pointer to an integer which will receive the
907 * value of the expression; and (3) a pointer to a char* that points to the
908 * expression to be evaluated and that is updated to the end of the expression
909 * when evaluation is complete. The function returns LT_FALSE if the value of
910 * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
911 * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
915 typedef Linetype eval_fn(const struct ops *, long *, const char **);
917 static eval_fn eval_table, eval_unary;
920 * The precedence table. Expressions involving binary operators are evaluated
921 * in a table-driven way by eval_table. When it evaluates a subexpression it
922 * calls the inner function with its first argument pointing to the next
923 * element of the table. Innermost expressions have special non-table-driven
928 Linetype (*fn)(long *, Linetype, long, Linetype, long);
934 static const struct ops eval_ops[] = {
935 { eval_table, { { "||", op_or } } },
936 { eval_table, { { "&&", op_and } } },
937 { eval_table, { { "==", op_eq },
939 { eval_unary, { { "<=", op_le },
945 /* Current operator precedence level */
946 static long prec(const struct ops *ops)
948 return (ops - eval_ops);
952 * Function for evaluating the innermost parts of expressions,
953 * viz. !expr (expr) number defined(symbol) symbol
954 * We reset the constexpr flag in the last two cases.
957 eval_unary(const struct ops *ops, long *valp, const char **cpp)
965 cp = skipcomment(*cpp);
967 debug("eval%ld !", prec(ops));
969 lt = eval_unary(ops, valp, &cp);
974 lt = *valp ? LT_TRUE : LT_FALSE;
976 } else if (*cp == '(') {
978 debug("eval%ld (", prec(ops));
979 lt = eval_table(eval_ops, valp, &cp);
982 cp = skipcomment(cp);
985 } else if (isdigit((unsigned char)*cp)) {
986 debug("eval%ld number", prec(ops));
987 *valp = strtol(cp, &ep, 0);
990 lt = *valp ? LT_TRUE : LT_FALSE;
992 } else if (matchsym("defined", cp) != NULL) {
993 cp = skipcomment(cp+7);
995 cp = skipcomment(cp+1);
1001 cp = skipcomment(cp);
1002 if (defparen && *cp++ != ')') {
1003 debug("eval%ld defined missing ')'", prec(ops));
1007 debug("eval%ld defined unknown", prec(ops));
1010 debug("eval%ld defined %s", prec(ops), symname[sym]);
1011 *valp = (value[sym] != NULL);
1012 lt = *valp ? LT_TRUE : LT_FALSE;
1015 } else if (!endsym(*cp)) {
1016 debug("eval%ld symbol", prec(ops));
1021 } else if (value[sym] == NULL) {
1025 *valp = strtol(value[sym], &ep, 0);
1026 if (*ep != '\0' || ep == value[sym])
1028 lt = *valp ? LT_TRUE : LT_FALSE;
1033 debug("eval%ld bad expr", prec(ops));
1038 debug("eval%ld = %ld", prec(ops), *valp);
1043 * Table-driven evaluation of binary operators.
1046 eval_table(const struct ops *ops, long *valp, const char **cpp)
1048 const struct op *op;
1053 debug("eval%ld", prec(ops));
1055 lt = ops->inner(ops+1, valp, &cp);
1059 cp = skipcomment(cp);
1060 for (op = ops->op; op->str != NULL; op++)
1061 if (strncmp(cp, op->str, strlen(op->str)) == 0)
1063 if (op->str == NULL)
1065 cp += strlen(op->str);
1066 debug("eval%ld %s", prec(ops), op->str);
1067 rt = ops->inner(ops+1, &val, &cp);
1070 lt = op->fn(valp, lt, *valp, rt, val);
1074 debug("eval%ld = %ld", prec(ops), *valp);
1075 debug("eval%ld lt = %s", prec(ops), linetype_name[lt]);
1080 * Evaluate the expression on a #if or #elif line. If we can work out
1081 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
1082 * return just a generic LT_IF.
1085 ifeval(const char **cpp)
1090 debug("eval %s", *cpp);
1091 constexpr = killconsts ? false : true;
1092 ret = eval_table(eval_ops, &val, cpp);
1093 debug("eval = %ld", val);
1094 return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
1098 * Read a line and examine its initial part to determine if it is a
1099 * preprocessor directive. Returns NULL on EOF, or a pointer to a
1100 * preprocessor directive name, or a pointer to the zero byte at the
1109 if (fgets(tline, MAXLINE, input) == NULL) {
1111 err(2, "can't read %s", filename);
1115 cp = skipcomment(tline);
1116 if (linestate == LS_START && *cp == '#') {
1117 linestate = LS_HASH;
1118 return (skipcomment(cp + 1));
1119 } else if (*cp == '\0') {
1122 return (skipline(cp));
1127 * Mark a line dirty and consume the rest of it, keeping track of the
1131 skipline(const char *cp)
1134 linestate = LS_DIRTY;
1136 cp = skipcomment(cp + 1);
1141 * Skip over comments, strings, and character literals and stop at the
1142 * next character position that is not whitespace. Between calls we keep
1143 * the comment state in the global variable incomment, and we also adjust
1144 * the global variable linestate when we see a newline.
1145 * XXX: doesn't cope with the buffer splitting inside a state transition.
1148 skipcomment(const char *cp)
1150 if (text || ignoring[depth]) {
1151 for (; isspace((unsigned char)*cp); cp++)
1153 linestate = LS_START;
1157 /* don't reset to LS_START after a line continuation */
1158 if (strncmp(cp, "\\\r\n", 3) == 0)
1160 else if (strncmp(cp, "\\\n", 2) == 0)
1162 else switch (incomment) {
1164 if (strncmp(cp, "/\\\r\n", 4) == 0) {
1165 incomment = STARTING_COMMENT;
1167 } else if (strncmp(cp, "/\\\n", 3) == 0) {
1168 incomment = STARTING_COMMENT;
1170 } else if (strncmp(cp, "/*", 2) == 0) {
1171 incomment = C_COMMENT;
1173 } else if (strncmp(cp, "//", 2) == 0) {
1174 incomment = CXX_COMMENT;
1176 } else if (strncmp(cp, "\'", 1) == 0) {
1177 incomment = CHAR_LITERAL;
1178 linestate = LS_DIRTY;
1180 } else if (strncmp(cp, "\"", 1) == 0) {
1181 incomment = STRING_LITERAL;
1182 linestate = LS_DIRTY;
1184 } else if (strncmp(cp, "\n", 1) == 0) {
1185 linestate = LS_START;
1187 } else if (strchr(" \r\t", *cp) != NULL) {
1193 if (strncmp(cp, "\n", 1) == 0) {
1194 incomment = NO_COMMENT;
1195 linestate = LS_START;
1200 case STRING_LITERAL:
1201 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
1202 (incomment == STRING_LITERAL && cp[0] == '\"')) {
1203 incomment = NO_COMMENT;
1205 } else if (cp[0] == '\\') {
1210 } else if (strncmp(cp, "\n", 1) == 0) {
1211 if (incomment == CHAR_LITERAL)
1212 error("unterminated char literal");
1214 error("unterminated string literal");
1219 if (strncmp(cp, "*\\\r\n", 4) == 0) {
1220 incomment = FINISHING_COMMENT;
1222 } else if (strncmp(cp, "*\\\n", 3) == 0) {
1223 incomment = FINISHING_COMMENT;
1225 } else if (strncmp(cp, "*/", 2) == 0) {
1226 incomment = NO_COMMENT;
1231 case STARTING_COMMENT:
1233 incomment = C_COMMENT;
1235 } else if (*cp == '/') {
1236 incomment = CXX_COMMENT;
1239 incomment = NO_COMMENT;
1240 linestate = LS_DIRTY;
1243 case FINISHING_COMMENT:
1245 incomment = NO_COMMENT;
1248 incomment = C_COMMENT;
1257 * Skip macro arguments.
1260 skipargs(const char *cp)
1262 const char *ocp = cp;
1264 cp = skipcomment(cp);
1272 cp = skipcomment(cp+1);
1273 } while (level != 0 && *cp != '\0');
1277 /* Rewind and re-detect the syntax error later. */
1282 * Skip over an identifier.
1285 skipsym(const char *cp)
1287 while (!endsym(*cp))
1293 * Skip whitespace and take a copy of any following identifier.
1296 getsym(const char **cpp)
1298 const char *cp = *cpp, *sym;
1300 cp = skipcomment(cp);
1301 cp = skipsym(sym = cp);
1305 return (xstrdup(sym, cp));
1309 * Check that s (a symbol) matches the start of t, and that the
1310 * following character in t is not a symbol character. Returns a
1311 * pointer to the following character in t if there is a match,
1315 matchsym(const char *s, const char *t)
1317 while (*s != '\0' && *t != '\0')
1322 if (*s == '\0' && endsym(*t))
1329 * Look for the symbol in the symbol table. If it is found, we return
1330 * the symbol table index, else we return -1.
1333 findsym(const char **strp)
1339 *strp = skipsym(str);
1343 if (symdepth && firstsym)
1344 printf("%s%3d", zerosyms ? "" : "\n", depth);
1345 firstsym = zerosyms = false;
1347 symdepth ? " " : "",
1348 (int)(*strp-str), str,
1349 symdepth ? "" : "\n");
1350 /* we don't care about the value of the symbol */
1353 for (symind = 0; symind < nsyms; ++symind) {
1354 if (matchsym(symname[symind], str) != NULL) {
1355 debugsym("findsym", symind);
1363 * Resolve indirect symbol values to their final definitions.
1369 int changed, sym, ind;
1373 for (sym = 0; sym < nsyms; ++sym) {
1374 if (value[sym] == NULL)
1378 if (ind == -1 || ind == sym ||
1380 value[ind] == NULL ||
1381 value[ind] == value[sym])
1383 debugsym("indir...", sym);
1384 value[sym] = value[ind];
1385 debugsym("...ectsym", sym);
1392 * Add a symbol to the symbol table, specified with the format sym=val
1395 addsym1(bool ignorethis, bool definethis, char *symval)
1397 const char *sym, *val;
1401 if (definethis && *val == '=') {
1402 symval[val - sym] = '\0';
1404 } else if (*val == '\0') {
1405 val = definethis ? "1" : NULL;
1409 addsym2(ignorethis, sym, val);
1413 * Add a symbol to the symbol table.
1416 addsym2(bool ignorethis, const char *sym, const char *val)
1418 const char *cp = sym;
1421 symind = findsym(&cp);
1423 if (nsyms >= MAXSYMS)
1424 errx(2, "too many symbols");
1427 ignore[symind] = ignorethis;
1428 symname[symind] = sym;
1429 value[symind] = val;
1430 debugsym("addsym", symind);
1434 debugsym(const char *why, int symind)
1436 debug("%s %s%c%s", why, symname[symind],
1437 value[symind] ? '=' : ' ',
1438 value[symind] ? value[symind] : "undef");
1442 * Add symbols to the symbol table from a file containing
1443 * #define and #undef preprocessor directives.
1446 defundefile(const char *fn)
1449 input = fopen(fn, "rb");
1451 err(2, "can't open %s", fn);
1456 err(2, "can't read %s", filename);
1460 error("EOF in comment");
1464 * Read and process one #define or #undef directive
1469 const char *cp, *kw, *sym, *val, *end;
1476 /* strip trailing whitespace, and do a fairly rough check to
1477 avoid unsupported multi-line preprocessor directives */
1478 end = cp + strlen(cp);
1479 while (end > tline && strchr(" \t\n\r", end[-1]) != NULL)
1481 if (end > tline && end[-1] == '\\')
1485 if ((cp = matchsym("define", kw)) != NULL) {
1488 error("missing macro name in #define");
1492 cp = skipcomment(cp);
1493 val = (cp < end) ? xstrdup(cp, end) : "";
1496 addsym2(false, sym, val);
1497 } else if ((cp = matchsym("undef", kw)) != NULL) {
1500 error("missing macro name in #undef");
1501 cp = skipcomment(cp);
1503 addsym2(false, sym, NULL);
1505 error("unrecognized preprocessor directive");
1509 debug("parser line %d state %s comment %s line", linenum,
1510 comment_name[incomment], linestate_name[linestate]);
1515 * Concatenate two strings into new memory, checking for failure.
1518 astrcat(const char *s1, const char *s2)
1524 len = snprintf(NULL, 0, "%s%s", s1, s2);
1527 size = (size_t)len + 1;
1528 s = (char *)malloc(size);
1531 snprintf(s, size, "%s%s", s1, s2);
1536 * Duplicate a segment of a string, checking for failure.
1539 xstrdup(const char *start, const char *end)
1544 if (end < start) abort(); /* bug */
1545 n = (size_t)(end - start) + 1;
1549 snprintf(s, n, "%s", start);
1557 debug(const char *msg, ...)
1569 error(const char *msg)
1572 warnx("%s: %d: %s", filename, linenum, msg);
1574 warnx("%s: %d: %s (#if line %d depth %d)",
1575 filename, linenum, msg, stifline[depth], depth);
1577 errx(2, "output may be truncated");