2 * Copyright (c) 2002 - 2005 Tony Finch <dot@dotat.at>. All rights reserved.
4 * This code is derived from software contributed to Berkeley by Dave Yost.
5 * It was rewritten to support ANSI C by Tony Finch. The original version of
6 * unifdef carried the following copyright notice. None of its code remains
7 * in this version (though some of the names remain).
9 * Copyright (c) 1985, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#) Copyright (c) 1985, 1993\n\
34 * The Regents of the University of California. All rights reserved.
35 * @(#)unifdef.c 8.1 (Berkeley) 6/6/93
37 * $DragonFly: src/usr.bin/unifdef/unifdef.c,v 1.4 2007/06/26 07:47:28 hasso Exp $
38 * $FreeBSD: src/usr.bin/unifdef/unifdef.c,v 1.20 2005/05/21 09:55:09 ru Exp $
39 * $NetBSD: unifdef.c,v 1.8 2000/07/03 02:51:36 matt Exp $
40 * $dotat: things/unifdef.c,v 1.171 2005/03/08 12:38:48 fanf2 Exp $"
44 * unifdef - remove ifdef'ed lines
47 * provide an option which will append the name of the
48 * appropriate symbol after #else's and #endif's
49 * provide an option which will check symbols after
50 * #else's and #endif's to see that they match their
51 * corresponding #ifdef or #ifndef
53 * The first two items above require better buffer handling, which would
54 * also make it possible to handle all "dodgy" directives correctly.
66 /* types of input lines: */
68 LT_TRUEI, /* a true #if with ignore flag */
69 LT_FALSEI, /* a false #if with ignore flag */
70 LT_IF, /* an unknown #if */
71 LT_TRUE, /* a true #if */
72 LT_FALSE, /* a false #if */
73 LT_ELIF, /* an unknown #elif */
74 LT_ELTRUE, /* a true #elif */
75 LT_ELFALSE, /* a false #elif */
77 LT_ENDIF, /* #endif */
78 LT_DODGY, /* flag: directive is not on one line */
79 LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
80 LT_PLAIN, /* ordinary line */
81 LT_EOF, /* end of file */
85 static char const * const linetype_name[] = {
86 "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
87 "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
88 "DODGY TRUEI", "DODGY FALSEI",
89 "DODGY IF", "DODGY TRUE", "DODGY FALSE",
90 "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
91 "DODGY ELSE", "DODGY ENDIF",
95 /* state of #if processing */
98 IS_FALSE_PREFIX, /* false #if followed by false #elifs */
99 IS_TRUE_PREFIX, /* first non-false #(el)if is true */
100 IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
101 IS_FALSE_MIDDLE, /* a false #elif after a pass state */
102 IS_TRUE_MIDDLE, /* a true #elif after a pass state */
103 IS_PASS_ELSE, /* an else after a pass state */
104 IS_FALSE_ELSE, /* an else after a true state */
105 IS_TRUE_ELSE, /* an else after only false states */
106 IS_FALSE_TRAILER, /* #elifs after a true are false */
110 static char const * const ifstate_name[] = {
111 "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
112 "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
113 "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
117 /* state of comment parser */
119 NO_COMMENT = false, /* outside a comment */
120 C_COMMENT, /* in a comment like this one */
121 CXX_COMMENT, /* between // and end of line */
122 STARTING_COMMENT, /* just after slash-backslash-newline */
123 FINISHING_COMMENT, /* star-backslash-newline in a C comment */
124 CHAR_LITERAL, /* inside '' */
125 STRING_LITERAL /* inside "" */
128 static char const * const comment_name[] = {
129 "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
132 /* state of preprocessor line parser */
134 LS_START, /* only space and comments on this line */
135 LS_HASH, /* only space, comments, and a hash */
136 LS_DIRTY /* this line can't be a preprocessor line */
139 static char const * const linestate_name[] = {
140 "START", "HASH", "DIRTY"
144 * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
146 #define MAXDEPTH 64 /* maximum #if nesting */
147 #define MAXLINE 4096 /* maximum length of line */
148 #define MAXSYMS 4096 /* maximum number of symbols */
151 * Sometimes when editing a keyword the replacement text is longer, so
152 * we leave some space at the end of the tline buffer to accommodate this.
160 static bool complement; /* -c: do the complement */
161 static bool debugging; /* -d: debugging reports */
162 static bool iocccok; /* -e: fewer IOCCC errors */
163 static bool killconsts; /* -k: eval constant #ifs */
164 static bool lnblank; /* -l: blank deleted lines */
165 static bool lnnum; /* -n: add #line directives */
166 static bool symlist; /* -s: output symbol list */
167 static bool text; /* -t: this is a text file */
169 static const char *symname[MAXSYMS]; /* symbol name */
170 static const char *value[MAXSYMS]; /* -Dsym=value */
171 static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
172 static int nsyms; /* number of symbols */
174 static FILE *input; /* input file pointer */
175 static const char *filename; /* input file name */
176 static int linenum; /* current line number */
178 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
179 static char *keyword; /* used for editing #elif's */
181 static Comment_state incomment; /* comment parser state */
182 static Line_state linestate; /* #if line parser state */
183 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
184 static bool ignoring[MAXDEPTH]; /* ignore comments state */
185 static int stifline[MAXDEPTH]; /* start of current #if */
186 static int depth; /* current #if nesting */
187 static int delcount; /* count of deleted lines */
188 static bool keepthis; /* don't delete constant #if */
190 static int exitstat; /* program exit status */
192 static void addsym(bool, bool, char *);
193 static void debug(const char *, ...) __printflike(1, 2);
194 static void done(void);
195 static void error(const char *);
196 static int findsym(const char *);
197 static void flushline(bool);
198 static Linetype getline(void);
199 static Linetype ifeval(const char **);
200 static void ignoreoff(void);
201 static void ignoreon(void);
202 static void keywordedit(const char *);
203 static void nest(void);
204 static void process(void);
205 static const char *skipcomment(const char *);
206 static const char *skipsym(const char *);
207 static void state(Ifstate);
208 static int strlcmp(const char *, const char *, size_t);
209 static void unnest(void);
210 static void usage(void);
212 #define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')
218 main(int argc, char *argv[])
222 while ((opt = getopt(argc, argv, "i:D:U:I:cdeklnst")) != -1)
224 case 'i': /* treat stuff controlled by these symbols as text */
226 * For strict backwards-compatibility the U or D
227 * should be immediately after the -i but it doesn't
228 * matter much if we relax that requirement.
232 addsym(true, true, optarg);
234 addsym(true, false, optarg);
238 case 'D': /* define a symbol */
239 addsym(false, true, optarg);
241 case 'U': /* undef a symbol */
242 addsym(false, false, optarg);
245 /* no-op for compatibility with cpp */
247 case 'c': /* treat -D as -U and vice versa */
253 case 'e': /* fewer errors from dodgy lines */
256 case 'k': /* process constant #ifs */
259 case 'l': /* blank deleted lines instead of omitting them */
262 case 'n': /* add #line directive after deleted lines */
265 case 's': /* only output list of symbols that control #ifs */
268 case 't': /* don't parse C comments */
277 errx(2, "can only do one file");
278 } else if (argc == 1 && strcmp(*argv, "-") != 0) {
280 input = fopen(filename, "r");
282 err(2, "can't open %s", filename);
284 filename = "[stdin]";
294 fprintf(stderr, "usage: unifdef [-cdeklnst] [-Ipath]"
295 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
300 * A state transition function alters the global #if processing state
301 * in a particular way. The table below is indexed by the current
302 * processing state and the type of the current line.
304 * Nesting is handled by keeping a stack of states; some transition
305 * functions increase or decrease the depth. They also maintain the
306 * ignore state on a stack. In some complicated cases they have to
307 * alter the preprocessor directive, as follows.
309 * When we have processed a group that starts off with a known-false
310 * #if/#elif sequence (which has therefore been deleted) followed by a
311 * #elif that we don't understand and therefore must keep, we edit the
312 * latter into a #if to keep the nesting correct.
314 * When we find a true #elif in a group, the following block will
315 * always be kept and the rest of the sequence after the next #elif or
316 * #else will be discarded. We edit the #elif into a #else and the
317 * following directive to #endif since this has the desired behaviour.
319 * "Dodgy" directives are split across multiple lines, the most common
320 * example being a multi-line comment hanging off the right of the
321 * directive. We can handle them correctly only if there is no change
322 * from printing to dropping (or vice versa) caused by that directive.
323 * If the directive is the first of a group we have a choice between
324 * failing with an error, or passing it through unchanged instead of
325 * evaluating it. The latter is not the default to avoid questions from
326 * users about unifdef unexpectedly leaving behind preprocessor directives.
328 typedef void state_fn(void);
330 /* report an error */
331 static void Eelif (void) { error("Inappropriate #elif"); }
332 static void Eelse (void) { error("Inappropriate #else"); }
333 static void Eendif(void) { error("Inappropriate #endif"); }
334 static void Eeof (void) { error("Premature EOF"); }
335 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
336 /* plain line handling */
337 static void print (void) { flushline(true); }
338 static void drop (void) { flushline(false); }
339 /* output lacks group's start line */
340 static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
341 static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
342 static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
343 /* print/pass this block */
344 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
345 static void Pelse (void) { print(); state(IS_PASS_ELSE); }
346 static void Pendif(void) { print(); unnest(); }
347 /* discard this block */
348 static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
349 static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
350 static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
351 static void Dendif(void) { drop(); unnest(); }
352 /* first line of group */
353 static void Fdrop (void) { nest(); Dfalse(); }
354 static void Fpass (void) { nest(); Pelif(); }
355 static void Ftrue (void) { nest(); Strue(); }
356 static void Ffalse(void) { nest(); Sfalse(); }
357 /* variable pedantry for obfuscated lines */
358 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
359 static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
360 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
361 /* ignore comments in this block */
362 static void Idrop (void) { Fdrop(); ignoreon(); }
363 static void Itrue (void) { Ftrue(); ignoreon(); }
364 static void Ifalse(void) { Ffalse(); ignoreon(); }
366 static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
367 static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
368 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
369 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
371 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
373 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
374 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
376 /* IS_FALSE_PREFIX */
377 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
378 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
381 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
382 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
385 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
386 Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
388 /* IS_FALSE_MIDDLE */
389 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
390 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
393 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
394 Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
397 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
398 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
401 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
402 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
405 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
406 Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
408 /* IS_FALSE_TRAILER */
409 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
410 Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
412 /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
413 TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
418 * State machine utility functions
424 error("EOF in comment");
432 ignoring[depth] = ignoring[depth-1];
437 ignoring[depth] = true;
440 keywordedit(const char *replacement)
442 strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
449 if (depth >= MAXDEPTH)
450 error("Too many levels of nesting");
451 stifline[depth] = linenum;
467 * Write a line to the output or not, according to command line options.
474 if (keep ^ complement) {
475 if (lnnum && delcount > 0)
476 printf("#line %d\n", linenum);
477 fputs(tline, stdout);
488 * The driver for the state machine.
498 trans_table[ifstate[depth]][lineval]();
499 debug("process %s -> %s depth %d",
500 linetype_name[lineval],
501 ifstate_name[ifstate[depth]], depth);
506 * Parse a line and determine its type. We keep the preprocessor line
507 * parser state between calls in the global variable linestate, with
508 * help from skipcomment().
517 Comment_state wascomment;
519 if (fgets(tline, MAXLINE, input) == NULL)
522 wascomment = incomment;
523 cp = skipcomment(tline);
524 if (linestate == LS_START) {
527 cp = skipcomment(cp + 1);
528 } else if (*cp != '\0')
529 linestate = LS_DIRTY;
531 if (!incomment && linestate == LS_HASH) {
532 keyword = tline + (cp - tline);
534 kwlen = cp - keyword;
535 /* no way can we deal with a continuation inside a keyword */
536 if (strncmp(cp, "\\\n", 2) == 0)
538 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
539 strlcmp("ifndef", keyword, kwlen) == 0) {
540 cp = skipcomment(cp);
541 if ((cursym = findsym(cp)) < 0)
544 retval = (keyword[2] == 'n')
545 ? LT_FALSE : LT_TRUE;
546 if (value[cursym] == NULL)
547 retval = (retval == LT_TRUE)
548 ? LT_FALSE : LT_TRUE;
550 retval = (retval == LT_TRUE)
551 ? LT_TRUEI : LT_FALSEI;
554 } else if (strlcmp("if", keyword, kwlen) == 0)
555 retval = ifeval(&cp);
556 else if (strlcmp("elif", keyword, kwlen) == 0)
557 retval = ifeval(&cp) - LT_IF + LT_ELIF;
558 else if (strlcmp("else", keyword, kwlen) == 0)
560 else if (strlcmp("endif", keyword, kwlen) == 0)
563 linestate = LS_DIRTY;
566 cp = skipcomment(cp);
568 linestate = LS_DIRTY;
569 if (retval == LT_TRUE || retval == LT_FALSE ||
570 retval == LT_TRUEI || retval == LT_FALSEI)
572 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
575 if (retval != LT_PLAIN && (wascomment || incomment)) {
578 linestate = LS_DIRTY;
580 /* skipcomment should have changed the state */
581 if (linestate == LS_HASH)
584 if (linestate == LS_DIRTY) {
586 cp = skipcomment(cp + 1);
588 debug("parser %s comment %s line",
589 comment_name[incomment], linestate_name[linestate]);
594 * These are the binary operators that are supported by the expression
595 * evaluator. Note that if support for division is added then we also
596 * need short-circuiting booleans because of divide-by-zero.
598 static int op_lt(int a, int b) { return (a < b); }
599 static int op_gt(int a, int b) { return (a > b); }
600 static int op_le(int a, int b) { return (a <= b); }
601 static int op_ge(int a, int b) { return (a >= b); }
602 static int op_eq(int a, int b) { return (a == b); }
603 static int op_ne(int a, int b) { return (a != b); }
604 static int op_or(int a, int b) { return (a || b); }
605 static int op_and(int a, int b) { return (a && b); }
608 * An evaluation function takes three arguments, as follows: (1) a pointer to
609 * an element of the precedence table which lists the operators at the current
610 * level of precedence; (2) a pointer to an integer which will receive the
611 * value of the expression; and (3) a pointer to a char* that points to the
612 * expression to be evaluated and that is updated to the end of the expression
613 * when evaluation is complete. The function returns LT_FALSE if the value of
614 * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
615 * expression could not be evaluated.
619 typedef Linetype eval_fn(const struct ops *, int *, const char **);
621 static eval_fn eval_table, eval_unary;
624 * The precedence table. Expressions involving binary operators are evaluated
625 * in a table-driven way by eval_table. When it evaluates a subexpression it
626 * calls the inner function with its first argument pointing to the next
627 * element of the table. Innermost expressions have special non-table-driven
630 static const struct ops {
637 { eval_table, { { "||", op_or } } },
638 { eval_table, { { "&&", op_and } } },
639 { eval_table, { { "==", op_eq },
641 { eval_unary, { { "<=", op_le },
648 * Function for evaluating the innermost parts of expressions,
649 * viz. !expr (expr) defined(symbol) symbol number
650 * We reset the keepthis flag when we find a non-constant subexpression.
653 eval_unary(const struct ops *ops, int *valp, const char **cpp)
659 cp = skipcomment(*cpp);
661 debug("eval%td !", ops - eval_ops);
663 if (eval_unary(ops, valp, &cp) == LT_IF)
666 } else if (*cp == '(') {
668 debug("eval%td (", ops - eval_ops);
669 if (eval_table(eval_ops, valp, &cp) == LT_IF)
671 cp = skipcomment(cp);
674 } else if (isdigit((unsigned char)*cp)) {
675 debug("eval%td number", ops - eval_ops);
676 *valp = strtol(cp, &ep, 0);
678 } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
679 cp = skipcomment(cp+7);
680 debug("eval%td defined", ops - eval_ops);
683 cp = skipcomment(cp);
687 *valp = (value[sym] != NULL);
689 cp = skipcomment(cp);
693 } else if (!endsym(*cp)) {
694 debug("eval%td symbol", ops - eval_ops);
698 if (value[sym] == NULL)
701 *valp = strtol(value[sym], &ep, 0);
702 if (*ep != '\0' || ep == value[sym])
708 debug("eval%td bad expr", ops - eval_ops);
713 debug("eval%td = %d", ops - eval_ops, *valp);
714 return (*valp ? LT_TRUE : LT_FALSE);
718 * Table-driven evaluation of binary operators.
721 eval_table(const struct ops *ops, int *valp, const char **cpp)
727 debug("eval%td", ops - eval_ops);
729 if (ops->inner(ops+1, valp, &cp) == LT_IF)
732 cp = skipcomment(cp);
733 for (op = ops->op; op->str != NULL; op++)
734 if (strncmp(cp, op->str, strlen(op->str)) == 0)
738 cp += strlen(op->str);
739 debug("eval%td %s", ops - eval_ops, op->str);
740 if (ops->inner(ops+1, &val, &cp) == LT_IF)
742 *valp = op->fn(*valp, val);
746 debug("eval%td = %d", ops - eval_ops, *valp);
747 return (*valp ? LT_TRUE : LT_FALSE);
751 * Evaluate the expression on a #if or #elif line. If we can work out
752 * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
753 * return just a generic LT_IF.
756 ifeval(const char **cpp)
761 debug("eval %s", *cpp);
762 keepthis = killconsts ? false : true;
763 ret = eval_table(eval_ops, &val, cpp);
764 debug("eval = %d", val);
765 return (keepthis ? LT_IF : ret);
769 * Skip over comments, strings, and character literals and stop at the
770 * next character position that is not whitespace. Between calls we keep
771 * the comment state in the global variable incomment, and we also adjust
772 * the global variable linestate when we see a newline.
773 * XXX: doesn't cope with the buffer splitting inside a state transition.
776 skipcomment(const char *cp)
778 if (text || ignoring[depth]) {
779 for (; isspace((unsigned char)*cp); cp++)
781 linestate = LS_START;
785 /* don't reset to LS_START after a line continuation */
786 if (strncmp(cp, "\\\n", 2) == 0)
788 else switch (incomment) {
790 if (strncmp(cp, "/\\\n", 3) == 0) {
791 incomment = STARTING_COMMENT;
793 } else if (strncmp(cp, "/*", 2) == 0) {
794 incomment = C_COMMENT;
796 } else if (strncmp(cp, "//", 2) == 0) {
797 incomment = CXX_COMMENT;
799 } else if (strncmp(cp, "\'", 1) == 0) {
800 incomment = CHAR_LITERAL;
801 linestate = LS_DIRTY;
803 } else if (strncmp(cp, "\"", 1) == 0) {
804 incomment = STRING_LITERAL;
805 linestate = LS_DIRTY;
807 } else if (strncmp(cp, "\n", 1) == 0) {
808 linestate = LS_START;
810 } else if (strchr(" \t", *cp) != NULL) {
816 if (strncmp(cp, "\n", 1) == 0) {
817 incomment = NO_COMMENT;
818 linestate = LS_START;
824 if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
825 (incomment == STRING_LITERAL && cp[0] == '\"')) {
826 incomment = NO_COMMENT;
828 } else if (cp[0] == '\\') {
833 } else if (strncmp(cp, "\n", 1) == 0) {
834 if (incomment == CHAR_LITERAL)
835 error("unterminated char literal");
837 error("unterminated string literal");
842 if (strncmp(cp, "*\\\n", 3) == 0) {
843 incomment = FINISHING_COMMENT;
845 } else if (strncmp(cp, "*/", 2) == 0) {
846 incomment = NO_COMMENT;
851 case STARTING_COMMENT:
853 incomment = C_COMMENT;
855 } else if (*cp == '/') {
856 incomment = CXX_COMMENT;
859 incomment = NO_COMMENT;
860 linestate = LS_DIRTY;
863 case FINISHING_COMMENT:
865 incomment = NO_COMMENT;
868 incomment = C_COMMENT;
877 * Skip over an identifier.
880 skipsym(const char *cp)
888 * Look for the symbol in the symbol table. If it is found, we return
889 * the symbol table index, else we return -1.
892 findsym(const char *str)
901 printf("%.*s\n", (int)(cp-str), str);
902 /* we don't care about the value of the symbol */
905 for (symind = 0; symind < nsyms; ++symind) {
906 if (strlcmp(symname[symind], str, cp-str) == 0) {
907 debug("findsym %s %s", symname[symind],
908 value[symind] ? value[symind] : "");
916 * Add a symbol to the symbol table.
919 addsym(bool ignorethis, bool definethis, char *sym)
924 symind = findsym(sym);
926 if (nsyms >= MAXSYMS)
927 errx(2, "too many symbols");
930 symname[symind] = sym;
931 ignore[symind] = ignorethis;
932 val = sym + (skipsym(sym) - sym);
935 value[symind] = val+1;
937 } else if (*val == '\0')
944 value[symind] = NULL;
949 * Compare s with n characters of t.
950 * The same as strncmp() except that it checks that s[n] == '\0'.
953 strlcmp(const char *s, const char *t, size_t n)
955 while (n-- && *t != '\0')
957 return ((unsigned char)*s - (unsigned char)*t);
960 return ((unsigned char)*s);
967 debug(const char *msg, ...)
979 error(const char *msg)
982 warnx("%s: %d: %s", filename, linenum, msg);
984 warnx("%s: %d: %s (#if line %d depth %d)",
985 filename, linenum, msg, stifline[depth], depth);
986 errx(2, "output may be truncated");