2 * Copyright (c) 2002 - 2008 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 is 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.
34 #include <sys/cdefs.h>
38 static const char copyright[] =
39 "@(#) Copyright (c) 1985, 1993\n\
40 The Regents of the University of California. All rights reserved.\n";
43 __IDSTRING(Berkeley, "@(#)unifdef.c 8.1 (Berkeley) 6/6/93");
44 __IDSTRING(NetBSD, "$NetBSD: unifdef.c,v 1.8 2000/07/03 02:51:36 matt Exp $");
45 __IDSTRING(dotat, "$dotat: things/unifdef.c,v 1.178 2008/03/02 22:23:32 fanf2 Exp $");
49 __FBSDID("$FreeBSD$");
53 * unifdef - remove ifdef'ed lines
56 * provide an option which will append the name of the
57 * appropriate symbol after #else's and #endif's
58 * provide an option which will check symbols after
59 * #else's and #endif's to see that they match their
60 * corresponding #ifdef or #ifndef
62 * The first two items above require better buffer handling, which would
63 * also make it possible to handle all "dodgy" directives correctly.
75 /* types of input lines: */
77 LT_TRUEI, /* a true #if with ignore flag */
78 LT_FALSEI, /* a false #if with ignore flag */
79 LT_IF, /* an unknown #if */
80 LT_TRUE, /* a true #if */
81 LT_FALSE, /* a false #if */
82 LT_ELIF, /* an unknown #elif */
83 LT_ELTRUE, /* a true #elif */
84 LT_ELFALSE, /* a false #elif */
86 LT_ENDIF, /* #endif */
87 LT_DODGY, /* flag: directive is not on one line */
88 LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
89 LT_PLAIN, /* ordinary line */
90 LT_EOF, /* end of file */
94 static char const * const linetype_name[] = {
95 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
96 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
97 "DODGY TRUEI", "DODGY FALSEI",
98 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
99 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
100 "DODGY ELSE", "DODGY ENDIF",
104 /* state of #if processing */
107 IS_FALSE_PREFIX, /* false #if followed by false #elifs */
108 IS_TRUE_PREFIX, /* first non-false #(el)if is true */
109 IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
110 IS_FALSE_MIDDLE, /* a false #elif after a pass state */
111 IS_TRUE_MIDDLE, /* a true #elif after a pass state */
112 IS_PASS_ELSE, /* an else after a pass state */
113 IS_FALSE_ELSE, /* an else after a true state */
114 IS_TRUE_ELSE, /* an else after only false states */
115 IS_FALSE_TRAILER, /* #elifs after a true are false */
119 static char const * const ifstate_name[] = {
120 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
121 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
122 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
126 /* state of comment parser */
128 NO_COMMENT = false, /* outside a comment */
129 C_COMMENT, /* in a comment like this one */
130 CXX_COMMENT, /* between // and end of line */
131 STARTING_COMMENT, /* just after slash-backslash-newline */
132 FINISHING_COMMENT, /* star-backslash-newline in a C comment */
133 CHAR_LITERAL, /* inside '' */
134 STRING_LITERAL /* inside "" */
137 static char const * const comment_name[] = {
138 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
141 /* state of preprocessor line parser */
143 LS_START, /* only space and comments on this line */
144 LS_HASH, /* only space, comments, and a hash */
145 LS_DIRTY /* this line can't be a preprocessor line */
148 static char const * const linestate_name[] = {
149 "START", "HASH", "DIRTY"
153 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
155 #define MAXDEPTH 64 /* maximum #if nesting */
156 #define MAXLINE 4096 /* maximum length of line */
157 #define MAXSYMS 4096 /* maximum number of symbols */
160 * Sometimes when editing a keyword the replacement text is longer, so
161 * we leave some space at the end of the tline buffer to accommodate this.
169 static bool complement; /* -c: do the complement */
170 static bool debugging; /* -d: debugging reports */
171 static bool iocccok; /* -e: fewer IOCCC errors */
172 static bool killconsts; /* -k: eval constant #ifs */
173 static bool lnblank; /* -l: blank deleted lines */
174 static bool lnnum; /* -n: add #line directives */
175 static bool symlist; /* -s: output symbol list */
176 static bool text; /* -t: this is a text file */
178 static const char *symname[MAXSYMS]; /* symbol name */
179 static const char *value[MAXSYMS]; /* -Dsym=value */
180 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
181 static int nsyms; /* number of symbols */
183 static FILE *input; /* input file pointer */
184 static const char *filename; /* input file name */
185 static int linenum; /* current line number */
187 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
188 static char *keyword; /* used for editing #elif's */
190 static Comment_state incomment; /* comment parser state */
191 static Line_state linestate; /* #if line parser state */
192 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
193 static bool ignoring[MAXDEPTH]; /* ignore comments state */
194 static int stifline[MAXDEPTH]; /* start of current #if */
195 static int depth; /* current #if nesting */
196 static int delcount; /* count of deleted lines */
197 static bool keepthis; /* don't delete constant #if */
199 static int exitstat; /* program exit status */
201 static void addsym(bool, bool, char *);
202 static void debug(const char *, ...);
203 static void done(void);
204 static void error(const char *);
205 static int findsym(const char *);
206 static void flushline(bool);
207 static Linetype getline(void);
208 static Linetype ifeval(const char **);
209 static void ignoreoff(void);
210 static void ignoreon(void);
211 static void keywordedit(const char *);
212 static void nest(void);
213 static void process(void);
214 static const char *skipcomment(const char *);
215 static const char *skipsym(const char *);
216 static void state(Ifstate);
217 static int strlcmp(const char *, const char *, size_t);
218 static void unnest(void);
219 static void usage(void);
221 #define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')
227 main(int argc, char *argv[])
231 while ((opt = getopt(argc, argv, "i:D:U:I:cdeklnst")) != -1)
233 case 'i': /* treat stuff controlled by these symbols as text */
235 * For strict backwards-compatibility the U or D
236 * should be immediately after the -i but it doesn't
237 * matter much if we relax that requirement.
241 addsym(true, true, optarg);
243 addsym(true, false, optarg);
247 case 'D': /* define a symbol */
248 addsym(false, true, optarg);
250 case 'U': /* undef a symbol */
251 addsym(false, false, optarg);
254 /* no-op for compatibility with cpp */
256 case 'c': /* treat -D as -U and vice versa */
262 case 'e': /* fewer errors from dodgy lines */
265 case 'k': /* process constant #ifs */
268 case 'l': /* blank deleted lines instead of omitting them */
271 case 'n': /* add #line directive after deleted lines */
274 case 's': /* only output list of symbols that control #ifs */
277 case 't': /* don't parse C comments */
286 errx(2, "can only do one file");
287 } else if (argc == 1 && strcmp(*argv, "-") != 0) {
289 input = fopen(filename, "r");
291 err(2, "can't open %s", filename);
293 filename = "[stdin]";
303 fprintf(stderr, "usage: unifdef [-cdeklnst] [-Ipath]"
304 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
309 * A state transition function alters the global #if processing state
310 * in a particular way. The table below is indexed by the current
311 * processing state and the type of the current line.
313 * Nesting is handled by keeping a stack of states; some transition
314 * functions increase or decrease the depth. They also maintain the
315 * ignore state on a stack. In some complicated cases they have to
316 * alter the preprocessor directive, as follows.
318 * When we have processed a group that starts off with a known-false
319 * #if/#elif sequence (which has therefore been deleted) followed by a
320 * #elif that we don't understand and therefore must keep, we edit the
321 * latter into a #if to keep the nesting correct.
323 * When we find a true #elif in a group, the following block will
324 * always be kept and the rest of the sequence after the next #elif or
325 * #else will be discarded. We edit the #elif into a #else and the
326 * following directive to #endif since this has the desired behaviour.
328 * "Dodgy" directives are split across multiple lines, the most common
329 * example being a multi-line comment hanging off the right of the
330 * directive. We can handle them correctly only if there is no change
331 * from printing to dropping (or vice versa) caused by that directive.
332 * If the directive is the first of a group we have a choice between
333 * failing with an error, or passing it through unchanged instead of
334 * evaluating it. The latter is not the default to avoid questions from
335 * users about unifdef unexpectedly leaving behind preprocessor directives.
337 typedef void state_fn(void);
339 /* report an error */
340 static void Eelif (void) { error("Inappropriate #elif"); }
341 static void Eelse (void) { error("Inappropriate #else"); }
342 static void Eendif(void) { error("Inappropriate #endif"); }
343 static void Eeof (void) { error("Premature EOF"); }
344 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
345 /* plain line handling */
346 static void print (void) { flushline(true); }
347 static void drop (void) { flushline(false); }
348 /* output lacks group's start line */
349 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
350 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
351 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
352 /* print/pass this block */
353 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
354 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
355 static void Pendif(void) { print(); unnest(); }
356 /* discard this block */
357 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
358 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
359 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
360 static void Dendif(void) { drop(); unnest(); }
361 /* first line of group */
362 static void Fdrop (void) { nest(); Dfalse(); }
363 static void Fpass (void) { nest(); Pelif(); }
364 static void Ftrue (void) { nest(); Strue(); }
365 static void Ffalse(void) { nest(); Sfalse(); }
366 /* variable pedantry for obfuscated lines */
367 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
368 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
369 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
370 /* ignore comments in this block */
371 static void Idrop (void) { Fdrop(); ignoreon(); }
372 static void Itrue (void) { Ftrue(); ignoreon(); }
373 static void Ifalse(void) { Ffalse(); ignoreon(); }
375 static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
376 static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
377 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
378 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
380 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
382 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
383 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
385 /* IS_FALSE_PREFIX */
386 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
387 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
390 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
391 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
394 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
395 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
397 /* IS_FALSE_MIDDLE */
398 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
399 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
402 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
403 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
406 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
407 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
410 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
411 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
414 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
415 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
417 /* IS_FALSE_TRAILER */
418 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
419 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
421 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
422 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
427 * State machine utility functions
433 error("EOF in comment");
441 ignoring[depth] = ignoring[depth-1];
446 ignoring[depth] = true;
449 keywordedit(const char *replacement)
451 strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
458 if (depth >= MAXDEPTH)
459 error("Too many levels of nesting");
460 stifline[depth] = linenum;
476 * Write a line to the output or not, according to command line options.
483 if (keep ^ complement) {
484 if (lnnum && delcount > 0)
485 printf("#line %d\n", linenum);
486 fputs(tline, stdout);
497 * The driver for the state machine.
507 trans_table[ifstate[depth]][lineval]();
508 debug("process %s -> %s depth %d",
509 linetype_name[lineval],
510 ifstate_name[ifstate[depth]], depth);
515 * Parse a line and determine its type. We keep the preprocessor line
516 * parser state between calls in the global variable linestate, with
517 * help from skipcomment().
526 Comment_state wascomment;
528 if (fgets(tline, MAXLINE, input) == NULL)
531 wascomment = incomment;
532 cp = skipcomment(tline);
533 if (linestate == LS_START) {
536 cp = skipcomment(cp + 1);
537 } else if (*cp != '\0')
538 linestate = LS_DIRTY;
540 if (!incomment && linestate == LS_HASH) {
541 keyword = tline + (cp - tline);
543 kwlen = cp - keyword;
544 /* no way can we deal with a continuation inside a keyword */
545 if (strncmp(cp, "\\\n", 2) == 0)
547 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
548 strlcmp("ifndef", keyword, kwlen) == 0) {
549 cp = skipcomment(cp);
550 if ((cursym = findsym(cp)) < 0)
553 retval = (keyword[2] == 'n')
554 ? LT_FALSE : LT_TRUE;
555 if (value[cursym] == NULL)
556 retval = (retval == LT_TRUE)
557 ? LT_FALSE : LT_TRUE;
559 retval = (retval == LT_TRUE)
560 ? LT_TRUEI : LT_FALSEI;
563 } else if (strlcmp("if", keyword, kwlen) == 0)
564 retval = ifeval(&cp);
565 else if (strlcmp("elif", keyword, kwlen) == 0)
566 retval = ifeval(&cp) - LT_IF + LT_ELIF;
567 else if (strlcmp("else", keyword, kwlen) == 0)
569 else if (strlcmp("endif", keyword, kwlen) == 0)
572 linestate = LS_DIRTY;
575 cp = skipcomment(cp);
577 linestate = LS_DIRTY;
578 if (retval == LT_TRUE || retval == LT_FALSE ||
579 retval == LT_TRUEI || retval == LT_FALSEI)
581 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
584 if (retval != LT_PLAIN && (wascomment || incomment)) {
587 linestate = LS_DIRTY;
589 /* skipcomment normally changes the state, except
590 if the last line of the file lacks a newline, or
591 if there is too much whitespace in a directive */
592 if (linestate == LS_HASH) {
593 size_t len = cp - tline;
594 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
595 /* append the missing newline */
599 linestate = LS_START;
601 linestate = LS_DIRTY;
605 if (linestate == LS_DIRTY) {
607 cp = skipcomment(cp + 1);
609 debug("parser %s comment %s line",
610 comment_name[incomment], linestate_name[linestate]);
615 * These are the binary operators that are supported by the expression
616 * evaluator. Note that if support for division is added then we also
617 * need short-circuiting booleans because of divide-by-zero.
619 static int op_lt(int a, int b) { return (a < b); }
620 static int op_gt(int a, int b) { return (a > b); }
621 static int op_le(int a, int b) { return (a <= b); }
622 static int op_ge(int a, int b) { return (a >= b); }
623 static int op_eq(int a, int b) { return (a == b); }
624 static int op_ne(int a, int b) { return (a != b); }
625 static int op_or(int a, int b) { return (a || b); }
626 static int op_and(int a, int b) { return (a && b); }
629 * An evaluation function takes three arguments, as follows: (1) a pointer to
630 * an element of the precedence table which lists the operators at the current
631 * level of precedence; (2) a pointer to an integer which will receive the
632 * value of the expression; and (3) a pointer to a char* that points to the
633 * expression to be evaluated and that is updated to the end of the expression
634 * when evaluation is complete. The function returns LT_FALSE if the value of
635 * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
636 * expression could not be evaluated.
640 typedef Linetype eval_fn(const struct ops *, int *, const char **);
642 static eval_fn eval_table, eval_unary;
645 * The precedence table. Expressions involving binary operators are evaluated
646 * in a table-driven way by eval_table. When it evaluates a subexpression it
647 * calls the inner function with its first argument pointing to the next
648 * element of the table. Innermost expressions have special non-table-driven
651 static const struct ops {
658 { eval_table, { { "||", op_or } } },
659 { eval_table, { { "&&", op_and } } },
660 { eval_table, { { "==", op_eq },
662 { eval_unary, { { "<=", op_le },
669 * Function for evaluating the innermost parts of expressions,
670 * viz. !expr (expr) defined(symbol) symbol number
671 * We reset the keepthis flag when we find a non-constant subexpression.
674 eval_unary(const struct ops *ops, int *valp, const char **cpp)
681 cp = skipcomment(*cpp);
683 debug("eval%d !", ops - eval_ops);
685 if (eval_unary(ops, valp, &cp) == LT_IF)
688 } else if (*cp == '(') {
690 debug("eval%d (", ops - eval_ops);
691 if (eval_table(eval_ops, valp, &cp) == LT_IF)
693 cp = skipcomment(cp);
696 } else if (isdigit((unsigned char)*cp)) {
697 debug("eval%d number", ops - eval_ops);
698 *valp = strtol(cp, &ep, 0);
700 } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
701 cp = skipcomment(cp+7);
702 debug("eval%d defined", ops - eval_ops);
704 cp = skipcomment(cp+1);
712 *valp = (value[sym] != NULL);
714 cp = skipcomment(cp);
715 if (defparen && *cp++ != ')')
718 } else if (!endsym(*cp)) {
719 debug("eval%d symbol", ops - eval_ops);
723 if (value[sym] == NULL)
726 *valp = strtol(value[sym], &ep, 0);
727 if (*ep != '\0' || ep == value[sym])
733 debug("eval%d bad expr", ops - eval_ops);
738 debug("eval%d = %d", ops - eval_ops, *valp);
739 return (*valp ? LT_TRUE : LT_FALSE);
743 * Table-driven evaluation of binary operators.
746 eval_table(const struct ops *ops, int *valp, const char **cpp)
752 debug("eval%d", ops - eval_ops);
754 if (ops->inner(ops+1, valp, &cp) == LT_IF)
757 cp = skipcomment(cp);
758 for (op = ops->op; op->str != NULL; op++)
759 if (strncmp(cp, op->str, strlen(op->str)) == 0)
763 cp += strlen(op->str);
764 debug("eval%d %s", ops - eval_ops, op->str);
765 if (ops->inner(ops+1, &val, &cp) == LT_IF)
767 *valp = op->fn(*valp, val);
771 debug("eval%d = %d", ops - eval_ops, *valp);
772 return (*valp ? LT_TRUE : LT_FALSE);
776 * Evaluate the expression on a #if or #elif line. If we can work out
777 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
778 * return just a generic LT_IF.
781 ifeval(const char **cpp)
786 debug("eval %s", *cpp);
787 keepthis = killconsts ? false : true;
788 ret = eval_table(eval_ops, &val, cpp);
789 debug("eval = %d", val);
790 return (keepthis ? LT_IF : ret);
794 * Skip over comments, strings, and character literals and stop at the
795 * next character position that is not whitespace. Between calls we keep
796 * the comment state in the global variable incomment, and we also adjust
797 * the global variable linestate when we see a newline.
798 * XXX: doesn't cope with the buffer splitting inside a state transition.
801 skipcomment(const char *cp)
803 if (text || ignoring[depth]) {
804 for (; isspace((unsigned char)*cp); cp++)
806 linestate = LS_START;
810 /* don't reset to LS_START after a line continuation */
811 if (strncmp(cp, "\\\n", 2) == 0)
813 else switch (incomment) {
815 if (strncmp(cp, "/\\\n", 3) == 0) {
816 incomment = STARTING_COMMENT;
818 } else if (strncmp(cp, "/*", 2) == 0) {
819 incomment = C_COMMENT;
821 } else if (strncmp(cp, "//", 2) == 0) {
822 incomment = CXX_COMMENT;
824 } else if (strncmp(cp, "\'", 1) == 0) {
825 incomment = CHAR_LITERAL;
826 linestate = LS_DIRTY;
828 } else if (strncmp(cp, "\"", 1) == 0) {
829 incomment = STRING_LITERAL;
830 linestate = LS_DIRTY;
832 } else if (strncmp(cp, "\n", 1) == 0) {
833 linestate = LS_START;
835 } else if (strchr(" \t", *cp) != NULL) {
841 if (strncmp(cp, "\n", 1) == 0) {
842 incomment = NO_COMMENT;
843 linestate = LS_START;
849 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
850 (incomment == STRING_LITERAL && cp[0] == '\"')) {
851 incomment = NO_COMMENT;
853 } else if (cp[0] == '\\') {
858 } else if (strncmp(cp, "\n", 1) == 0) {
859 if (incomment == CHAR_LITERAL)
860 error("unterminated char literal");
862 error("unterminated string literal");
867 if (strncmp(cp, "*\\\n", 3) == 0) {
868 incomment = FINISHING_COMMENT;
870 } else if (strncmp(cp, "*/", 2) == 0) {
871 incomment = NO_COMMENT;
876 case STARTING_COMMENT:
878 incomment = C_COMMENT;
880 } else if (*cp == '/') {
881 incomment = CXX_COMMENT;
884 incomment = NO_COMMENT;
885 linestate = LS_DIRTY;
888 case FINISHING_COMMENT:
890 incomment = NO_COMMENT;
893 incomment = C_COMMENT;
902 * Skip over an identifier.
905 skipsym(const char *cp)
913 * Look for the symbol in the symbol table. If it is found, we return
914 * the symbol table index, else we return -1.
917 findsym(const char *str)
926 printf("%.*s\n", (int)(cp-str), str);
927 /* we don't care about the value of the symbol */
930 for (symind = 0; symind < nsyms; ++symind) {
931 if (strlcmp(symname[symind], str, cp-str) == 0) {
932 debug("findsym %s %s", symname[symind],
933 value[symind] ? value[symind] : "");
941 * Add a symbol to the symbol table.
944 addsym(bool ignorethis, bool definethis, char *sym)
949 symind = findsym(sym);
951 if (nsyms >= MAXSYMS)
952 errx(2, "too many symbols");
955 symname[symind] = sym;
956 ignore[symind] = ignorethis;
957 val = sym + (skipsym(sym) - sym);
960 value[symind] = val+1;
962 } else if (*val == '\0')
969 value[symind] = NULL;
974 * Compare s with n characters of t.
975 * The same as strncmp() except that it checks that s[n] == '\0'.
978 strlcmp(const char *s, const char *t, size_t n)
980 while (n-- && *t != '\0')
982 return ((unsigned char)*s - (unsigned char)*t);
985 return ((unsigned char)*s);
992 debug(const char *msg, ...)
1004 error(const char *msg)
1007 warnx("%s: %d: %s", filename, linenum, msg);
1009 warnx("%s: %d: %s (#if line %d depth %d)",
1010 filename, linenum, msg, stifline[depth], depth);
1011 errx(2, "output may be truncated");