xref: /dragonfly/usr.bin/unifdef/unifdef.c (revision 49781055)
1 /*
2  * Copyright (c) 2002 - 2005 Tony Finch <dot@dotat.at>.  All rights reserved.
3  *
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).
8  *
9  * Copyright (c) 1985, 1993
10  *	The Regents of the University of California.  All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
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.
20  *
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
31  * SUCH DAMAGE.
32  *
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
36  *
37  * $DragonFly: src/usr.bin/unifdef/unifdef.c,v 1.3 2005/07/25 17:51:36 hmp 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 $"
41  */
42 
43 /*
44  * unifdef - remove ifdef'ed lines
45  *
46  *  Wishlist:
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
52  *
53  *   The first two items above require better buffer handling, which would
54  *     also make it possible to handle all "dodgy" directives correctly.
55  */
56 
57 #include <ctype.h>
58 #include <err.h>
59 #include <stdarg.h>
60 #include <stdbool.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 
66 /* types of input lines: */
67 typedef enum {
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 */
76 	LT_ELSE,		/* #else */
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 */
82 	LT_COUNT
83 } Linetype;
84 
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",
92 	"PLAIN", "EOF"
93 };
94 
95 /* state of #if processing */
96 typedef enum {
97 	IS_OUTSIDE,
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 */
107 	IS_COUNT
108 } Ifstate;
109 
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",
114 	"FALSE_TRAILER"
115 };
116 
117 /* state of comment parser */
118 typedef enum {
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 "" */
126 } Comment_state;
127 
128 static char const * const comment_name[] = {
129 	"NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
130 };
131 
132 /* state of preprocessor line parser */
133 typedef enum {
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 */
137 } Line_state;
138 
139 static char const * const linestate_name[] = {
140 	"START", "HASH", "DIRTY"
141 };
142 
143 /*
144  * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
145  */
146 #define	MAXDEPTH        64			/* maximum #if nesting */
147 #define	MAXLINE         4096			/* maximum length of line */
148 #define	MAXSYMS         4096			/* maximum number of symbols */
149 
150 /*
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.
153  */
154 #define	EDITSLOP        10
155 
156 /*
157  * Globals.
158  */
159 
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 */
168 
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 */
173 
174 static FILE            *input;			/* input file pointer */
175 static const char      *filename;		/* input file name */
176 static int              linenum;		/* current line number */
177 
178 static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */
179 static char            *keyword;		/* used for editing #elif's */
180 
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 */
189 
190 static int              exitstat;		/* program exit status */
191 
192 static void             addsym(bool, bool, char *);
193 static void             debug(const char *, ...);
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);
211 
212 #define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')
213 
214 /*
215  * The main program.
216  */
217 int
218 main(int argc, char *argv[])
219 {
220 	int opt;
221 
222 	while ((opt = getopt(argc, argv, "i:D:U:I:cdeklnst")) != -1)
223 		switch (opt) {
224 		case 'i': /* treat stuff controlled by these symbols as text */
225 			/*
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.
229 			 */
230 			opt = *optarg++;
231 			if (opt == 'D')
232 				addsym(true, true, optarg);
233 			else if (opt == 'U')
234 				addsym(true, false, optarg);
235 			else
236 				usage();
237 			break;
238 		case 'D': /* define a symbol */
239 			addsym(false, true, optarg);
240 			break;
241 		case 'U': /* undef a symbol */
242 			addsym(false, false, optarg);
243 			break;
244 		case 'I':
245 			/* no-op for compatibility with cpp */
246 			break;
247 		case 'c': /* treat -D as -U and vice versa */
248 			complement = true;
249 			break;
250 		case 'd':
251 			debugging = true;
252 			break;
253 		case 'e': /* fewer errors from dodgy lines */
254 			iocccok = true;
255 			break;
256 		case 'k': /* process constant #ifs */
257 			killconsts = true;
258 			break;
259 		case 'l': /* blank deleted lines instead of omitting them */
260 			lnblank = true;
261 			break;
262 		case 'n': /* add #line directive after deleted lines */
263 			lnnum = true;
264 			break;
265 		case 's': /* only output list of symbols that control #ifs */
266 			symlist = true;
267 			break;
268 		case 't': /* don't parse C comments */
269 			text = true;
270 			break;
271 		default:
272 			usage();
273 		}
274 	argc -= optind;
275 	argv += optind;
276 	if (argc > 1) {
277 		errx(2, "can only do one file");
278 	} else if (argc == 1 && strcmp(*argv, "-") != 0) {
279 		filename = *argv;
280 		input = fopen(filename, "r");
281 		if (input == NULL)
282 			err(2, "can't open %s", filename);
283 	} else {
284 		filename = "[stdin]";
285 		input = stdin;
286 	}
287 	process();
288 	abort(); /* bug */
289 }
290 
291 static void
292 usage(void)
293 {
294 	fprintf(stderr, "usage: unifdef [-cdeklnst] [-Ipath]"
295 	    " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
296 	exit(2);
297 }
298 
299 /*
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.
303  *
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.
308  *
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.
313  *
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.
318  *
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.
327  */
328 typedef void state_fn(void);
329 
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(); }
365 /* edit this line */
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); }
370 
371 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
372 /* IS_OUTSIDE */
373 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
374   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,
375   print, done },
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,
379   drop,  Eeof },
380 /* IS_TRUE_PREFIX */
381 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
382   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
383   print, Eeof },
384 /* IS_PASS_MIDDLE */
385 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
386   Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,
387   print, Eeof },
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,
391   drop,  Eeof },
392 /* IS_TRUE_MIDDLE */
393 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
394   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
395   print, Eeof },
396 /* IS_PASS_ELSE */
397 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
398   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,
399   print, Eeof },
400 /* IS_FALSE_ELSE */
401 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
402   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
403   drop,  Eeof },
404 /* IS_TRUE_ELSE */
405 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
406   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,
407   print, Eeof },
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,
411   drop,  Eeof }
412 /*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF
413   TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)
414   PLAIN  EOF */
415 };
416 
417 /*
418  * State machine utility functions
419  */
420 static void
421 done(void)
422 {
423 	if (incomment)
424 		error("EOF in comment");
425 	exit(exitstat);
426 }
427 static void
428 ignoreoff(void)
429 {
430 	if (depth == 0)
431 		abort(); /* bug */
432 	ignoring[depth] = ignoring[depth-1];
433 }
434 static void
435 ignoreon(void)
436 {
437 	ignoring[depth] = true;
438 }
439 static void
440 keywordedit(const char *replacement)
441 {
442 	strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
443 	print();
444 }
445 static void
446 nest(void)
447 {
448 	depth += 1;
449 	if (depth >= MAXDEPTH)
450 		error("Too many levels of nesting");
451 	stifline[depth] = linenum;
452 }
453 static void
454 unnest(void)
455 {
456 	if (depth == 0)
457 		abort(); /* bug */
458 	depth -= 1;
459 }
460 static void
461 state(Ifstate is)
462 {
463 	ifstate[depth] = is;
464 }
465 
466 /*
467  * Write a line to the output or not, according to command line options.
468  */
469 static void
470 flushline(bool keep)
471 {
472 	if (symlist)
473 		return;
474 	if (keep ^ complement) {
475 		if (lnnum && delcount > 0)
476 			printf("#line %d\n", linenum);
477 		fputs(tline, stdout);
478 		delcount = 0;
479 	} else {
480 		if (lnblank)
481 			putc('\n', stdout);
482 		exitstat = 1;
483 		delcount += 1;
484 	}
485 }
486 
487 /*
488  * The driver for the state machine.
489  */
490 static void
491 process(void)
492 {
493 	Linetype lineval;
494 
495 	for (;;) {
496 		linenum++;
497 		lineval = getline();
498 		trans_table[ifstate[depth]][lineval]();
499 		debug("process %s -> %s depth %d",
500 		    linetype_name[lineval],
501 		    ifstate_name[ifstate[depth]], depth);
502 	}
503 }
504 
505 /*
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().
509  */
510 static Linetype
511 getline(void)
512 {
513 	const char *cp;
514 	int cursym;
515 	int kwlen;
516 	Linetype retval;
517 	Comment_state wascomment;
518 
519 	if (fgets(tline, MAXLINE, input) == NULL)
520 		return (LT_EOF);
521 	retval = LT_PLAIN;
522 	wascomment = incomment;
523 	cp = skipcomment(tline);
524 	if (linestate == LS_START) {
525 		if (*cp == '#') {
526 			linestate = LS_HASH;
527 			cp = skipcomment(cp + 1);
528 		} else if (*cp != '\0')
529 			linestate = LS_DIRTY;
530 	}
531 	if (!incomment && linestate == LS_HASH) {
532 		keyword = tline + (cp - tline);
533 		cp = skipsym(cp);
534 		kwlen = cp - keyword;
535 		/* no way can we deal with a continuation inside a keyword */
536 		if (strncmp(cp, "\\\n", 2) == 0)
537 			Eioccc();
538 		if (strlcmp("ifdef", keyword, kwlen) == 0 ||
539 		    strlcmp("ifndef", keyword, kwlen) == 0) {
540 			cp = skipcomment(cp);
541 			if ((cursym = findsym(cp)) < 0)
542 				retval = LT_IF;
543 			else {
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;
549 				if (ignore[cursym])
550 					retval = (retval == LT_TRUE)
551 					    ? LT_TRUEI : LT_FALSEI;
552 			}
553 			cp = skipsym(cp);
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)
559 			retval = LT_ELSE;
560 		else if (strlcmp("endif", keyword, kwlen) == 0)
561 			retval = LT_ENDIF;
562 		else {
563 			linestate = LS_DIRTY;
564 			retval = LT_PLAIN;
565 		}
566 		cp = skipcomment(cp);
567 		if (*cp != '\0') {
568 			linestate = LS_DIRTY;
569 			if (retval == LT_TRUE || retval == LT_FALSE ||
570 			    retval == LT_TRUEI || retval == LT_FALSEI)
571 				retval = LT_IF;
572 			if (retval == LT_ELTRUE || retval == LT_ELFALSE)
573 				retval = LT_ELIF;
574 		}
575 		if (retval != LT_PLAIN && (wascomment || incomment)) {
576 			retval += LT_DODGY;
577 			if (incomment)
578 				linestate = LS_DIRTY;
579 		}
580 		/* skipcomment should have changed the state */
581 		if (linestate == LS_HASH)
582 			abort(); /* bug */
583 	}
584 	if (linestate == LS_DIRTY) {
585 		while (*cp != '\0')
586 			cp = skipcomment(cp + 1);
587 	}
588 	debug("parser %s comment %s line",
589 	    comment_name[incomment], linestate_name[linestate]);
590 	return (retval);
591 }
592 
593 /*
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.
597  */
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); }
606 
607 /*
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.
616  */
617 struct ops;
618 
619 typedef Linetype eval_fn(const struct ops *, int *, const char **);
620 
621 static eval_fn eval_table, eval_unary;
622 
623 /*
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
628  * handling.
629  */
630 static const struct ops {
631 	eval_fn *inner;
632 	struct op {
633 		const char *str;
634 		int (*fn)(int, int);
635 	} op[5];
636 } eval_ops[] = {
637 	{ eval_table, { { "||", op_or } } },
638 	{ eval_table, { { "&&", op_and } } },
639 	{ eval_table, { { "==", op_eq },
640 			{ "!=", op_ne } } },
641 	{ eval_unary, { { "<=", op_le },
642 			{ ">=", op_ge },
643 			{ "<", op_lt },
644 			{ ">", op_gt } } }
645 };
646 
647 /*
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.
651  */
652 static Linetype
653 eval_unary(const struct ops *ops, int *valp, const char **cpp)
654 {
655 	const char *cp;
656 	char *ep;
657 	int sym;
658 
659 	cp = skipcomment(*cpp);
660 	if (*cp == '!') {
661 		debug("eval%d !", ops - eval_ops);
662 		cp++;
663 		if (eval_unary(ops, valp, &cp) == LT_IF)
664 			return (LT_IF);
665 		*valp = !*valp;
666 	} else if (*cp == '(') {
667 		cp++;
668 		debug("eval%d (", ops - eval_ops);
669 		if (eval_table(eval_ops, valp, &cp) == LT_IF)
670 			return (LT_IF);
671 		cp = skipcomment(cp);
672 		if (*cp++ != ')')
673 			return (LT_IF);
674 	} else if (isdigit((unsigned char)*cp)) {
675 		debug("eval%d number", ops - eval_ops);
676 		*valp = strtol(cp, &ep, 0);
677 		cp = skipsym(cp);
678 	} else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
679 		cp = skipcomment(cp+7);
680 		debug("eval%d defined", ops - eval_ops);
681 		if (*cp++ != '(')
682 			return (LT_IF);
683 		cp = skipcomment(cp);
684 		sym = findsym(cp);
685 		if (sym < 0)
686 			return (LT_IF);
687 		*valp = (value[sym] != NULL);
688 		cp = skipsym(cp);
689 		cp = skipcomment(cp);
690 		if (*cp++ != ')')
691 			return (LT_IF);
692 		keepthis = false;
693 	} else if (!endsym(*cp)) {
694 		debug("eval%d symbol", ops - eval_ops);
695 		sym = findsym(cp);
696 		if (sym < 0)
697 			return (LT_IF);
698 		if (value[sym] == NULL)
699 			*valp = 0;
700 		else {
701 			*valp = strtol(value[sym], &ep, 0);
702 			if (*ep != '\0' || ep == value[sym])
703 				return (LT_IF);
704 		}
705 		cp = skipsym(cp);
706 		keepthis = false;
707 	} else {
708 		debug("eval%d bad expr", ops - eval_ops);
709 		return (LT_IF);
710 	}
711 
712 	*cpp = cp;
713 	debug("eval%d = %d", ops - eval_ops, *valp);
714 	return (*valp ? LT_TRUE : LT_FALSE);
715 }
716 
717 /*
718  * Table-driven evaluation of binary operators.
719  */
720 static Linetype
721 eval_table(const struct ops *ops, int *valp, const char **cpp)
722 {
723 	const struct op *op;
724 	const char *cp;
725 	int val;
726 
727 	debug("eval%d", ops - eval_ops);
728 	cp = *cpp;
729 	if (ops->inner(ops+1, valp, &cp) == LT_IF)
730 		return (LT_IF);
731 	for (;;) {
732 		cp = skipcomment(cp);
733 		for (op = ops->op; op->str != NULL; op++)
734 			if (strncmp(cp, op->str, strlen(op->str)) == 0)
735 				break;
736 		if (op->str == NULL)
737 			break;
738 		cp += strlen(op->str);
739 		debug("eval%d %s", ops - eval_ops, op->str);
740 		if (ops->inner(ops+1, &val, &cp) == LT_IF)
741 			return (LT_IF);
742 		*valp = op->fn(*valp, val);
743 	}
744 
745 	*cpp = cp;
746 	debug("eval%d = %d", ops - eval_ops, *valp);
747 	return (*valp ? LT_TRUE : LT_FALSE);
748 }
749 
750 /*
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.
754  */
755 static Linetype
756 ifeval(const char **cpp)
757 {
758 	int ret;
759 	int val;
760 
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);
766 }
767 
768 /*
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.
774  */
775 static const char *
776 skipcomment(const char *cp)
777 {
778 	if (text || ignoring[depth]) {
779 		for (; isspace((unsigned char)*cp); cp++)
780 			if (*cp == '\n')
781 				linestate = LS_START;
782 		return (cp);
783 	}
784 	while (*cp != '\0')
785 		/* don't reset to LS_START after a line continuation */
786 		if (strncmp(cp, "\\\n", 2) == 0)
787 			cp += 2;
788 		else switch (incomment) {
789 		case NO_COMMENT:
790 			if (strncmp(cp, "/\\\n", 3) == 0) {
791 				incomment = STARTING_COMMENT;
792 				cp += 3;
793 			} else if (strncmp(cp, "/*", 2) == 0) {
794 				incomment = C_COMMENT;
795 				cp += 2;
796 			} else if (strncmp(cp, "//", 2) == 0) {
797 				incomment = CXX_COMMENT;
798 				cp += 2;
799 			} else if (strncmp(cp, "\'", 1) == 0) {
800 				incomment = CHAR_LITERAL;
801 				linestate = LS_DIRTY;
802 				cp += 1;
803 			} else if (strncmp(cp, "\"", 1) == 0) {
804 				incomment = STRING_LITERAL;
805 				linestate = LS_DIRTY;
806 				cp += 1;
807 			} else if (strncmp(cp, "\n", 1) == 0) {
808 				linestate = LS_START;
809 				cp += 1;
810 			} else if (strchr(" \t", *cp) != NULL) {
811 				cp += 1;
812 			} else
813 				return (cp);
814 			continue;
815 		case CXX_COMMENT:
816 			if (strncmp(cp, "\n", 1) == 0) {
817 				incomment = NO_COMMENT;
818 				linestate = LS_START;
819 			}
820 			cp += 1;
821 			continue;
822 		case CHAR_LITERAL:
823 		case STRING_LITERAL:
824 			if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
825 			    (incomment == STRING_LITERAL && cp[0] == '\"')) {
826 				incomment = NO_COMMENT;
827 				cp += 1;
828 			} else if (cp[0] == '\\') {
829 				if (cp[1] == '\0')
830 					cp += 1;
831 				else
832 					cp += 2;
833 			} else if (strncmp(cp, "\n", 1) == 0) {
834 				if (incomment == CHAR_LITERAL)
835 					error("unterminated char literal");
836 				else
837 					error("unterminated string literal");
838 			} else
839 				cp += 1;
840 			continue;
841 		case C_COMMENT:
842 			if (strncmp(cp, "*\\\n", 3) == 0) {
843 				incomment = FINISHING_COMMENT;
844 				cp += 3;
845 			} else if (strncmp(cp, "*/", 2) == 0) {
846 				incomment = NO_COMMENT;
847 				cp += 2;
848 			} else
849 				cp += 1;
850 			continue;
851 		case STARTING_COMMENT:
852 			if (*cp == '*') {
853 				incomment = C_COMMENT;
854 				cp += 1;
855 			} else if (*cp == '/') {
856 				incomment = CXX_COMMENT;
857 				cp += 1;
858 			} else {
859 				incomment = NO_COMMENT;
860 				linestate = LS_DIRTY;
861 			}
862 			continue;
863 		case FINISHING_COMMENT:
864 			if (*cp == '/') {
865 				incomment = NO_COMMENT;
866 				cp += 1;
867 			} else
868 				incomment = C_COMMENT;
869 			continue;
870 		default:
871 			abort(); /* bug */
872 		}
873 	return (cp);
874 }
875 
876 /*
877  * Skip over an identifier.
878  */
879 static const char *
880 skipsym(const char *cp)
881 {
882 	while (!endsym(*cp))
883 		++cp;
884 	return (cp);
885 }
886 
887 /*
888  * Look for the symbol in the symbol table. If is is found, we return
889  * the symbol table index, else we return -1.
890  */
891 static int
892 findsym(const char *str)
893 {
894 	const char *cp;
895 	int symind;
896 
897 	cp = skipsym(str);
898 	if (cp == str)
899 		return (-1);
900 	if (symlist) {
901 		printf("%.*s\n", (int)(cp-str), str);
902 		/* we don't care about the value of the symbol */
903 		return (0);
904 	}
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] : "");
909 			return (symind);
910 		}
911 	}
912 	return (-1);
913 }
914 
915 /*
916  * Add a symbol to the symbol table.
917  */
918 static void
919 addsym(bool ignorethis, bool definethis, char *sym)
920 {
921 	int symind;
922 	char *val;
923 
924 	symind = findsym(sym);
925 	if (symind < 0) {
926 		if (nsyms >= MAXSYMS)
927 			errx(2, "too many symbols");
928 		symind = nsyms++;
929 	}
930 	symname[symind] = sym;
931 	ignore[symind] = ignorethis;
932 	val = sym + (skipsym(sym) - sym);
933 	if (definethis) {
934 		if (*val == '=') {
935 			value[symind] = val+1;
936 			*val = '\0';
937 		} else if (*val == '\0')
938 			value[symind] = "";
939 		else
940 			usage();
941 	} else {
942 		if (*val != '\0')
943 			usage();
944 		value[symind] = NULL;
945 	}
946 }
947 
948 /*
949  * Compare s with n characters of t.
950  * The same as strncmp() except that it checks that s[n] == '\0'.
951  */
952 static int
953 strlcmp(const char *s, const char *t, size_t n)
954 {
955 	while (n-- && *t != '\0')
956 		if (*s != *t)
957 			return ((unsigned char)*s - (unsigned char)*t);
958 		else
959 			++s, ++t;
960 	return ((unsigned char)*s);
961 }
962 
963 /*
964  * Diagnostics.
965  */
966 static void
967 debug(const char *msg, ...)
968 {
969 	va_list ap;
970 
971 	if (debugging) {
972 		va_start(ap, msg);
973 		vwarnx(msg, ap);
974 		va_end(ap);
975 	}
976 }
977 
978 static void
979 error(const char *msg)
980 {
981 	if (depth == 0)
982 		warnx("%s: %d: %s", filename, linenum, msg);
983 	else
984 		warnx("%s: %d: %s (#if line %d depth %d)",
985 		    filename, linenum, msg, stifline[depth], depth);
986 	errx(2, "output may be truncated");
987 }
988