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