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