2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002 - 2015 Tony Finch <dot@dotat.at>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * unifdef - remove ifdef'ed lines
31 * This code was derived from software contributed to Berkeley by Dave Yost.
32 * It was rewritten to support ANSI C by Tony Finch. The original version
33 * of unifdef carried the 4-clause BSD copyright licence. None of its code
34 * remains in this version (though some of the names remain) so it now
35 * carries a more liberal licence.
38 * provide an option which will append the name of the
39 * appropriate symbol after #else's and #endif's
40 * provide an option which will check symbols after
41 * #else's and #endif's to see that they match their
42 * corresponding #ifdef or #ifndef
44 * These require better buffer handling, which would also make
45 * it possible to handle all "dodgy" directives correctly.
50 static const char copyright[] =
51 "@(#) $Version: unifdef-2.11 $\n"
53 "@(#) $Author: Tony Finch (dot@dotat.at) $\n"
54 "@(#) $URL: https://dotat.at/prog/unifdef $\n"
57 /* types of input lines: */
59 LT_TRUEI, /* a true #if with ignore flag */
60 LT_FALSEI, /* a false #if with ignore flag */
61 LT_IF, /* an unknown #if */
62 LT_TRUE, /* a true #if */
63 LT_FALSE, /* a false #if */
64 LT_ELIF, /* an unknown #elif */
65 LT_ELTRUE, /* a true #elif */
66 LT_ELFALSE, /* a false #elif */
68 LT_ENDIF, /* #endif */
69 LT_DODGY, /* flag: directive is not on one line */
70 LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
71 LT_PLAIN, /* ordinary line */
72 LT_EOF, /* end of file */
73 LT_ERROR, /* unevaluable #if */
77 static char const * const linetype_name[] = {
78 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
79 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
80 "DODGY TRUEI", "DODGY FALSEI",
81 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
82 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
83 "DODGY ELSE", "DODGY ENDIF",
84 "PLAIN", "EOF", "ERROR"
87 #define linetype_if2elif(lt) ((Linetype)(lt - LT_IF + LT_ELIF))
88 #define linetype_2dodgy(lt) ((Linetype)(lt + LT_DODGY))
90 /* state of #if processing */
93 IS_FALSE_PREFIX, /* false #if followed by false #elifs */
94 IS_TRUE_PREFIX, /* first non-false #(el)if is true */
95 IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
96 IS_FALSE_MIDDLE, /* a false #elif after a pass state */
97 IS_TRUE_MIDDLE, /* a true #elif after a pass state */
98 IS_PASS_ELSE, /* an else after a pass state */
99 IS_FALSE_ELSE, /* an else after a true state */
100 IS_TRUE_ELSE, /* an else after only false states */
101 IS_FALSE_TRAILER, /* #elifs after a true are false */
105 static char const * const ifstate_name[] = {
106 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
107 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
108 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
112 /* state of comment parser */
114 NO_COMMENT = false, /* outside a comment */
115 C_COMMENT, /* in a comment like this one */
116 CXX_COMMENT, /* between // and end of line */
117 STARTING_COMMENT, /* just after slash-backslash-newline */
118 FINISHING_COMMENT, /* star-backslash-newline in a C comment */
119 CHAR_LITERAL, /* inside '' */
120 STRING_LITERAL /* inside "" */
123 static char const * const comment_name[] = {
124 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
127 /* state of preprocessor line parser */
129 LS_START, /* only space and comments on this line */
130 LS_HASH, /* only space, comments, and a hash */
131 LS_DIRTY /* this line can't be a preprocessor line */
134 static char const * const linestate_name[] = {
135 "START", "HASH", "DIRTY"
139 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
141 #define MAXDEPTH 64 /* maximum #if nesting */
142 #define MAXLINE 4096 /* maximum length of line */
143 #define MAXSYMS 16384 /* maximum number of symbols */
146 * Sometimes when editing a keyword the replacement text is longer, so
147 * we leave some space at the end of the tline buffer to accommodate this.
155 static bool compblank; /* -B: compress blank lines */
156 static bool lnblank; /* -b: blank deleted lines */
157 static bool complement; /* -c: do the complement */
158 static bool debugging; /* -d: debugging reports */
159 static bool inplace; /* -m: modify in place */
160 static bool iocccok; /* -e: fewer IOCCC errors */
161 static bool strictlogic; /* -K: keep ambiguous #ifs */
162 static bool killconsts; /* -k: eval constant #ifs */
163 static bool lnnum; /* -n: add #line directives */
164 static bool symlist; /* -s: output symbol list */
165 static bool symdepth; /* -S: output symbol depth */
166 static bool text; /* -t: this is a text file */
168 static const char *symname[MAXSYMS]; /* symbol name */
169 static const char *value[MAXSYMS]; /* -Dsym=value */
170 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
171 static int nsyms; /* number of symbols */
173 static FILE *input; /* input file pointer */
174 static const char *filename; /* input file name */
175 static int linenum; /* current line number */
176 static const char *linefile; /* file name for #line */
177 static FILE *output; /* output file pointer */
178 static const char *ofilename; /* output file name */
179 static const char *backext; /* backup extension */
180 static char *tempname; /* avoid splatting input */
182 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
183 static char *keyword; /* used for editing #elif's */
186 * When processing a file, the output's newline style will match the
187 * input's, and unifdef correctly handles CRLF or LF endings whatever
188 * the platform's native style. The stdio streams are opened in binary
189 * mode to accommodate platforms whose native newline style is CRLF.
190 * When the output isn't a processed input file (when it is error /
191 * debug / diagnostic messages) then unifdef uses native line endings.
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; /* to format symdepth output */
209 static bool firstsym; /* ditto */
211 static int exitmode; /* exit status mode */
212 static int exitstat; /* program exit status */
213 static bool altered; /* was this file modified? */
215 static void addsym1(bool, bool, char *);
216 static void addsym2(bool, const char *, const char *);
217 static char *astrcat(const char *, const char *);
218 static void cleantemp(void);
219 static void closeio(void);
220 static void debug(const char *, ...);
221 static void debugsym(const char *, int);
222 static bool defundef(void);
223 static void defundefile(const char *);
224 static void done(void);
225 static void error(const char *);
226 static int findsym(const char **);
227 static void flushline(bool);
228 static void hashline(void);
229 static void help(void);
230 static Linetype ifeval(const char **);
231 static void ignoreoff(void);
232 static void ignoreon(void);
233 static void indirectsym(void);
234 static void keywordedit(const char *);
235 static const char *matchsym(const char *, const char *);
236 static void nest(void);
237 static Linetype parseline(void);
238 static void process(void);
239 static void processinout(const char *, const char *);
240 static const char *skipargs(const char *);
241 static const char *skipcomment(const char *);
242 static const char *skiphash(void);
243 static const char *skipline(const char *);
244 static const char *skipsym(const char *);
245 static void state(Ifstate);
246 static void unnest(void);
247 static void usage(void);
248 static void version(void);
249 static const char *xstrdup(const char *, const char *);
251 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
257 main(int argc, char *argv[])
261 while ((opt = getopt(argc, argv, "i:D:U:f:I:M:o:x:bBcdehKklmnsStV")) != -1)
263 case 'i': /* treat stuff controlled by these symbols as text */
265 * For strict backwards-compatibility the U or D
266 * should be immediately after the -i but it doesn't
267 * matter much if we relax that requirement.
271 addsym1(true, true, optarg);
273 addsym1(true, false, optarg);
277 case 'D': /* define a symbol */
278 addsym1(false, true, optarg);
280 case 'U': /* undef a symbol */
281 addsym1(false, false, optarg);
283 case 'I': /* no-op for compatibility with cpp */
285 case 'b': /* blank deleted lines instead of omitting them */
286 case 'l': /* backwards compatibility */
289 case 'B': /* compress blank lines around removed section */
292 case 'c': /* treat -D as -U and vice versa */
298 case 'e': /* fewer errors from dodgy lines */
301 case 'f': /* definitions file */
307 case 'K': /* keep ambiguous #ifs */
310 case 'k': /* process constant #ifs */
313 case 'm': /* modify in place */
316 case 'M': /* modify in place and keep backup */
318 if (strlen(optarg) > 0)
321 case 'n': /* add #line directive after deleted lines */
324 case 'o': /* output to a file */
327 case 's': /* only output list of symbols that control #ifs */
330 case 'S': /* list symbols with their nesting depth */
331 symlist = symdepth = true;
333 case 't': /* don't parse C comments */
340 exitmode = atoi(optarg);
341 if(exitmode < 0 || exitmode > 2)
349 if (compblank && lnblank)
350 errx(2, "-B and -b are mutually exclusive");
351 if (symlist && (ofilename != NULL || inplace || argc > 1))
352 errx(2, "-s only works with one input file");
353 if (argc > 1 && ofilename != NULL)
354 errx(2, "-o cannot be used with multiple input files");
355 if (argc > 1 && !inplace)
356 errx(2, "multiple input files require -m or -M");
357 if (argc == 0 && inplace)
358 errx(2, "-m requires an input file");
361 if (argc == 1 && !inplace && ofilename == NULL)
366 if (ofilename != NULL)
367 processinout(*argv, ofilename);
368 else while (argc-- > 0) {
369 processinout(*argv, *argv);
373 case(0): exit(exitstat);
374 case(1): exit(!exitstat);
376 default: abort(); /* bug */
384 processinout(const char *ifn, const char *ofn)
388 if (ifn == NULL || strcmp(ifn, "-") == 0) {
389 filename = "[stdin]";
391 input = fbinmode(stdin);
395 input = fopen(ifn, "rb");
397 err(2, "can't open %s", ifn);
399 if (strcmp(ofn, "-") == 0) {
400 output = fbinmode(stdout);
404 if (stat(ofn, &st) < 0) {
405 output = fopen(ofn, "wb");
407 err(2, "can't create %s", ofn);
412 tempname = astrcat(ofn, ".XXXXXX");
413 output = mktempmode(tempname, st.st_mode);
415 err(2, "can't create %s", tempname);
419 if (backext != NULL) {
420 char *backname = astrcat(ofn, backext);
421 if (rename(ofn, backname) < 0)
422 err(2, "can't rename \"%s\" to \"%s\"", ofn, backname);
425 /* leave file unmodified if unifdef made no changes */
426 if (!altered && backext == NULL) {
427 if (remove(tempname) < 0)
428 warn("can't remove \"%s\"", tempname);
429 } else if (replace(tempname, ofn) < 0)
430 err(2, "can't rename \"%s\" to \"%s\"", tempname, ofn);
436 * For cleaning up if there is an error.
441 if (tempname != NULL)
446 * Self-identification functions.
452 const char *c = copyright;
467 "usage: unifdef [-bBcdehKkmnsStV] [-x{012}] [-Mext] [-opath] \\\n"
468 " [-[i]Dsym[=val]] [-[i]Usym] [-fpath] ... [file] ...\n");
483 " -Dsym=val define preprocessor symbol with given value\n"
484 " -Dsym define preprocessor symbol with value 1\n"
485 " -Usym preprocessor symbol is undefined\n"
486 " -iDsym=val \\ ignore C strings and comments\n"
487 " -iDsym ) in sections controlled by these\n"
488 " -iUsym / preprocessor symbols\n"
489 " -fpath file containing #define and #undef directives\n"
490 " -b blank lines instead of deleting them\n"
491 " -B compress blank lines around deleted section\n"
492 " -c complement (invert) keep vs. delete\n"
493 " -d debugging mode\n"
494 " -e ignore multiline preprocessor directives\n"
496 " -Ipath extra include file path (ignored)\n"
497 " -K disable && and || short-circuiting\n"
498 " -k process constant #if expressions\n"
499 " -Mext modify in place and keep backups\n"
500 " -m modify input files in place\n"
501 " -n add #line directives to output\n"
502 " -opath output file name\n"
503 " -S list #if control symbols with nesting\n"
504 " -s list #if control symbols\n"
505 " -t ignore C strings and comments\n"
506 " -V print version\n"
507 " -x{012} exit status mode\n"
513 * A state transition function alters the global #if processing state
514 * in a particular way. The table below is indexed by the current
515 * processing state and the type of the current line.
517 * Nesting is handled by keeping a stack of states; some transition
518 * functions increase or decrease the depth. They also maintain the
519 * ignore state on a stack. In some complicated cases they have to
520 * alter the preprocessor directive, as follows.
522 * When we have processed a group that starts off with a known-false
523 * #if/#elif sequence (which has therefore been deleted) followed by a
524 * #elif that we don't understand and therefore must keep, we edit the
525 * latter into a #if to keep the nesting correct. We use memcpy() to
526 * overwrite the 4 byte token "elif" with "if " without a '\0' byte.
528 * When we find a true #elif in a group, the following block will
529 * always be kept and the rest of the sequence after the next #elif or
530 * #else will be discarded. We edit the #elif into a #else and the
531 * following directive to #endif since this has the desired behaviour.
533 * "Dodgy" directives are split across multiple lines, the most common
534 * example being a multi-line comment hanging off the right of the
535 * directive. We can handle them correctly only if there is no change
536 * from printing to dropping (or vice versa) caused by that directive.
537 * If the directive is the first of a group we have a choice between
538 * failing with an error, or passing it through unchanged instead of
539 * evaluating it. The latter is not the default to avoid questions from
540 * users about unifdef unexpectedly leaving behind preprocessor directives.
542 typedef void state_fn(void);
544 /* report an error */
545 static void Eelif (void) { error("Inappropriate #elif"); }
546 static void Eelse (void) { error("Inappropriate #else"); }
547 static void Eendif(void) { error("Inappropriate #endif"); }
548 static void Eeof (void) { error("Premature EOF"); }
549 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
550 /* plain line handling */
551 static void print (void) { flushline(true); }
552 static void drop (void) { flushline(false); }
553 /* output lacks group's start line */
554 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
555 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
556 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
557 /* print/pass this block */
558 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
559 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
560 static void Pendif(void) { print(); unnest(); }
561 /* discard this block */
562 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
563 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
564 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
565 static void Dendif(void) { drop(); unnest(); }
566 /* first line of group */
567 static void Fdrop (void) { nest(); Dfalse(); }
568 static void Fpass (void) { nest(); Pelif(); }
569 static void Ftrue (void) { nest(); Strue(); }
570 static void Ffalse(void) { nest(); Sfalse(); }
571 /* variable pedantry for obfuscated lines */
572 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
573 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
574 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
575 /* ignore comments in this block */
576 static void Idrop (void) { Fdrop(); ignoreon(); }
577 static void Itrue (void) { Ftrue(); ignoreon(); }
578 static void Ifalse(void) { Ffalse(); ignoreon(); }
579 /* modify this line */
580 static void Mpass (void) { memcpy(keyword, "if ", 4); Pelif(); }
581 static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); }
582 static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
583 static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
585 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
587 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
588 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
589 print, done, abort },
590 /* IS_FALSE_PREFIX */
591 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
592 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
595 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
596 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
597 print, Eeof, abort },
599 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
600 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
601 print, Eeof, abort },
602 /* IS_FALSE_MIDDLE */
603 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
604 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
607 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
608 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
609 print, Eeof, abort },
611 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
612 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
613 print, Eeof, abort },
615 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
616 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
619 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
620 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
621 print, Eeof, abort },
622 /* IS_FALSE_TRAILER */
623 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
624 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
626 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
627 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
632 * State machine utility functions
639 ignoring[depth] = ignoring[depth-1];
644 ignoring[depth] = true;
647 keywordedit(const char *replacement)
649 snprintf(keyword, tline + sizeof(tline) - keyword,
650 "%s%s", replacement, newline);
657 if (depth > MAXDEPTH-1)
659 if (depth == MAXDEPTH-1)
660 error("Too many levels of nesting");
662 stifline[depth] = linenum;
678 * The last state transition function. When this is called,
679 * lineval == LT_EOF, so the process() loop will terminate.
685 error("EOF in comment");
690 * Write a line to the output or not, according to command line options.
691 * If writing fails, closeio() will print the error and exit.
698 if (keep ^ complement) {
699 bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
700 if (blankline && compblank && blankcount != blankmax) {
704 if (lnnum && delcount > 0)
706 if (fputs(tline, output) == EOF)
709 blankmax = blankcount = blankline ? blankcount + 1 : 0;
712 if (lnblank && fputs(newline, output) == EOF)
718 if (debugging && fflush(output) == EOF)
723 * Format of #line directives depends on whether we know the input filename.
730 if (linefile == NULL)
731 e = fprintf(output, "#line %d%s", linenum, newline);
733 e = fprintf(output, "#line %d \"%s\"%s",
734 linenum, linefile, newline);
740 * Flush the output and handle errors.
745 /* Tidy up after findsym(). */
746 if (symdepth && !zerosyms)
748 if (output != NULL && (ferror(output) || fclose(output) == EOF))
749 err(2, "%s: can't write to output", filename);
754 * The driver for the state machine.
759 Linetype lineval = LT_PLAIN;
760 /* When compressing blank lines, act as if the file
761 is preceded by a large number of blank lines. */
762 blankmax = blankcount = 1000;
767 while (lineval != LT_EOF) {
768 lineval = parseline();
769 trans_table[ifstate[depth]][lineval]();
770 debug("process line %d %s -> %s depth %d",
771 linenum, linetype_name[lineval],
772 ifstate_name[ifstate[depth]], depth);
778 * Parse a line and determine its type. We keep the preprocessor line
779 * parser state between calls in the global variable linestate, with
780 * help from skipcomment().
788 Comment_state wascomment;
790 wascomment = incomment;
794 if (newline == NULL) {
795 if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
796 newline = newline_crlf;
798 newline = newline_unix;
804 keyword = tline + (cp - tline);
805 if ((cp = matchsym("ifdef", keyword)) != NULL ||
806 (cp = matchsym("ifndef", keyword)) != NULL) {
807 cp = skipcomment(cp);
808 if ((cursym = findsym(&cp)) < 0)
811 retval = (keyword[2] == 'n')
812 ? LT_FALSE : LT_TRUE;
813 if (value[cursym] == NULL)
814 retval = (retval == LT_TRUE)
815 ? LT_FALSE : LT_TRUE;
817 retval = (retval == LT_TRUE)
818 ? LT_TRUEI : LT_FALSEI;
820 } else if ((cp = matchsym("if", keyword)) != NULL)
821 retval = ifeval(&cp);
822 else if ((cp = matchsym("elif", keyword)) != NULL)
823 retval = linetype_if2elif(ifeval(&cp));
824 else if ((cp = matchsym("else", keyword)) != NULL)
826 else if ((cp = matchsym("endif", keyword)) != NULL)
829 cp = skipsym(keyword);
830 /* no way can we deal with a continuation inside a keyword */
831 if (strncmp(cp, "\\\r\n", 3) == 0 ||
832 strncmp(cp, "\\\n", 2) == 0)
838 cp = skipcomment(cp);
841 if (retval == LT_TRUE || retval == LT_FALSE ||
842 retval == LT_TRUEI || retval == LT_FALSEI)
844 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
847 /* the following can happen if the last line of the file lacks a
848 newline or if there is too much whitespace in a directive */
849 if (linestate == LS_HASH) {
850 long len = cp - tline;
851 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
853 err(2, "can't read %s", filename);
854 /* append the missing newline at eof */
855 strcpy(tline + len, newline);
856 cp += strlen(newline);
857 linestate = LS_START;
859 linestate = LS_DIRTY;
862 if (retval != LT_PLAIN && (wascomment || linestate != LS_START)) {
863 retval = linetype_2dodgy(retval);
864 linestate = LS_DIRTY;
867 debug("parser line %d state %s comment %s line", linenum,
868 comment_name[incomment], linestate_name[linestate]);
873 * These are the binary operators that are supported by the expression
876 static Linetype op_strict(long *p, long v, Linetype at, Linetype bt) {
877 if(at == LT_IF || bt == LT_IF) return (LT_IF);
878 return (*p = v, v ? LT_TRUE : LT_FALSE);
880 static Linetype op_lt(long *p, Linetype at, long a, Linetype bt, long b) {
881 return op_strict(p, a < b, at, bt);
883 static Linetype op_gt(long *p, Linetype at, long a, Linetype bt, long b) {
884 return op_strict(p, a > b, at, bt);
886 static Linetype op_le(long *p, Linetype at, long a, Linetype bt, long b) {
887 return op_strict(p, a <= b, at, bt);
889 static Linetype op_ge(long *p, Linetype at, long a, Linetype bt, long b) {
890 return op_strict(p, a >= b, at, bt);
892 static Linetype op_eq(long *p, Linetype at, long a, Linetype bt, long b) {
893 return op_strict(p, a == b, at, bt);
895 static Linetype op_ne(long *p, Linetype at, long a, Linetype bt, long b) {
896 return op_strict(p, a != b, at, bt);
898 static Linetype op_or(long *p, Linetype at, long a, Linetype bt, long b) {
899 if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
900 return (*p = 1, LT_TRUE);
901 return op_strict(p, a || b, at, bt);
903 static Linetype op_and(long *p, Linetype at, long a, Linetype bt, long b) {
904 if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
905 return (*p = 0, LT_FALSE);
906 return op_strict(p, a && b, at, bt);
908 static Linetype op_blsh(long *p, Linetype at, long a, Linetype bt, long b) {
909 return op_strict(p, a << b, at, bt);
911 static Linetype op_brsh(long *p, Linetype at, long a, Linetype bt, long b) {
912 return op_strict(p, a >> b, at, bt);
914 static Linetype op_add(long *p, Linetype at, long a, Linetype bt, long b) {
915 return op_strict(p, a + b, at, bt);
917 static Linetype op_sub(long *p, Linetype at, long a, Linetype bt, long b) {
918 return op_strict(p, a - b, at, bt);
920 static Linetype op_mul(long *p, Linetype at, long a, Linetype bt, long b) {
921 return op_strict(p, a * b, at, bt);
923 static Linetype op_div(long *p, Linetype at, long a, Linetype bt, long b) {
925 debug("eval division by zero");
928 return op_strict(p, a / b, at, bt);
930 static Linetype op_mod(long *p, Linetype at, long a, Linetype bt, long b) {
931 return op_strict(p, a % b, at, bt);
933 static Linetype op_bor(long *p, Linetype at, long a, Linetype bt, long b) {
934 return op_strict(p, a | b, at, bt);
936 static Linetype op_bxor(long *p, Linetype at, long a, Linetype bt, long b) {
937 return op_strict(p, a ^ b, at, bt);
939 static Linetype op_band(long *p, Linetype at, long a, Linetype bt, long b) {
940 return op_strict(p, a & b, at, bt);
944 * An evaluation function takes three arguments, as follows: (1) a pointer to
945 * an element of the precedence table which lists the operators at the current
946 * level of precedence; (2) a pointer to an integer which will receive the
947 * value of the expression; and (3) a pointer to a char* that points to the
948 * expression to be evaluated and that is updated to the end of the expression
949 * when evaluation is complete. The function returns LT_FALSE if the value of
950 * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
951 * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
955 typedef Linetype eval_fn(const struct ops *, long *, const char **);
957 static eval_fn eval_table, eval_unary;
960 * The precedence table. Expressions involving binary operators are evaluated
961 * in a table-driven way by eval_table. When it evaluates a subexpression it
962 * calls the inner function with its first argument pointing to the next
963 * element of the table. Innermost expressions have special non-table-driven
966 * The stop characters help with lexical analysis: an operator is not
967 * recognized if it is followed by one of the stop characters because
968 * that would make it a different operator.
972 Linetype (*fn)(long *, Linetype, long, Linetype, long);
979 static const struct ops eval_ops[] = {
980 { eval_table, { { "||", op_or, NULL } } },
981 { eval_table, { { "&&", op_and, NULL } } },
982 { eval_table, { { "|", op_bor, "|" } } },
983 { eval_table, { { "^", op_bxor, NULL } } },
984 { eval_table, { { "&", op_band, "&" } } },
985 { eval_table, { { "==", op_eq, NULL },
986 { "!=", op_ne, NULL } } },
987 { eval_table, { { "<=", op_le, NULL },
988 { ">=", op_ge, NULL },
989 { "<", op_lt, "<=" },
990 { ">", op_gt, ">=" } } },
991 { eval_table, { { "<<", op_blsh, NULL },
992 { ">>", op_brsh, NULL } } },
993 { eval_table, { { "+", op_add, NULL },
994 { "-", op_sub, NULL } } },
995 { eval_unary, { { "*", op_mul, NULL },
996 { "/", op_div, NULL },
997 { "%", op_mod, NULL } } },
1000 /* Current operator precedence level */
1001 static long prec(const struct ops *ops)
1003 return (ops - eval_ops);
1007 * Function for evaluating the innermost parts of expressions,
1008 * viz. !expr (expr) number defined(symbol) symbol
1009 * We reset the constexpr flag in the last two cases.
1012 eval_unary(const struct ops *ops, long *valp, const char **cpp)
1020 cp = skipcomment(*cpp);
1022 debug("eval%d !", prec(ops));
1024 lt = eval_unary(ops, valp, &cp);
1029 lt = *valp ? LT_TRUE : LT_FALSE;
1031 } else if (*cp == '~') {
1032 debug("eval%d ~", prec(ops));
1034 lt = eval_unary(ops, valp, &cp);
1039 lt = *valp ? LT_TRUE : LT_FALSE;
1041 } else if (*cp == '-') {
1042 debug("eval%d -", prec(ops));
1044 lt = eval_unary(ops, valp, &cp);
1049 lt = *valp ? LT_TRUE : LT_FALSE;
1051 } else if (*cp == '(') {
1053 debug("eval%d (", prec(ops));
1054 lt = eval_table(eval_ops, valp, &cp);
1057 cp = skipcomment(cp);
1060 } else if (isdigit((unsigned char)*cp)) {
1061 debug("eval%d number", prec(ops));
1062 *valp = strtol(cp, &ep, 0);
1065 lt = *valp ? LT_TRUE : LT_FALSE;
1067 } else if (matchsym("defined", cp) != NULL) {
1068 cp = skipcomment(cp+7);
1070 cp = skipcomment(cp+1);
1076 cp = skipcomment(cp);
1077 if (defparen && *cp++ != ')') {
1078 debug("eval%d defined missing ')'", prec(ops));
1082 debug("eval%d defined unknown", prec(ops));
1085 debug("eval%d defined %s", prec(ops), symname[sym]);
1086 *valp = (value[sym] != NULL);
1087 lt = *valp ? LT_TRUE : LT_FALSE;
1090 } else if (!endsym(*cp)) {
1091 debug("eval%d symbol", prec(ops));
1096 } else if (value[sym] == NULL) {
1100 *valp = strtol(value[sym], &ep, 0);
1101 if (*ep != '\0' || ep == value[sym])
1103 lt = *valp ? LT_TRUE : LT_FALSE;
1108 debug("eval%d bad expr", prec(ops));
1113 debug("eval%d = %d", prec(ops), *valp);
1118 * Table-driven evaluation of binary operators.
1121 eval_table(const struct ops *ops, long *valp, const char **cpp)
1123 const struct op *op;
1128 debug("eval%d", prec(ops));
1130 lt = ops->inner(ops+1, valp, &cp);
1134 cp = skipcomment(cp);
1135 for (op = ops->op; op->str != NULL; op++) {
1136 if (strncmp(cp, op->str, strlen(op->str)) == 0) {
1137 /* assume only one-char operators have stop chars */
1138 if (op->stop != NULL && cp[1] != '\0' &&
1139 strchr(op->stop, cp[1]) != NULL)
1145 if (op->str == NULL)
1147 cp += strlen(op->str);
1148 debug("eval%d %s", prec(ops), op->str);
1149 rt = ops->inner(ops+1, &val, &cp);
1152 lt = op->fn(valp, lt, *valp, rt, val);
1156 debug("eval%d = %d", prec(ops), *valp);
1157 debug("eval%d lt = %s", prec(ops), linetype_name[lt]);
1162 * Evaluate the expression on a #if or #elif line. If we can work out
1163 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
1164 * return just a generic LT_IF.
1167 ifeval(const char **cpp)
1172 debug("eval %s", *cpp);
1173 constexpr = killconsts ? false : true;
1174 ret = eval_table(eval_ops, &val, cpp);
1175 debug("eval = %d", val);
1176 return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
1180 * Read a line and examine its initial part to determine if it is a
1181 * preprocessor directive. Returns NULL on EOF, or a pointer to a
1182 * preprocessor directive name, or a pointer to the zero byte at the
1191 if (fgets(tline, MAXLINE, input) == NULL) {
1193 err(2, "can't read %s", filename);
1197 cp = skipcomment(tline);
1198 if (linestate == LS_START && *cp == '#') {
1199 linestate = LS_HASH;
1200 return (skipcomment(cp + 1));
1201 } else if (*cp == '\0') {
1204 return (skipline(cp));
1209 * Mark a line dirty and consume the rest of it, keeping track of the
1213 skipline(const char *cp)
1217 linestate = LS_DIRTY;
1218 while (*cp != '\0') {
1219 cp = skipcomment(pcp = cp);
1227 * Skip over comments, strings, and character literals and stop at the
1228 * next character position that is not whitespace. Between calls we keep
1229 * the comment state in the global variable incomment, and we also adjust
1230 * the global variable linestate when we see a newline.
1231 * XXX: doesn't cope with the buffer splitting inside a state transition.
1234 skipcomment(const char *cp)
1236 if (text || ignoring[depth]) {
1237 for (; isspace((unsigned char)*cp); cp++)
1239 linestate = LS_START;
1243 /* don't reset to LS_START after a line continuation */
1244 if (strncmp(cp, "\\\r\n", 3) == 0)
1246 else if (strncmp(cp, "\\\n", 2) == 0)
1248 else switch (incomment) {
1250 if (strncmp(cp, "/\\\r\n", 4) == 0) {
1251 incomment = STARTING_COMMENT;
1253 } else if (strncmp(cp, "/\\\n", 3) == 0) {
1254 incomment = STARTING_COMMENT;
1256 } else if (strncmp(cp, "/*", 2) == 0) {
1257 incomment = C_COMMENT;
1259 } else if (strncmp(cp, "//", 2) == 0) {
1260 incomment = CXX_COMMENT;
1262 } else if (strncmp(cp, "\'", 1) == 0) {
1263 incomment = CHAR_LITERAL;
1264 linestate = LS_DIRTY;
1266 } else if (strncmp(cp, "\"", 1) == 0) {
1267 incomment = STRING_LITERAL;
1268 linestate = LS_DIRTY;
1270 } else if (strncmp(cp, "\n", 1) == 0) {
1271 linestate = LS_START;
1273 } else if (strchr(" \r\t", *cp) != NULL) {
1279 if (strncmp(cp, "\n", 1) == 0) {
1280 incomment = NO_COMMENT;
1281 linestate = LS_START;
1286 case STRING_LITERAL:
1287 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
1288 (incomment == STRING_LITERAL && cp[0] == '\"')) {
1289 incomment = NO_COMMENT;
1291 } else if (cp[0] == '\\') {
1296 } else if (strncmp(cp, "\n", 1) == 0) {
1297 if (incomment == CHAR_LITERAL)
1298 error("Unterminated char literal");
1300 error("Unterminated string literal");
1305 if (strncmp(cp, "*\\\r\n", 4) == 0) {
1306 incomment = FINISHING_COMMENT;
1308 } else if (strncmp(cp, "*\\\n", 3) == 0) {
1309 incomment = FINISHING_COMMENT;
1311 } else if (strncmp(cp, "*/", 2) == 0) {
1312 incomment = NO_COMMENT;
1317 case STARTING_COMMENT:
1319 incomment = C_COMMENT;
1321 } else if (*cp == '/') {
1322 incomment = CXX_COMMENT;
1325 incomment = NO_COMMENT;
1326 linestate = LS_DIRTY;
1329 case FINISHING_COMMENT:
1331 incomment = NO_COMMENT;
1334 incomment = C_COMMENT;
1343 * Skip macro arguments.
1346 skipargs(const char *cp)
1348 const char *ocp = cp;
1350 cp = skipcomment(cp);
1358 cp = skipcomment(cp+1);
1359 } while (level != 0 && *cp != '\0');
1363 /* Rewind and re-detect the syntax error later. */
1368 * Skip over an identifier.
1371 skipsym(const char *cp)
1373 while (!endsym(*cp))
1379 * Skip whitespace and take a copy of any following identifier.
1382 getsym(const char **cpp)
1384 const char *cp = *cpp, *sym;
1386 cp = skipcomment(cp);
1387 cp = skipsym(sym = cp);
1391 return (xstrdup(sym, cp));
1395 * Check that s (a symbol) matches the start of t, and that the
1396 * following character in t is not a symbol character. Returns a
1397 * pointer to the following character in t if there is a match,
1401 matchsym(const char *s, const char *t)
1403 while (*s != '\0' && *t != '\0')
1408 if (*s == '\0' && endsym(*t))
1415 * Look for the symbol in the symbol table. If it is found, we return
1416 * the symbol table index, else we return -1.
1419 findsym(const char **strp)
1425 *strp = skipsym(str);
1429 if (symdepth && firstsym)
1430 printf("%s%3d", zerosyms ? "" : "\n", depth);
1431 firstsym = zerosyms = false;
1433 symdepth ? " " : "",
1434 (int)(*strp-str), str,
1435 symdepth ? "" : "\n");
1436 /* we don't care about the value of the symbol */
1439 for (symind = 0; symind < nsyms; ++symind) {
1440 if (matchsym(symname[symind], str) != NULL) {
1441 debugsym("findsym", symind);
1449 * Resolve indirect symbol values to their final definitions.
1455 int changed, sym, ind;
1459 for (sym = 0; sym < nsyms; ++sym) {
1460 if (value[sym] == NULL)
1464 if (ind == -1 || ind == sym ||
1466 value[ind] == NULL ||
1467 value[ind] == value[sym])
1469 debugsym("indir...", sym);
1470 value[sym] = value[ind];
1471 debugsym("...ectsym", sym);
1478 * Add a symbol to the symbol table, specified with the format sym=val
1481 addsym1(bool ignorethis, bool definethis, char *symval)
1483 const char *sym, *val;
1487 if (definethis && *val == '=') {
1488 symval[val - sym] = '\0';
1490 } else if (*val == '\0') {
1491 val = definethis ? "1" : NULL;
1495 addsym2(ignorethis, sym, val);
1499 * Add a symbol to the symbol table.
1502 addsym2(bool ignorethis, const char *sym, const char *val)
1504 const char *cp = sym;
1507 symind = findsym(&cp);
1509 if (nsyms >= MAXSYMS)
1510 errx(2, "too many symbols");
1513 ignore[symind] = ignorethis;
1514 symname[symind] = sym;
1515 value[symind] = val;
1516 debugsym("addsym", symind);
1520 debugsym(const char *why, int symind)
1522 debug("%s %s%c%s", why, symname[symind],
1523 value[symind] ? '=' : ' ',
1524 value[symind] ? value[symind] : "undef");
1528 * Add symbols to the symbol table from a file containing
1529 * #define and #undef preprocessor directives.
1532 defundefile(const char *fn)
1535 input = fopen(fn, "rb");
1537 err(2, "can't open %s", fn);
1542 err(2, "can't read %s", filename);
1546 error("EOF in comment");
1550 * Read and process one #define or #undef directive
1555 const char *cp, *kw, *sym, *val, *end;
1562 /* strip trailing whitespace, and do a fairly rough check to
1563 avoid unsupported multi-line preprocessor directives */
1564 end = cp + strlen(cp);
1565 while (end > tline && strchr(" \t\n\r", end[-1]) != NULL)
1567 if (end > tline && end[-1] == '\\')
1571 if ((cp = matchsym("define", kw)) != NULL) {
1574 error("Missing macro name in #define");
1578 cp = skipcomment(cp);
1579 val = (cp < end) ? xstrdup(cp, end) : "";
1582 addsym2(false, sym, val);
1583 } else if ((cp = matchsym("undef", kw)) != NULL) {
1586 error("Missing macro name in #undef");
1587 cp = skipcomment(cp);
1589 addsym2(false, sym, NULL);
1591 error("Unrecognized preprocessor directive");
1595 debug("parser line %d state %s comment %s line", linenum,
1596 comment_name[incomment], linestate_name[linestate]);
1601 * Concatenate two strings into new memory, checking for failure.
1604 astrcat(const char *s1, const char *s2)
1610 len = snprintf(NULL, 0, "%s%s", s1, s2);
1613 size = (size_t)len + 1;
1614 s = (char *)malloc(size);
1617 snprintf(s, size, "%s%s", s1, s2);
1622 * Duplicate a segment of a string, checking for failure.
1625 xstrdup(const char *start, const char *end)
1630 if (end < start) abort(); /* bug */
1631 n = (size_t)(end - start) + 1;
1635 snprintf(s, n, "%s", start);
1643 debug(const char *msg, ...)
1655 error(const char *msg)
1658 warnx("%s: %d: %s", filename, linenum, msg);
1660 warnx("%s: %d: %s (#if line %d depth %d)",
1661 filename, linenum, msg, stifline[depth], depth);
1663 errx(2, "Output may be truncated");