xref: /dflybsd-src/usr.bin/unifdef/unifdef.c (revision c6cf4f8f1ebc9e3fe2a8c566f08adfc86122c7bf)
1 /*
2  * Copyright (c) 1985, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Dave Yost. Support for #if and #elif was added by Tony Finch.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#) Copyright (c) 1985, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)unifdef.c	8.1 (Berkeley) 6/6/93
38  * $NetBSD: unifdef.c,v 1.8 2000/07/03 02:51:36 matt Exp $
39  * $dotat: things/unifdef.c,v 1.148 2003/01/20 12:05:41 fanf2 Exp $
40  * $FreeBSD: src/usr.bin/unifdef/unifdef.c,v 1.4.2.5 2003/01/29 21:46:39 fanf Exp $
41  * $DragonFly: src/usr.bin/unifdef/unifdef.c,v 1.2 2003/06/17 04:29:33 dillon Exp $
42  */
43 
44 #include <sys/cdefs.h>
45 
46 /*
47  * unifdef - remove ifdef'ed lines
48  *
49  *  Wishlist:
50  *      provide an option which will append the name of the
51  *        appropriate symbol after #else's and #endif's
52  *      provide an option which will check symbols after
53  *        #else's and #endif's to see that they match their
54  *        corresponding #ifdef or #ifndef
55  *      generate #line directives in place of deleted code
56  *
57  *   The first two items above require better buffer handling, which would
58  *     also make it possible to handle all "dodgy" directives correctly.
59  */
60 
61 #include <ctype.h>
62 #include <err.h>
63 #include <stdarg.h>
64 #include <stdbool.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 
70 /* types of input lines: */
71 typedef enum {
72 	LT_TRUEI,		/* a true #if with ignore flag */
73 	LT_FALSEI,		/* a false #if with ignore flag */
74 	LT_IF,			/* an unknown #if */
75 	LT_TRUE,		/* a true #if */
76 	LT_FALSE,		/* a false #if */
77 	LT_ELIF,		/* an unknown #elif */
78 	LT_ELTRUE,		/* a true #elif */
79 	LT_ELFALSE,		/* a false #elif */
80 	LT_ELSE,		/* #else */
81 	LT_ENDIF,		/* #endif */
82 	LT_DODGY,		/* flag: directive is not on one line */
83 	LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
84 	LT_PLAIN,		/* ordinary line */
85 	LT_EOF,			/* end of file */
86 	LT_COUNT
87 } Linetype;
88 
89 static char const * const linetype_name[] = {
90 	"TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
91 	"ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
92 	"DODGY TRUEI", "DODGY FALSEI",
93 	"DODGY IF", "DODGY TRUE", "DODGY FALSE",
94 	"DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
95 	"DODGY ELSE", "DODGY ENDIF",
96 	"PLAIN", "EOF"
97 };
98 
99 /* state of #if processing */
100 typedef enum {
101 	IS_OUTSIDE,
102 	IS_FALSE_PREFIX,	/* false #if followed by false #elifs */
103 	IS_TRUE_PREFIX,		/* first non-false #(el)if is true */
104 	IS_PASS_MIDDLE,		/* first non-false #(el)if is unknown */
105 	IS_FALSE_MIDDLE,	/* a false #elif after a pass state */
106 	IS_TRUE_MIDDLE,		/* a true #elif after a pass state */
107 	IS_PASS_ELSE,		/* an else after a pass state */
108 	IS_FALSE_ELSE,		/* an else after a true state */
109 	IS_TRUE_ELSE,		/* an else after only false states */
110 	IS_FALSE_TRAILER,	/* #elifs after a true are false */
111 	IS_COUNT
112 } Ifstate;
113 
114 static char const * const ifstate_name[] = {
115 	"OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
116 	"PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
117 	"PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
118 	"FALSE_TRAILER"
119 };
120 
121 /* state of comment parser */
122 typedef enum {
123 	NO_COMMENT = false,	/* outside a comment */
124 	C_COMMENT,		/* in a comment like this one */
125 	CXX_COMMENT,		/* between // and end of line */
126 	STARTING_COMMENT,	/* just after slash-backslash-newline */
127 	FINISHING_COMMENT	/* star-backslash-newline in a C comment */
128 } Comment_state;
129 
130 static char const * const comment_name[] = {
131 	"NO", "C", "CXX", "STARTING", "FINISHING"
132 };
133 
134 /* state of preprocessor line parser */
135 typedef enum {
136 	LS_START,		/* only space and comments on this line */
137 	LS_HASH,		/* only space, comments, and a hash */
138 	LS_DIRTY		/* this line can't be a preprocessor line */
139 } Line_state;
140 
141 static char const * const linestate_name[] = {
142 	"START", "HASH", "DIRTY"
143 };
144 
145 /*
146  * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
147  */
148 #define	MAXDEPTH        64			/* maximum #if nesting */
149 #define	MAXLINE         4096			/* maximum length of line */
150 #define	MAXSYMS         4096			/* maximum number of symbols */
151 
152 /*
153  * Sometimes when editing a keyword the replacement text is longer, so
154  * we leave some space at the end of the tline buffer to accommodate this.
155  */
156 #define	EDITSLOP        10
157 
158 /*
159  * Globals.
160  */
161 
162 static bool             complement;		/* -c: do the complement */
163 static bool             debugging;		/* -d: debugging reports */
164 static bool             iocccok;		/* -e: fewer IOCCC errors */
165 static bool             killconsts;		/* -k: eval constant #ifs */
166 static bool             lnblank;		/* -l: blank deleted lines */
167 static bool             symlist;		/* -s: output symbol list */
168 static bool             text;			/* -t: this is a text file */
169 
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 */
174 
175 static FILE            *input;			/* input file pointer */
176 static const char      *filename;		/* input file name */
177 static int              linenum;		/* current line number */
178 
179 static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */
180 static char            *keyword;		/* used for editing #elif's */
181 
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 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             error(const char *);
195 static int              findsym(const char *);
196 static void             flushline(bool);
197 static Linetype         getline(void);
198 static Linetype         ifeval(const char **);
199 static void             ignoreoff(void);
200 static void             ignoreon(void);
201 static void             keywordedit(const char *);
202 static void             nest(void);
203 static void             process(void);
204 static const char      *skipcomment(const char *);
205 static const char      *skipsym(const char *);
206 static void             state(Ifstate);
207 static int              strlcmp(const char *, const char *, size_t);
208 static void             usage(void);
209 
210 #define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')
211 
212 /*
213  * The main program.
214  */
215 int
216 main(int argc, char *argv[])
217 {
218 	int opt;
219 
220 	while ((opt = getopt(argc, argv, "i:D:U:I:cdeklst")) != -1)
221 		switch (opt) {
222 		case 'i': /* treat stuff controlled by these symbols as text */
223 			/*
224 			 * For strict backwards-compatibility the U or D
225 			 * should be immediately after the -i but it doesn't
226 			 * matter much if we relax that requirement.
227 			 */
228 			opt = *optarg++;
229 			if (opt == 'D')
230 				addsym(true, true, optarg);
231 			else if (opt == 'U')
232 				addsym(true, false, optarg);
233 			else
234 				usage();
235 			break;
236 		case 'D': /* define a symbol */
237 			addsym(false, true, optarg);
238 			break;
239 		case 'U': /* undef a symbol */
240 			addsym(false, false, optarg);
241 			break;
242 		case 'I':
243 			/* no-op for compatibility with cpp */
244 			break;
245 		case 'c': /* treat -D as -U and vice versa */
246 			complement = true;
247 			break;
248 		case 'd':
249 			debugging = true;
250 			break;
251 		case 'e': /* fewer errors from dodgy lines */
252 			iocccok = true;
253 			break;
254 		case 'k': /* process constant #ifs */
255 			killconsts = true;
256 			break;
257 		case 'l': /* blank deleted lines instead of omitting them */
258 			lnblank = true;
259 			break;
260 		case 's': /* only output list of symbols that control #ifs */
261 			symlist = true;
262 			break;
263 		case 't': /* don't parse C comments */
264 			text = true;
265 			break;
266 		default:
267 			usage();
268 		}
269 	argc -= optind;
270 	argv += optind;
271 	if (nsyms == 0 && !symlist) {
272 		warnx("must -D or -U at least one symbol");
273 		usage();
274 	}
275 	if (argc > 1) {
276 		errx(2, "can only do one file");
277 	} else if (argc == 1 && strcmp(*argv, "-") != 0) {
278 		filename = *argv;
279 		if ((input = fopen(filename, "r")) != NULL) {
280 			process();
281 			(void) fclose(input);
282 		} else
283 			err(2, "can't open %s", *argv);
284 	} else {
285 		filename = "[stdin]";
286 		input = stdin;
287 		process();
288 	}
289 
290 	exit(exitstat);
291 }
292 
293 static void
294 usage(void)
295 {
296 	fprintf(stderr, "usage: unifdef [-cdeklst]"
297 	    " [[-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym]] ... [file]\n");
298 	exit(2);
299 }
300 
301 /*
302  * A state transition function alters the global #if processing state
303  * in a particular way. The table below is indexed by the current
304  * processing state and the type of the current line. A NULL entry
305  * indicate that processing is complete.
306  *
307  * Nesting is handled by keeping a stack of states; some transition
308  * functions increase or decrease the depth. They also maintain the
309  * ignore state on a stack. In some complicated cases they have to
310  * alter the preprocessor directive, as follows.
311  *
312  * When we have processed a group that starts off with a known-false
313  * #if/#elif sequence (which has therefore been deleted) followed by a
314  * #elif that we don't understand and therefore must keep, we edit the
315  * latter into a #if to keep the nesting correct.
316  *
317  * When we find a true #elif in a group, the following block will
318  * always be kept and the rest of the sequence after the next #elif or
319  * #else will be discarded. We edit the #elif into a #else and the
320  * following directive to #endif since this has the desired behaviour.
321  *
322  * "Dodgy" directives are split across multiple lines, the most common
323  * example being a multi-line comment hanging off the right of the
324  * directive. We can handle them correctly only if there is no change
325  * from printing to dropping (or vice versa) caused by that directive.
326  * If the directive is the first of a group we have a choice between
327  * failing with an error, or passing it through unchanged instead of
328  * evaluating it. The latter is not the default to avoid questions from
329  * users about unifdef unexpectedly leaving behind preprocessor directives.
330  */
331 typedef void state_fn(void);
332 
333 /* report an error */
334 static void Eelif (void) { error("Inappropriate #elif"); }
335 static void Eelse (void) { error("Inappropriate #else"); }
336 static void Eendif(void) { error("Inappropriate #endif"); }
337 static void Eeof  (void) { error("Premature EOF"); }
338 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
339 /* plain line handling */
340 static void print (void) { flushline(true); }
341 static void drop  (void) { flushline(false); }
342 /* output lacks group's start line */
343 static void Strue (void) { drop();  ignoreoff(); state(IS_TRUE_PREFIX); }
344 static void Sfalse(void) { drop();  ignoreoff(); state(IS_FALSE_PREFIX); }
345 static void Selse (void) { drop();               state(IS_TRUE_ELSE); }
346 /* print/pass this block */
347 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
348 static void Pelse (void) { print();              state(IS_PASS_ELSE); }
349 static void Pendif(void) { print(); --depth; }
350 /* discard this block */
351 static void Dfalse(void) { drop();  ignoreoff(); state(IS_FALSE_TRAILER); }
352 static void Delif (void) { drop();  ignoreoff(); state(IS_FALSE_MIDDLE); }
353 static void Delse (void) { drop();               state(IS_FALSE_ELSE); }
354 static void Dendif(void) { drop();  --depth; }
355 /* first line of group */
356 static void Fdrop (void) { nest();  Dfalse(); }
357 static void Fpass (void) { nest();  Pelif(); }
358 static void Ftrue (void) { nest();  Strue(); }
359 static void Ffalse(void) { nest();  Sfalse(); }
360 /* variable pedantry for obfuscated lines */
361 static void Oiffy (void) { if (iocccok) Fpass(); else Eioccc(); ignoreon(); }
362 static void Oif   (void) { if (iocccok) Fpass(); else Eioccc(); }
363 static void Oelif (void) { if (iocccok) Pelif(); else Eioccc(); }
364 /* ignore comments in this block */
365 static void Idrop (void) { Fdrop();  ignoreon(); }
366 static void Itrue (void) { Ftrue();  ignoreon(); }
367 static void Ifalse(void) { Ffalse(); ignoreon(); }
368 /* edit this line */
369 static void Mpass (void) { strncpy(keyword, "if  ", 4); Pelif(); }
370 static void Mtrue (void) { keywordedit("else\n");  state(IS_TRUE_MIDDLE); }
371 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
372 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
373 
374 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
375 /* IS_OUTSIDE */
376 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
377   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,
378   print, NULL },
379 /* IS_FALSE_PREFIX */
380 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
381   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
382   drop,  Eeof },
383 /* IS_TRUE_PREFIX */
384 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
385   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
386   print, Eeof },
387 /* IS_PASS_MIDDLE */
388 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
389   Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,
390   print, Eeof },
391 /* IS_FALSE_MIDDLE */
392 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
393   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
394   drop,  Eeof },
395 /* IS_TRUE_MIDDLE */
396 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
397   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
398   print, Eeof },
399 /* IS_PASS_ELSE */
400 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
401   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,
402   print, Eeof },
403 /* IS_FALSE_ELSE */
404 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
405   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
406   drop,  Eeof },
407 /* IS_TRUE_ELSE */
408 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
409   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,
410   print, Eeof },
411 /* IS_FALSE_TRAILER */
412 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
413   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
414   drop,  Eeof }
415 /*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF
416   TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)
417   PLAIN  EOF */
418 };
419 
420 /*
421  * State machine utility functions
422  */
423 static void
424 ignoreoff(void)
425 {
426 	ignoring[depth] = ignoring[depth-1];
427 }
428 static void
429 ignoreon(void)
430 {
431 	ignoring[depth] = true;
432 }
433 static void
434 keywordedit(const char *replacement)
435 {
436 	strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
437 	print();
438 }
439 static void
440 nest(void)
441 {
442 	depth += 1;
443 	if (depth >= MAXDEPTH)
444 		error("Too many levels of nesting");
445 	stifline[depth] = linenum;
446 }
447 static void
448 state(Ifstate is)
449 {
450 	ifstate[depth] = is;
451 }
452 
453 /*
454  * Write a line to the output or not, according to command line options.
455  */
456 static void
457 flushline(bool keep)
458 {
459 	if (symlist)
460 		return;
461 	if (keep ^ complement)
462 		fputs(tline, stdout);
463 	else {
464 		if (lnblank)
465 			putc('\n', stdout);
466 		exitstat = 1;
467 	}
468 }
469 
470 /*
471  * The driver for the state machine.
472  */
473 static void
474 process(void)
475 {
476 	Linetype lineval;
477 	state_fn *trans;
478 
479 	for (;;) {
480 		linenum++;
481 		lineval = getline();
482 		trans = trans_table[ifstate[depth]][lineval];
483 		if (trans == NULL)
484 			break;
485 		trans();
486 		debug("process %s -> %s depth %d",
487 		    linetype_name[lineval],
488 		    ifstate_name[ifstate[depth]], depth);
489 	}
490 	if (incomment)
491 		error("EOF in comment");
492 }
493 
494 /*
495  * Parse a line and determine its type. We keep the preprocessor line
496  * parser state between calls in a global variable.
497  */
498 static Linetype
499 getline(void)
500 {
501 	const char *cp;
502 	int cursym;
503 	int kwlen;
504 	Linetype retval;
505 	Comment_state wascomment;
506 
507 	if (fgets(tline, MAXLINE, input) == NULL)
508 		return (LT_EOF);
509 	retval = LT_PLAIN;
510 	wascomment = incomment;
511 	cp = skipcomment(tline);
512 	if (linestate == LS_START) {
513 		if (*cp == '#') {
514 			linestate = LS_HASH;
515 			cp = skipcomment(cp + 1);
516 		} else if (*cp != '\0')
517 			linestate = LS_DIRTY;
518 	}
519 	if (!incomment && linestate == LS_HASH) {
520 		keyword = tline + (cp - tline);
521 		cp = skipsym(cp);
522 		kwlen = cp - keyword;
523 		/* no way can we deal with a continuation inside a keyword */
524 		if (strncmp(cp, "\\\n", 2) == 0)
525 			Eioccc();
526 		if (strlcmp("ifdef", keyword, kwlen) == 0 ||
527 		    strlcmp("ifndef", keyword, kwlen) == 0) {
528 			cp = skipcomment(cp);
529 			if ((cursym = findsym(cp)) < 0)
530 				retval = LT_IF;
531 			else {
532 				retval = (keyword[2] == 'n')
533 				    ? LT_FALSE : LT_TRUE;
534 				if (value[cursym] == NULL)
535 					retval = (retval == LT_TRUE)
536 					    ? LT_FALSE : LT_TRUE;
537 				if (ignore[cursym])
538 					retval = (retval == LT_TRUE)
539 					    ? LT_TRUEI : LT_FALSEI;
540 			}
541 			cp = skipsym(cp);
542 		} else if (strlcmp("if", keyword, kwlen) == 0)
543 			retval = ifeval(&cp);
544 		else if (strlcmp("elif", keyword, kwlen) == 0)
545 			retval = ifeval(&cp) - LT_IF + LT_ELIF;
546 		else if (strlcmp("else", keyword, kwlen) == 0)
547 			retval = LT_ELSE;
548 		else if (strlcmp("endif", keyword, kwlen) == 0)
549 			retval = LT_ENDIF;
550 		else {
551 			linestate = LS_DIRTY;
552 			retval = LT_PLAIN;
553 		}
554 		cp = skipcomment(cp);
555 		if (*cp != '\0') {
556 			linestate = LS_DIRTY;
557 			if (retval == LT_TRUE || retval == LT_FALSE ||
558 			    retval == LT_TRUEI || retval == LT_FALSEI)
559 				retval = LT_IF;
560 			if (retval == LT_ELTRUE || retval == LT_ELFALSE)
561 				retval = LT_ELIF;
562 		}
563 		if (retval != LT_PLAIN && (wascomment || incomment)) {
564 			retval += LT_DODGY;
565 			if (incomment)
566 				linestate = LS_DIRTY;
567 		}
568 		/* skipcomment should have changed the state */
569 		if (linestate == LS_HASH)
570 			abort(); /* bug */
571 	}
572 	if (linestate == LS_DIRTY) {
573 		while (*cp != '\0')
574 			cp = skipcomment(cp + 1);
575 	}
576 	debug("parser %s comment %s line",
577 	    comment_name[incomment], linestate_name[linestate]);
578 	return (retval);
579 }
580 
581 /*
582  * These are the operators that are supported by the expression evaluator.
583  */
584 static int op_lt(int a, int b) { return (a < b); }
585 static int op_gt(int a, int b) { return (a > b); }
586 static int op_le(int a, int b) { return (a <= b); }
587 static int op_ge(int a, int b) { return (a >= b); }
588 static int op_eq(int a, int b) { return (a == b); }
589 static int op_ne(int a, int b) { return (a != b); }
590 static int op_or(int a, int b) { return (a || b); }
591 static int op_and(int a, int b) { return (a && b); }
592 
593 /*
594  * An evaluation function takes three arguments, as follows: (1) a pointer to
595  * an element of the precedence table which lists the operators at the current
596  * level of precedence; (2) a pointer to an integer which will receive the
597  * value of the expression; and (3) a pointer to a char* that points to the
598  * expression to be evaluated and that is updated to the end of the expression
599  * when evaluation is complete. The function returns LT_FALSE if the value of
600  * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
601  * expression could not be evaluated.
602  */
603 struct ops;
604 
605 typedef Linetype eval_fn(const struct ops *, int *, const char **);
606 
607 static eval_fn eval_table, eval_unary;
608 
609 /*
610  * The precedence table. Expressions involving binary operators are evaluated
611  * in a table-driven way by eval_table. When it evaluates a subexpression it
612  * calls the inner function with its first argument pointing to the next
613  * element of the table. Innermost expressions have special non-table-driven
614  * handling.
615  */
616 static const struct ops {
617 	eval_fn *inner;
618 	struct op {
619 		const char *str;
620 		int (*fn)(int, int);
621 	} op[5];
622 } eval_ops[] = {
623 	{ eval_table, { { "||", op_or } } },
624 	{ eval_table, { { "&&", op_and } } },
625 	{ eval_table, { { "==", op_eq },
626 			{ "!=", op_ne } } },
627 	{ eval_unary, { { "<=", op_le },
628 			{ ">=", op_ge },
629 			{ "<", op_lt },
630 			{ ">", op_gt } } }
631 };
632 
633 /*
634  * Function for evaluating the innermost parts of expressions,
635  * viz. !expr (expr) defined(symbol) symbol number
636  * We reset the keepthis flag when we find a non-constant subexpression.
637  */
638 static Linetype
639 eval_unary(const struct ops *ops, int *valp, const char **cpp)
640 {
641 	const char *cp;
642 	char *ep;
643 	int sym;
644 
645 	cp = skipcomment(*cpp);
646 	if (*cp == '!') {
647 		debug("eval%d !", ops - eval_ops);
648 		cp++;
649 		if (eval_unary(ops, valp, &cp) == LT_IF)
650 			return (LT_IF);
651 		*valp = !*valp;
652 	} else if (*cp == '(') {
653 		cp++;
654 		debug("eval%d (", ops - eval_ops);
655 		if (eval_table(eval_ops, valp, &cp) == LT_IF)
656 			return (LT_IF);
657 		cp = skipcomment(cp);
658 		if (*cp++ != ')')
659 			return (LT_IF);
660 	} else if (isdigit((unsigned char)*cp)) {
661 		debug("eval%d number", ops - eval_ops);
662 		*valp = strtol(cp, &ep, 0);
663 		cp = skipsym(cp);
664 	} else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
665 		cp = skipcomment(cp+7);
666 		debug("eval%d defined", ops - eval_ops);
667 		if (*cp++ != '(')
668 			return (LT_IF);
669 		cp = skipcomment(cp);
670 		sym = findsym(cp);
671 		if (sym < 0 && !symlist)
672 			return (LT_IF);
673 		*valp = (value[sym] != NULL);
674 		cp = skipsym(cp);
675 		cp = skipcomment(cp);
676 		if (*cp++ != ')')
677 			return (LT_IF);
678 		keepthis = false;
679 	} else if (!endsym(*cp)) {
680 		debug("eval%d symbol", ops - eval_ops);
681 		sym = findsym(cp);
682 		if (sym < 0 && !symlist)
683 			return (LT_IF);
684 		if (value[sym] == NULL)
685 			*valp = 0;
686 		else {
687 			*valp = strtol(value[sym], &ep, 0);
688 			if (*ep != '\0' || ep == value[sym])
689 				return (LT_IF);
690 		}
691 		cp = skipsym(cp);
692 		keepthis = false;
693 	} else
694 		return (LT_IF);
695 
696 	*cpp = cp;
697 	debug("eval%d = %d", ops - eval_ops, *valp);
698 	return (*valp ? LT_TRUE : LT_FALSE);
699 }
700 
701 /*
702  * Table-driven evaluation of binary operators.
703  */
704 static Linetype
705 eval_table(const struct ops *ops, int *valp, const char **cpp)
706 {
707 	const struct op *op;
708 	const char *cp;
709 	int val;
710 
711 	debug("eval%d", ops - eval_ops);
712 	cp = *cpp;
713 	if (ops->inner(ops+1, valp, &cp) == LT_IF)
714 		return (LT_IF);
715 	for (;;) {
716 		cp = skipcomment(cp);
717 		for (op = ops->op; op->str != NULL; op++)
718 			if (strncmp(cp, op->str, strlen(op->str)) == 0)
719 				break;
720 		if (op->str == NULL)
721 			break;
722 		cp += strlen(op->str);
723 		debug("eval%d %s", ops - eval_ops, op->str);
724 		if (ops->inner(ops+1, &val, &cp) == LT_IF)
725 			return (LT_IF);
726 		*valp = op->fn(*valp, val);
727 	}
728 
729 	*cpp = cp;
730 	debug("eval%d = %d", ops - eval_ops, *valp);
731 	return (*valp ? LT_TRUE : LT_FALSE);
732 }
733 
734 /*
735  * Evaluate the expression on a #if or #elif line. If we can work out
736  * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
737  * return just a generic LT_IF.
738  */
739 static Linetype
740 ifeval(const char **cpp)
741 {
742 	int ret;
743 	int val;
744 
745 	debug("eval %s", *cpp);
746 	keepthis = killconsts ? false : true;
747 	ret = eval_table(eval_ops, &val, cpp);
748 	return (keepthis ? LT_IF : ret);
749 }
750 
751 /*
752  * Skip over comments and stop at the next character position that is
753  * not whitespace. Between calls we keep the comment state in a global
754  * variable, and we also make a note when we get a proper end-of-line.
755  * XXX: doesn't cope with the buffer splitting inside a state transition.
756  */
757 static const char *
758 skipcomment(const char *cp)
759 {
760 	if (text || ignoring[depth]) {
761 		while (isspace((unsigned char)*cp))
762 			cp += 1;
763 		return (cp);
764 	}
765 	while (*cp != '\0')
766 		if (strncmp(cp, "\\\n", 2) == 0)
767 			cp += 2;
768 		else switch (incomment) {
769 		case NO_COMMENT:
770 			if (strncmp(cp, "/\\\n", 3) == 0) {
771 				incomment = STARTING_COMMENT;
772 				cp += 3;
773 			} else if (strncmp(cp, "/*", 2) == 0) {
774 				incomment = C_COMMENT;
775 				cp += 2;
776 			} else if (strncmp(cp, "//", 2) == 0) {
777 				incomment = CXX_COMMENT;
778 				cp += 2;
779 			} else if (strncmp(cp, "\n", 1) == 0) {
780 				linestate = LS_START;
781 				cp += 1;
782 			} else if (strchr(" \t", *cp) != NULL) {
783 				cp += 1;
784 			} else
785 				return (cp);
786 			continue;
787 		case CXX_COMMENT:
788 			if (strncmp(cp, "\n", 1) == 0) {
789 				incomment = NO_COMMENT;
790 				linestate = LS_START;
791 			}
792 			cp += 1;
793 			continue;
794 		case C_COMMENT:
795 			if (strncmp(cp, "*\\\n", 3) == 0) {
796 				incomment = FINISHING_COMMENT;
797 				cp += 3;
798 			} else if (strncmp(cp, "*/", 2) == 0) {
799 				incomment = NO_COMMENT;
800 				cp += 2;
801 			} else
802 				cp += 1;
803 			continue;
804 		case STARTING_COMMENT:
805 			if (*cp == '*') {
806 				incomment = C_COMMENT;
807 				cp += 1;
808 			} else if (*cp == '/') {
809 				incomment = CXX_COMMENT;
810 				cp += 1;
811 			} else {
812 				incomment = NO_COMMENT;
813 				linestate = LS_DIRTY;
814 			}
815 			continue;
816 		case FINISHING_COMMENT:
817 			if (*cp == '/') {
818 				incomment = NO_COMMENT;
819 				cp += 1;
820 			} else
821 				incomment = C_COMMENT;
822 			continue;
823 		default:
824 			/* bug */
825 			abort();
826 		}
827 	return (cp);
828 }
829 
830 /*
831  * Skip over an identifier.
832  */
833 static const char *
834 skipsym(const char *cp)
835 {
836 	while (!endsym(*cp))
837 		++cp;
838 	return (cp);
839 }
840 
841 /*
842  * Look for the symbol in the symbol table. If is is found, we return
843  * the symbol table index, else we return -1.
844  */
845 static int
846 findsym(const char *str)
847 {
848 	const char *cp;
849 	int symind;
850 
851 	cp = skipsym(str);
852 	if (cp == str)
853 		return (-1);
854 	if (symlist)
855 		printf("%.*s\n", (int)(cp-str), str);
856 	for (symind = 0; symind < nsyms; ++symind) {
857 		if (strlcmp(symname[symind], str, cp-str) == 0) {
858 			debug("findsym %s %s", symname[symind],
859 			    value[symind] ? value[symind] : "");
860 			return (symind);
861 		}
862 	}
863 	return (-1);
864 }
865 
866 /*
867  * Add a symbol to the symbol table.
868  */
869 static void
870 addsym(bool ignorethis, bool definethis, char *sym)
871 {
872 	int symind;
873 	char *val;
874 
875 	symind = findsym(sym);
876 	if (symind < 0) {
877 		if (nsyms >= MAXSYMS)
878 			errx(2, "too many symbols");
879 		symind = nsyms++;
880 	}
881 	symname[symind] = sym;
882 	ignore[symind] = ignorethis;
883 	val = sym + (skipsym(sym) - sym);
884 	if (definethis) {
885 		if (*val == '=') {
886 			value[symind] = val+1;
887 			*val = '\0';
888 		} else if (*val == '\0')
889 			value[symind] = "";
890 		else
891 			usage();
892 	} else {
893 		if (*val != '\0')
894 			usage();
895 		value[symind] = NULL;
896 	}
897 }
898 
899 /*
900  * Compare s with n characters of t.
901  * The same as strncmp() except that it checks that s[n] == '\0'.
902  */
903 static int
904 strlcmp(const char *s, const char *t, size_t n)
905 {
906 	while (n-- && *t != '\0')
907 		if (*s != *t)
908 			return ((unsigned char)*s - (unsigned char)*t);
909 		else
910 			++s, ++t;
911 	return ((unsigned char)*s);
912 }
913 
914 /*
915  * Diagnostics.
916  */
917 static void
918 debug(const char *msg, ...)
919 {
920 	va_list ap;
921 
922 	if (debugging) {
923 		va_start(ap, msg);
924 		vwarnx(msg, ap);
925 		va_end(ap);
926 	}
927 }
928 
929 static void
930 error(const char *msg)
931 {
932 	if (depth == 0)
933 		warnx("%s: %d: %s", filename, linenum, msg);
934 	else
935 		warnx("%s: %d: %s (#if line %d depth %d)",
936 		    filename, linenum, msg, stifline[depth], depth);
937 	errx(2, "output may be truncated");
938 }
939