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