2 * Copyright (c) 2002 - 2009 Tony Finch <dot@dotat.at>
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * This code was derived from software contributed to Berkeley by Dave Yost.
28 * It was rewritten to support ANSI C by Tony Finch. The original version
29 * of unifdef carried the 4-clause BSD copyright licence. None of its code
30 * remains in this version (though some of the names remain) so it now
31 * carries a more liberal licence.
33 * The latest version is available from http://dotat.at/prog/unifdef
36 static const char * const copyright
[] = {
37 "@(#) Copyright (c) 2002 - 2009 Tony Finch <dot@dotat.at>\n",
38 "$dotat: unifdef/unifdef.c,v 1.190 2009/11/27 17:21:26 fanf2 Exp $",
42 * unifdef - remove ifdef'ed lines
45 * provide an option which will append the name of the
46 * appropriate symbol after #else's and #endif's
47 * provide an option which will check symbols after
48 * #else's and #endif's to see that they match their
49 * corresponding #ifdef or #ifndef
51 * The first two items above require better buffer handling, which would
52 * also make it possible to handle all "dodgy" directives correctly.
64 /* types of input lines: */
66 LT_TRUEI
, /* a true #if with ignore flag */
67 LT_FALSEI
, /* a false #if with ignore flag */
68 LT_IF
, /* an unknown #if */
69 LT_TRUE
, /* a true #if */
70 LT_FALSE
, /* a false #if */
71 LT_ELIF
, /* an unknown #elif */
72 LT_ELTRUE
, /* a true #elif */
73 LT_ELFALSE
, /* a false #elif */
75 LT_ENDIF
, /* #endif */
76 LT_DODGY
, /* flag: directive is not on one line */
77 LT_DODGY_LAST
= LT_DODGY
+ LT_ENDIF
,
78 LT_PLAIN
, /* ordinary line */
79 LT_EOF
, /* end of file */
80 LT_ERROR
, /* unevaluable #if */
84 static char const * const linetype_name
[] = {
85 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
86 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
87 "DODGY TRUEI", "DODGY FALSEI",
88 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
89 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
90 "DODGY ELSE", "DODGY ENDIF",
91 "PLAIN", "EOF", "ERROR"
94 /* state of #if processing */
97 IS_FALSE_PREFIX
, /* false #if followed by false #elifs */
98 IS_TRUE_PREFIX
, /* first non-false #(el)if is true */
99 IS_PASS_MIDDLE
, /* first non-false #(el)if is unknown */
100 IS_FALSE_MIDDLE
, /* a false #elif after a pass state */
101 IS_TRUE_MIDDLE
, /* a true #elif after a pass state */
102 IS_PASS_ELSE
, /* an else after a pass state */
103 IS_FALSE_ELSE
, /* an else after a true state */
104 IS_TRUE_ELSE
, /* an else after only false states */
105 IS_FALSE_TRAILER
, /* #elifs after a true are false */
109 static char const * const ifstate_name
[] = {
110 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
111 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
112 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
116 /* state of comment parser */
118 NO_COMMENT
= false, /* outside a comment */
119 C_COMMENT
, /* in a comment like this one */
120 CXX_COMMENT
, /* between // and end of line */
121 STARTING_COMMENT
, /* just after slash-backslash-newline */
122 FINISHING_COMMENT
, /* star-backslash-newline in a C comment */
123 CHAR_LITERAL
, /* inside '' */
124 STRING_LITERAL
/* inside "" */
127 static char const * const comment_name
[] = {
128 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
131 /* state of preprocessor line parser */
133 LS_START
, /* only space and comments on this line */
134 LS_HASH
, /* only space, comments, and a hash */
135 LS_DIRTY
/* this line can't be a preprocessor line */
138 static char const * const linestate_name
[] = {
139 "START", "HASH", "DIRTY"
143 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
145 #define MAXDEPTH 64 /* maximum #if nesting */
146 #define MAXLINE 4096 /* maximum length of line */
147 #define MAXSYMS 4096 /* maximum number of symbols */
150 * Sometimes when editing a keyword the replacement text is longer, so
151 * we leave some space at the end of the tline buffer to accommodate this.
159 static bool compblank
; /* -B: compress blank lines */
160 static bool lnblank
; /* -b: blank deleted lines */
161 static bool complement
; /* -c: do the complement */
162 static bool debugging
; /* -d: debugging reports */
163 static bool iocccok
; /* -e: fewer IOCCC errors */
164 static bool strictlogic
; /* -K: keep ambiguous #ifs */
165 static bool killconsts
; /* -k: eval constant #ifs */
166 static bool lnnum
; /* -n: add #line directives */
167 static bool symlist
; /* -s: output symbol list */
168 static bool text
; /* -t: this is a text file */
170 static const char *symname
[MAXSYMS
]; /* symbol name */
171 static const char *value
[MAXSYMS
]; /* -Dsym=value */
172 static bool ignore
[MAXSYMS
]; /* -iDsym or -iUsym */
173 static int nsyms
; /* number of symbols */
175 static FILE *input
; /* input file pointer */
176 static const char *filename
; /* input file name */
177 static int linenum
; /* current line number */
179 static char tline
[MAXLINE
+EDITSLOP
];/* input buffer plus space */
180 static char *keyword
; /* used for editing #elif's */
182 static Comment_state incomment
; /* comment parser state */
183 static Line_state linestate
; /* #if line parser state */
184 static Ifstate ifstate
[MAXDEPTH
]; /* #if processor state */
185 static bool ignoring
[MAXDEPTH
]; /* ignore comments state */
186 static int stifline
[MAXDEPTH
]; /* start of current #if */
187 static int depth
; /* current #if nesting */
188 static int delcount
; /* count of deleted lines */
189 static unsigned blankcount
; /* count of blank lines */
190 static unsigned blankmax
; /* maximum recent blankcount */
191 static bool constexpr; /* constant #if expression */
193 static int exitstat
; /* program exit status */
195 static void addsym(bool, bool, char *);
196 static void debug(const char *, ...);
197 static void done(void);
198 static void error(const char *);
199 static int findsym(const char *);
200 static void flushline(bool);
201 static Linetype
parseline(void);
202 static Linetype
ifeval(const char **);
203 static void ignoreoff(void);
204 static void ignoreon(void);
205 static void keywordedit(const char *);
206 static void nest(void);
207 static void process(void);
208 static const char *skipargs(const char *);
209 static const char *skipcomment(const char *);
210 static const char *skipsym(const char *);
211 static void state(Ifstate
);
212 static int strlcmp(const char *, const char *, size_t);
213 static void unnest(void);
214 static void usage(void);
216 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
222 main(int argc
, char *argv
[])
226 while ((opt
= getopt(argc
, argv
, "i:D:U:I:BbcdeKklnst")) != -1)
228 case 'i': /* treat stuff controlled by these symbols as text */
230 * For strict backwards-compatibility the U or D
231 * should be immediately after the -i but it doesn't
232 * matter much if we relax that requirement.
236 addsym(true, true, optarg
);
238 addsym(true, false, optarg
);
242 case 'D': /* define a symbol */
243 addsym(false, true, optarg
);
245 case 'U': /* undef a symbol */
246 addsym(false, false, optarg
);
249 /* no-op for compatibility with cpp */
251 case 'B': /* compress blank lines around removed section */
254 case 'b': /* blank deleted lines instead of omitting them */
255 case 'l': /* backwards compatibility */
258 case 'c': /* treat -D as -U and vice versa */
264 case 'e': /* fewer errors from dodgy lines */
267 case 'K': /* keep ambiguous #ifs */
270 case 'k': /* process constant #ifs */
273 case 'n': /* add #line directive after deleted lines */
276 case 's': /* only output list of symbols that control #ifs */
279 case 't': /* don't parse C comments */
287 if (compblank
&& lnblank
)
288 errx(2, "-B and -b are mutually exclusive");
290 errx(2, "can only do one file");
291 } else if (argc
== 1 && strcmp(*argv
, "-") != 0) {
293 input
= fopen(filename
, "r");
295 err(2, "can't open %s", filename
);
297 filename
= "[stdin]";
307 fprintf(stderr
, "usage: unifdef [-BbcdeKknst] [-Ipath]"
308 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
313 * A state transition function alters the global #if processing state
314 * in a particular way. The table below is indexed by the current
315 * processing state and the type of the current line.
317 * Nesting is handled by keeping a stack of states; some transition
318 * functions increase or decrease the depth. They also maintain the
319 * ignore state on a stack. In some complicated cases they have to
320 * alter the preprocessor directive, as follows.
322 * When we have processed a group that starts off with a known-false
323 * #if/#elif sequence (which has therefore been deleted) followed by a
324 * #elif that we don't understand and therefore must keep, we edit the
325 * latter into a #if to keep the nesting correct.
327 * When we find a true #elif in a group, the following block will
328 * always be kept and the rest of the sequence after the next #elif or
329 * #else will be discarded. We edit the #elif into a #else and the
330 * following directive to #endif since this has the desired behaviour.
332 * "Dodgy" directives are split across multiple lines, the most common
333 * example being a multi-line comment hanging off the right of the
334 * directive. We can handle them correctly only if there is no change
335 * from printing to dropping (or vice versa) caused by that directive.
336 * If the directive is the first of a group we have a choice between
337 * failing with an error, or passing it through unchanged instead of
338 * evaluating it. The latter is not the default to avoid questions from
339 * users about unifdef unexpectedly leaving behind preprocessor directives.
341 typedef void state_fn(void);
343 /* report an error */
344 static void Eelif (void) { error("Inappropriate #elif"); }
345 static void Eelse (void) { error("Inappropriate #else"); }
346 static void Eendif(void) { error("Inappropriate #endif"); }
347 static void Eeof (void) { error("Premature EOF"); }
348 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
349 /* plain line handling */
350 static void print (void) { flushline(true); }
351 static void drop (void) { flushline(false); }
352 /* output lacks group's start line */
353 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX
); }
354 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX
); }
355 static void Selse (void) { drop(); state(IS_TRUE_ELSE
); }
356 /* print/pass this block */
357 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE
); }
358 static void Pelse (void) { print(); state(IS_PASS_ELSE
); }
359 static void Pendif(void) { print(); unnest(); }
360 /* discard this block */
361 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER
); }
362 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE
); }
363 static void Delse (void) { drop(); state(IS_FALSE_ELSE
); }
364 static void Dendif(void) { drop(); unnest(); }
365 /* first line of group */
366 static void Fdrop (void) { nest(); Dfalse(); }
367 static void Fpass (void) { nest(); Pelif(); }
368 static void Ftrue (void) { nest(); Strue(); }
369 static void Ffalse(void) { nest(); Sfalse(); }
370 /* variable pedantry for obfuscated lines */
371 static void Oiffy (void) { if (!iocccok
) Eioccc(); Fpass(); ignoreon(); }
372 static void Oif (void) { if (!iocccok
) Eioccc(); Fpass(); }
373 static void Oelif (void) { if (!iocccok
) Eioccc(); Pelif(); }
374 /* ignore comments in this block */
375 static void Idrop (void) { Fdrop(); ignoreon(); }
376 static void Itrue (void) { Ftrue(); ignoreon(); }
377 static void Ifalse(void) { Ffalse(); ignoreon(); }
379 static void Mpass (void) { strncpy(keyword
, "if ", 4); Pelif(); }
380 static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE
); }
381 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER
); }
382 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE
); }
384 static state_fn
* const trans_table
[IS_COUNT
][LT_COUNT
] = {
386 { Itrue
, Ifalse
,Fpass
, Ftrue
, Ffalse
,Eelif
, Eelif
, Eelif
, Eelse
, Eendif
,
387 Oiffy
, Oiffy
, Fpass
, Oif
, Oif
, Eelif
, Eelif
, Eelif
, Eelse
, Eendif
,
388 print
, done
, abort
},
389 /* IS_FALSE_PREFIX */
390 { Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Mpass
, Strue
, Sfalse
,Selse
, Dendif
,
391 Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Mpass
, Eioccc
,Eioccc
,Eioccc
,Eioccc
,
394 { Itrue
, Ifalse
,Fpass
, Ftrue
, Ffalse
,Dfalse
,Dfalse
,Dfalse
,Delse
, Dendif
,
395 Oiffy
, Oiffy
, Fpass
, Oif
, Oif
, Eioccc
,Eioccc
,Eioccc
,Eioccc
,Eioccc
,
396 print
, Eeof
, abort
},
398 { Itrue
, Ifalse
,Fpass
, Ftrue
, Ffalse
,Pelif
, Mtrue
, Delif
, Pelse
, Pendif
,
399 Oiffy
, Oiffy
, Fpass
, Oif
, Oif
, Pelif
, Oelif
, Oelif
, Pelse
, Pendif
,
400 print
, Eeof
, abort
},
401 /* IS_FALSE_MIDDLE */
402 { Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Pelif
, Mtrue
, Delif
, Pelse
, Pendif
,
403 Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Eioccc
,Eioccc
,Eioccc
,Eioccc
,Eioccc
,
406 { Itrue
, Ifalse
,Fpass
, Ftrue
, Ffalse
,Melif
, Melif
, Melif
, Melse
, Pendif
,
407 Oiffy
, Oiffy
, Fpass
, Oif
, Oif
, Eioccc
,Eioccc
,Eioccc
,Eioccc
,Pendif
,
408 print
, Eeof
, abort
},
410 { Itrue
, Ifalse
,Fpass
, Ftrue
, Ffalse
,Eelif
, Eelif
, Eelif
, Eelse
, Pendif
,
411 Oiffy
, Oiffy
, Fpass
, Oif
, Oif
, Eelif
, Eelif
, Eelif
, Eelse
, Pendif
,
412 print
, Eeof
, abort
},
414 { Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Eelif
, Eelif
, Eelif
, Eelse
, Dendif
,
415 Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Eelif
, Eelif
, Eelif
, Eelse
, Eioccc
,
418 { Itrue
, Ifalse
,Fpass
, Ftrue
, Ffalse
,Eelif
, Eelif
, Eelif
, Eelse
, Dendif
,
419 Oiffy
, Oiffy
, Fpass
, Oif
, Oif
, Eelif
, Eelif
, Eelif
, Eelse
, Eioccc
,
420 print
, Eeof
, abort
},
421 /* IS_FALSE_TRAILER */
422 { Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Dfalse
,Dfalse
,Dfalse
,Delse
, Dendif
,
423 Idrop
, Idrop
, Fdrop
, Fdrop
, Fdrop
, Dfalse
,Dfalse
,Dfalse
,Delse
, Eioccc
,
425 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
426 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
431 * State machine utility functions
437 error("EOF in comment");
445 ignoring
[depth
] = ignoring
[depth
-1];
450 ignoring
[depth
] = true;
453 keywordedit(const char *replacement
)
455 size_t size
= tline
+ sizeof(tline
) - keyword
;
457 const char *src
= replacement
;
459 while ((--size
!= 0) && (*src
!= '\0'))
468 if (depth
> MAXDEPTH
-1)
470 if (depth
== MAXDEPTH
-1)
471 error("Too many levels of nesting");
473 stifline
[depth
] = linenum
;
489 * Write a line to the output or not, according to command line options.
496 if (keep
^ complement
) {
497 bool blankline
= tline
[strspn(tline
, " \t\n")] == '\0';
498 if (blankline
&& compblank
&& blankcount
!= blankmax
) {
502 if (lnnum
&& delcount
> 0)
503 printf("#line %d\n", linenum
);
504 fputs(tline
, stdout
);
506 blankmax
= blankcount
= blankline
? blankcount
+ 1 : 0;
518 * The driver for the state machine.
525 /* When compressing blank lines, act as if the file
526 is preceded by a large number of blank lines. */
527 blankmax
= blankcount
= 1000;
530 lineval
= parseline();
531 trans_table
[ifstate
[depth
]][lineval
]();
532 debug("process %s -> %s depth %d",
533 linetype_name
[lineval
],
534 ifstate_name
[ifstate
[depth
]], depth
);
539 * Parse a line and determine its type. We keep the preprocessor line
540 * parser state between calls in the global variable linestate, with
541 * help from skipcomment().
550 Comment_state wascomment
;
552 if (fgets(tline
, MAXLINE
, input
) == NULL
)
555 wascomment
= incomment
;
556 cp
= skipcomment(tline
);
557 if (linestate
== LS_START
) {
560 cp
= skipcomment(cp
+ 1);
561 } else if (*cp
!= '\0')
562 linestate
= LS_DIRTY
;
564 if (!incomment
&& linestate
== LS_HASH
) {
565 keyword
= tline
+ (cp
- tline
);
567 kwlen
= cp
- keyword
;
568 /* no way can we deal with a continuation inside a keyword */
569 if (strncmp(cp
, "\\\n", 2) == 0)
571 if (strlcmp("ifdef", keyword
, kwlen
) == 0 ||
572 strlcmp("ifndef", keyword
, kwlen
) == 0) {
573 cp
= skipcomment(cp
);
574 if ((cursym
= findsym(cp
)) < 0)
577 retval
= (keyword
[2] == 'n')
578 ? LT_FALSE
: LT_TRUE
;
579 if (value
[cursym
] == NULL
)
580 retval
= (retval
== LT_TRUE
)
581 ? LT_FALSE
: LT_TRUE
;
583 retval
= (retval
== LT_TRUE
)
584 ? LT_TRUEI
: LT_FALSEI
;
587 } else if (strlcmp("if", keyword
, kwlen
) == 0)
588 retval
= ifeval(&cp
);
589 else if (strlcmp("elif", keyword
, kwlen
) == 0)
590 retval
= ifeval(&cp
) - LT_IF
+ LT_ELIF
;
591 else if (strlcmp("else", keyword
, kwlen
) == 0)
593 else if (strlcmp("endif", keyword
, kwlen
) == 0)
596 linestate
= LS_DIRTY
;
599 cp
= skipcomment(cp
);
601 linestate
= LS_DIRTY
;
602 if (retval
== LT_TRUE
|| retval
== LT_FALSE
||
603 retval
== LT_TRUEI
|| retval
== LT_FALSEI
)
605 if (retval
== LT_ELTRUE
|| retval
== LT_ELFALSE
)
608 if (retval
!= LT_PLAIN
&& (wascomment
|| incomment
)) {
611 linestate
= LS_DIRTY
;
613 /* skipcomment normally changes the state, except
614 if the last line of the file lacks a newline, or
615 if there is too much whitespace in a directive */
616 if (linestate
== LS_HASH
) {
617 size_t len
= cp
- tline
;
618 if (fgets(tline
+ len
, MAXLINE
- len
, input
) == NULL
) {
619 /* append the missing newline */
623 linestate
= LS_START
;
625 linestate
= LS_DIRTY
;
629 if (linestate
== LS_DIRTY
) {
631 cp
= skipcomment(cp
+ 1);
633 debug("parser %s comment %s line",
634 comment_name
[incomment
], linestate_name
[linestate
]);
639 * These are the binary operators that are supported by the expression
642 static Linetype
op_strict(int *p
, int v
, Linetype at
, Linetype bt
) {
643 if(at
== LT_IF
|| bt
== LT_IF
) return (LT_IF
);
644 return (*p
= v
, v
? LT_TRUE
: LT_FALSE
);
646 static Linetype
op_lt(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
647 return op_strict(p
, a
< b
, at
, bt
);
649 static Linetype
op_gt(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
650 return op_strict(p
, a
> b
, at
, bt
);
652 static Linetype
op_le(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
653 return op_strict(p
, a
<= b
, at
, bt
);
655 static Linetype
op_ge(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
656 return op_strict(p
, a
>= b
, at
, bt
);
658 static Linetype
op_eq(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
659 return op_strict(p
, a
== b
, at
, bt
);
661 static Linetype
op_ne(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
662 return op_strict(p
, a
!= b
, at
, bt
);
664 static Linetype
op_or(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
665 if (!strictlogic
&& (at
== LT_TRUE
|| bt
== LT_TRUE
))
666 return (*p
= 1, LT_TRUE
);
667 return op_strict(p
, a
|| b
, at
, bt
);
669 static Linetype
op_and(int *p
, Linetype at
, int a
, Linetype bt
, int b
) {
670 if (!strictlogic
&& (at
== LT_FALSE
|| bt
== LT_FALSE
))
671 return (*p
= 0, LT_FALSE
);
672 return op_strict(p
, a
&& b
, at
, bt
);
676 * An evaluation function takes three arguments, as follows: (1) a pointer to
677 * an element of the precedence table which lists the operators at the current
678 * level of precedence; (2) a pointer to an integer which will receive the
679 * value of the expression; and (3) a pointer to a char* that points to the
680 * expression to be evaluated and that is updated to the end of the expression
681 * when evaluation is complete. The function returns LT_FALSE if the value of
682 * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
683 * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
687 typedef Linetype
eval_fn(const struct ops
*, int *, const char **);
689 static eval_fn eval_table
, eval_unary
;
692 * The precedence table. Expressions involving binary operators are evaluated
693 * in a table-driven way by eval_table. When it evaluates a subexpression it
694 * calls the inner function with its first argument pointing to the next
695 * element of the table. Innermost expressions have special non-table-driven
698 static const struct ops
{
702 Linetype (*fn
)(int *, Linetype
, int, Linetype
, int);
705 { eval_table
, { { "||", op_or
} } },
706 { eval_table
, { { "&&", op_and
} } },
707 { eval_table
, { { "==", op_eq
},
709 { eval_unary
, { { "<=", op_le
},
716 * Function for evaluating the innermost parts of expressions,
717 * viz. !expr (expr) number defined(symbol) symbol
718 * We reset the constexpr flag in the last two cases.
721 eval_unary(const struct ops
*ops
, int *valp
, const char **cpp
)
729 cp
= skipcomment(*cpp
);
731 debug("eval%d !", ops
- eval_ops
);
733 lt
= eval_unary(ops
, valp
, &cp
);
738 lt
= *valp
? LT_TRUE
: LT_FALSE
;
740 } else if (*cp
== '(') {
742 debug("eval%d (", ops
- eval_ops
);
743 lt
= eval_table(eval_ops
, valp
, &cp
);
746 cp
= skipcomment(cp
);
749 } else if (isdigit((unsigned char)*cp
)) {
750 debug("eval%d number", ops
- eval_ops
);
751 *valp
= strtol(cp
, &ep
, 0);
754 lt
= *valp
? LT_TRUE
: LT_FALSE
;
756 } else if (strncmp(cp
, "defined", 7) == 0 && endsym(cp
[7])) {
757 cp
= skipcomment(cp
+7);
758 debug("eval%d defined", ops
- eval_ops
);
760 cp
= skipcomment(cp
+1);
769 *valp
= (value
[sym
] != NULL
);
770 lt
= *valp
? LT_TRUE
: LT_FALSE
;
773 cp
= skipcomment(cp
);
774 if (defparen
&& *cp
++ != ')')
777 } else if (!endsym(*cp
)) {
778 debug("eval%d symbol", ops
- eval_ops
);
784 } else if (value
[sym
] == NULL
) {
788 *valp
= strtol(value
[sym
], &ep
, 0);
789 if (*ep
!= '\0' || ep
== value
[sym
])
791 lt
= *valp
? LT_TRUE
: LT_FALSE
;
796 debug("eval%d bad expr", ops
- eval_ops
);
801 debug("eval%d = %d", ops
- eval_ops
, *valp
);
806 * Table-driven evaluation of binary operators.
809 eval_table(const struct ops
*ops
, int *valp
, const char **cpp
)
816 debug("eval%d", ops
- eval_ops
);
818 lt
= ops
->inner(ops
+1, valp
, &cp
);
822 cp
= skipcomment(cp
);
823 for (op
= ops
->op
; op
->str
!= NULL
; op
++)
824 if (strncmp(cp
, op
->str
, strlen(op
->str
)) == 0)
828 cp
+= strlen(op
->str
);
829 debug("eval%d %s", ops
- eval_ops
, op
->str
);
830 rt
= ops
->inner(ops
+1, &val
, &cp
);
833 lt
= op
->fn(valp
, lt
, *valp
, rt
, val
);
837 debug("eval%d = %d", ops
- eval_ops
, *valp
);
838 debug("eval%d lt = %s", ops
- eval_ops
, linetype_name
[lt
]);
843 * Evaluate the expression on a #if or #elif line. If we can work out
844 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
845 * return just a generic LT_IF.
848 ifeval(const char **cpp
)
853 debug("eval %s", *cpp
);
854 constexpr = killconsts
? false : true;
855 ret
= eval_table(eval_ops
, &val
, cpp
);
856 debug("eval = %d", val
);
857 return (constexpr ? LT_IF
: ret
== LT_ERROR
? LT_IF
: ret
);
861 * Skip over comments, strings, and character literals and stop at the
862 * next character position that is not whitespace. Between calls we keep
863 * the comment state in the global variable incomment, and we also adjust
864 * the global variable linestate when we see a newline.
865 * XXX: doesn't cope with the buffer splitting inside a state transition.
868 skipcomment(const char *cp
)
870 if (text
|| ignoring
[depth
]) {
871 for (; isspace((unsigned char)*cp
); cp
++)
873 linestate
= LS_START
;
877 /* don't reset to LS_START after a line continuation */
878 if (strncmp(cp
, "\\\n", 2) == 0)
880 else switch (incomment
) {
882 if (strncmp(cp
, "/\\\n", 3) == 0) {
883 incomment
= STARTING_COMMENT
;
885 } else if (strncmp(cp
, "/*", 2) == 0) {
886 incomment
= C_COMMENT
;
888 } else if (strncmp(cp
, "//", 2) == 0) {
889 incomment
= CXX_COMMENT
;
891 } else if (strncmp(cp
, "\'", 1) == 0) {
892 incomment
= CHAR_LITERAL
;
893 linestate
= LS_DIRTY
;
895 } else if (strncmp(cp
, "\"", 1) == 0) {
896 incomment
= STRING_LITERAL
;
897 linestate
= LS_DIRTY
;
899 } else if (strncmp(cp
, "\n", 1) == 0) {
900 linestate
= LS_START
;
902 } else if (strchr(" \t", *cp
) != NULL
) {
908 if (strncmp(cp
, "\n", 1) == 0) {
909 incomment
= NO_COMMENT
;
910 linestate
= LS_START
;
916 if ((incomment
== CHAR_LITERAL
&& cp
[0] == '\'') ||
917 (incomment
== STRING_LITERAL
&& cp
[0] == '\"')) {
918 incomment
= NO_COMMENT
;
920 } else if (cp
[0] == '\\') {
925 } else if (strncmp(cp
, "\n", 1) == 0) {
926 if (incomment
== CHAR_LITERAL
)
927 error("unterminated char literal");
929 error("unterminated string literal");
934 if (strncmp(cp
, "*\\\n", 3) == 0) {
935 incomment
= FINISHING_COMMENT
;
937 } else if (strncmp(cp
, "*/", 2) == 0) {
938 incomment
= NO_COMMENT
;
943 case STARTING_COMMENT
:
945 incomment
= C_COMMENT
;
947 } else if (*cp
== '/') {
948 incomment
= CXX_COMMENT
;
951 incomment
= NO_COMMENT
;
952 linestate
= LS_DIRTY
;
955 case FINISHING_COMMENT
:
957 incomment
= NO_COMMENT
;
960 incomment
= C_COMMENT
;
969 * Skip macro arguments.
972 skipargs(const char *cp
)
974 const char *ocp
= cp
;
976 cp
= skipcomment(cp
);
984 cp
= skipcomment(cp
+1);
985 } while (level
!= 0 && *cp
!= '\0');
989 /* Rewind and re-detect the syntax error later. */
994 * Skip over an identifier.
997 skipsym(const char *cp
)
1005 * Look for the symbol in the symbol table. If it is found, we return
1006 * the symbol table index, else we return -1.
1009 findsym(const char *str
)
1018 printf("%.*s\n", (int)(cp
-str
), str
);
1019 /* we don't care about the value of the symbol */
1022 for (symind
= 0; symind
< nsyms
; ++symind
) {
1023 if (strlcmp(symname
[symind
], str
, cp
-str
) == 0) {
1024 debug("findsym %s %s", symname
[symind
],
1025 value
[symind
] ? value
[symind
] : "");
1033 * Add a symbol to the symbol table.
1036 addsym(bool ignorethis
, bool definethis
, char *sym
)
1041 symind
= findsym(sym
);
1043 if (nsyms
>= MAXSYMS
)
1044 errx(2, "too many symbols");
1047 symname
[symind
] = sym
;
1048 ignore
[symind
] = ignorethis
;
1049 val
= sym
+ (skipsym(sym
) - sym
);
1052 value
[symind
] = val
+1;
1054 } else if (*val
== '\0')
1061 value
[symind
] = NULL
;
1066 * Compare s with n characters of t.
1067 * The same as strncmp() except that it checks that s[n] == '\0'.
1070 strlcmp(const char *s
, const char *t
, size_t n
)
1072 while (n
-- && *t
!= '\0')
1074 return ((unsigned char)*s
- (unsigned char)*t
);
1077 return ((unsigned char)*s
);
1084 debug(const char *msg
, ...)
1096 error(const char *msg
)
1099 warnx("%s: %d: %s", filename
, linenum
, msg
);
1101 warnx("%s: %d: %s (#if line %d depth %d)",
1102 filename
, linenum
, msg
, stifline
[depth
], depth
);
1103 errx(2, "output may be truncated");