]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - usr.bin/unifdef/unifdef.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / usr.bin / unifdef / unifdef.c
1 /*
2  * Copyright (c) 2002 - 2008 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 is 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
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.178 2008/03/02 22:23:32 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 normally changes the state, except
590                    if the last line of the file lacks a newline, or
591                    if there is too much whitespace in a directive */
592                 if (linestate == LS_HASH) {
593                         size_t len = cp - tline;
594                         if (fgets(tline + len, MAXLINE - len, input) == NULL) {
595                                 /* append the missing newline */
596                                 tline[len+0] = '\n';
597                                 tline[len+1] = '\0';
598                                 cp++;
599                                 linestate = LS_START;
600                         } else {
601                                 linestate = LS_DIRTY;
602                         }
603                 }
604         }
605         if (linestate == LS_DIRTY) {
606                 while (*cp != '\0')
607                         cp = skipcomment(cp + 1);
608         }
609         debug("parser %s comment %s line",
610             comment_name[incomment], linestate_name[linestate]);
611         return (retval);
612 }
613
614 /*
615  * These are the binary operators that are supported by the expression
616  * evaluator. Note that if support for division is added then we also
617  * need short-circuiting booleans because of divide-by-zero.
618  */
619 static int op_lt(int a, int b) { return (a < b); }
620 static int op_gt(int a, int b) { return (a > b); }
621 static int op_le(int a, int b) { return (a <= b); }
622 static int op_ge(int a, int b) { return (a >= b); }
623 static int op_eq(int a, int b) { return (a == b); }
624 static int op_ne(int a, int b) { return (a != b); }
625 static int op_or(int a, int b) { return (a || b); }
626 static int op_and(int a, int b) { return (a && b); }
627
628 /*
629  * An evaluation function takes three arguments, as follows: (1) a pointer to
630  * an element of the precedence table which lists the operators at the current
631  * level of precedence; (2) a pointer to an integer which will receive the
632  * value of the expression; and (3) a pointer to a char* that points to the
633  * expression to be evaluated and that is updated to the end of the expression
634  * when evaluation is complete. The function returns LT_FALSE if the value of
635  * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
636  * expression could not be evaluated.
637  */
638 struct ops;
639
640 typedef Linetype eval_fn(const struct ops *, int *, const char **);
641
642 static eval_fn eval_table, eval_unary;
643
644 /*
645  * The precedence table. Expressions involving binary operators are evaluated
646  * in a table-driven way by eval_table. When it evaluates a subexpression it
647  * calls the inner function with its first argument pointing to the next
648  * element of the table. Innermost expressions have special non-table-driven
649  * handling.
650  */
651 static const struct ops {
652         eval_fn *inner;
653         struct op {
654                 const char *str;
655                 int (*fn)(int, int);
656         } op[5];
657 } eval_ops[] = {
658         { eval_table, { { "||", op_or } } },
659         { eval_table, { { "&&", op_and } } },
660         { eval_table, { { "==", op_eq },
661                         { "!=", op_ne } } },
662         { eval_unary, { { "<=", op_le },
663                         { ">=", op_ge },
664                         { "<", op_lt },
665                         { ">", op_gt } } }
666 };
667
668 /*
669  * Function for evaluating the innermost parts of expressions,
670  * viz. !expr (expr) defined(symbol) symbol number
671  * We reset the keepthis flag when we find a non-constant subexpression.
672  */
673 static Linetype
674 eval_unary(const struct ops *ops, int *valp, const char **cpp)
675 {
676         const char *cp;
677         char *ep;
678         int sym;
679         bool defparen;
680
681         cp = skipcomment(*cpp);
682         if (*cp == '!') {
683                 debug("eval%d !", ops - eval_ops);
684                 cp++;
685                 if (eval_unary(ops, valp, &cp) == LT_IF)
686                         return (LT_IF);
687                 *valp = !*valp;
688         } else if (*cp == '(') {
689                 cp++;
690                 debug("eval%d (", ops - eval_ops);
691                 if (eval_table(eval_ops, valp, &cp) == LT_IF)
692                         return (LT_IF);
693                 cp = skipcomment(cp);
694                 if (*cp++ != ')')
695                         return (LT_IF);
696         } else if (isdigit((unsigned char)*cp)) {
697                 debug("eval%d number", ops - eval_ops);
698                 *valp = strtol(cp, &ep, 0);
699                 cp = skipsym(cp);
700         } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
701                 cp = skipcomment(cp+7);
702                 debug("eval%d defined", ops - eval_ops);
703                 if (*cp == '(') {
704                         cp = skipcomment(cp+1);
705                         defparen = true;
706                 } else {
707                         defparen = false;
708                 }
709                 sym = findsym(cp);
710                 if (sym < 0)
711                         return (LT_IF);
712                 *valp = (value[sym] != NULL);
713                 cp = skipsym(cp);
714                 cp = skipcomment(cp);
715                 if (defparen && *cp++ != ')')
716                         return (LT_IF);
717                 keepthis = false;
718         } else if (!endsym(*cp)) {
719                 debug("eval%d symbol", ops - eval_ops);
720                 sym = findsym(cp);
721                 if (sym < 0)
722                         return (LT_IF);
723                 if (value[sym] == NULL)
724                         *valp = 0;
725                 else {
726                         *valp = strtol(value[sym], &ep, 0);
727                         if (*ep != '\0' || ep == value[sym])
728                                 return (LT_IF);
729                 }
730                 cp = skipsym(cp);
731                 keepthis = false;
732         } else {
733                 debug("eval%d bad expr", ops - eval_ops);
734                 return (LT_IF);
735         }
736
737         *cpp = cp;
738         debug("eval%d = %d", ops - eval_ops, *valp);
739         return (*valp ? LT_TRUE : LT_FALSE);
740 }
741
742 /*
743  * Table-driven evaluation of binary operators.
744  */
745 static Linetype
746 eval_table(const struct ops *ops, int *valp, const char **cpp)
747 {
748         const struct op *op;
749         const char *cp;
750         int val;
751
752         debug("eval%d", ops - eval_ops);
753         cp = *cpp;
754         if (ops->inner(ops+1, valp, &cp) == LT_IF)
755                 return (LT_IF);
756         for (;;) {
757                 cp = skipcomment(cp);
758                 for (op = ops->op; op->str != NULL; op++)
759                         if (strncmp(cp, op->str, strlen(op->str)) == 0)
760                                 break;
761                 if (op->str == NULL)
762                         break;
763                 cp += strlen(op->str);
764                 debug("eval%d %s", ops - eval_ops, op->str);
765                 if (ops->inner(ops+1, &val, &cp) == LT_IF)
766                         return (LT_IF);
767                 *valp = op->fn(*valp, val);
768         }
769
770         *cpp = cp;
771         debug("eval%d = %d", ops - eval_ops, *valp);
772         return (*valp ? LT_TRUE : LT_FALSE);
773 }
774
775 /*
776  * Evaluate the expression on a #if or #elif line. If we can work out
777  * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
778  * return just a generic LT_IF.
779  */
780 static Linetype
781 ifeval(const char **cpp)
782 {
783         int ret;
784         int val = 0;
785
786         debug("eval %s", *cpp);
787         keepthis = killconsts ? false : true;
788         ret = eval_table(eval_ops, &val, cpp);
789         debug("eval = %d", val);
790         return (keepthis ? LT_IF : ret);
791 }
792
793 /*
794  * Skip over comments, strings, and character literals and stop at the
795  * next character position that is not whitespace. Between calls we keep
796  * the comment state in the global variable incomment, and we also adjust
797  * the global variable linestate when we see a newline.
798  * XXX: doesn't cope with the buffer splitting inside a state transition.
799  */
800 static const char *
801 skipcomment(const char *cp)
802 {
803         if (text || ignoring[depth]) {
804                 for (; isspace((unsigned char)*cp); cp++)
805                         if (*cp == '\n')
806                                 linestate = LS_START;
807                 return (cp);
808         }
809         while (*cp != '\0')
810                 /* don't reset to LS_START after a line continuation */
811                 if (strncmp(cp, "\\\n", 2) == 0)
812                         cp += 2;
813                 else switch (incomment) {
814                 case NO_COMMENT:
815                         if (strncmp(cp, "/\\\n", 3) == 0) {
816                                 incomment = STARTING_COMMENT;
817                                 cp += 3;
818                         } else if (strncmp(cp, "/*", 2) == 0) {
819                                 incomment = C_COMMENT;
820                                 cp += 2;
821                         } else if (strncmp(cp, "//", 2) == 0) {
822                                 incomment = CXX_COMMENT;
823                                 cp += 2;
824                         } else if (strncmp(cp, "\'", 1) == 0) {
825                                 incomment = CHAR_LITERAL;
826                                 linestate = LS_DIRTY;
827                                 cp += 1;
828                         } else if (strncmp(cp, "\"", 1) == 0) {
829                                 incomment = STRING_LITERAL;
830                                 linestate = LS_DIRTY;
831                                 cp += 1;
832                         } else if (strncmp(cp, "\n", 1) == 0) {
833                                 linestate = LS_START;
834                                 cp += 1;
835                         } else if (strchr(" \t", *cp) != NULL) {
836                                 cp += 1;
837                         } else
838                                 return (cp);
839                         continue;
840                 case CXX_COMMENT:
841                         if (strncmp(cp, "\n", 1) == 0) {
842                                 incomment = NO_COMMENT;
843                                 linestate = LS_START;
844                         }
845                         cp += 1;
846                         continue;
847                 case CHAR_LITERAL:
848                 case STRING_LITERAL:
849                         if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
850                             (incomment == STRING_LITERAL && cp[0] == '\"')) {
851                                 incomment = NO_COMMENT;
852                                 cp += 1;
853                         } else if (cp[0] == '\\') {
854                                 if (cp[1] == '\0')
855                                         cp += 1;
856                                 else
857                                         cp += 2;
858                         } else if (strncmp(cp, "\n", 1) == 0) {
859                                 if (incomment == CHAR_LITERAL)
860                                         error("unterminated char literal");
861                                 else
862                                         error("unterminated string literal");
863                         } else
864                                 cp += 1;
865                         continue;
866                 case C_COMMENT:
867                         if (strncmp(cp, "*\\\n", 3) == 0) {
868                                 incomment = FINISHING_COMMENT;
869                                 cp += 3;
870                         } else if (strncmp(cp, "*/", 2) == 0) {
871                                 incomment = NO_COMMENT;
872                                 cp += 2;
873                         } else
874                                 cp += 1;
875                         continue;
876                 case STARTING_COMMENT:
877                         if (*cp == '*') {
878                                 incomment = C_COMMENT;
879                                 cp += 1;
880                         } else if (*cp == '/') {
881                                 incomment = CXX_COMMENT;
882                                 cp += 1;
883                         } else {
884                                 incomment = NO_COMMENT;
885                                 linestate = LS_DIRTY;
886                         }
887                         continue;
888                 case FINISHING_COMMENT:
889                         if (*cp == '/') {
890                                 incomment = NO_COMMENT;
891                                 cp += 1;
892                         } else
893                                 incomment = C_COMMENT;
894                         continue;
895                 default:
896                         abort(); /* bug */
897                 }
898         return (cp);
899 }
900
901 /*
902  * Skip over an identifier.
903  */
904 static const char *
905 skipsym(const char *cp)
906 {
907         while (!endsym(*cp))
908                 ++cp;
909         return (cp);
910 }
911
912 /*
913  * Look for the symbol in the symbol table. If it is found, we return
914  * the symbol table index, else we return -1.
915  */
916 static int
917 findsym(const char *str)
918 {
919         const char *cp;
920         int symind;
921
922         cp = skipsym(str);
923         if (cp == str)
924                 return (-1);
925         if (symlist) {
926                 printf("%.*s\n", (int)(cp-str), str);
927                 /* we don't care about the value of the symbol */
928                 return (0);
929         }
930         for (symind = 0; symind < nsyms; ++symind) {
931                 if (strlcmp(symname[symind], str, cp-str) == 0) {
932                         debug("findsym %s %s", symname[symind],
933                             value[symind] ? value[symind] : "");
934                         return (symind);
935                 }
936         }
937         return (-1);
938 }
939
940 /*
941  * Add a symbol to the symbol table.
942  */
943 static void
944 addsym(bool ignorethis, bool definethis, char *sym)
945 {
946         int symind;
947         char *val;
948
949         symind = findsym(sym);
950         if (symind < 0) {
951                 if (nsyms >= MAXSYMS)
952                         errx(2, "too many symbols");
953                 symind = nsyms++;
954         }
955         symname[symind] = sym;
956         ignore[symind] = ignorethis;
957         val = sym + (skipsym(sym) - sym);
958         if (definethis) {
959                 if (*val == '=') {
960                         value[symind] = val+1;
961                         *val = '\0';
962                 } else if (*val == '\0')
963                         value[symind] = "";
964                 else
965                         usage();
966         } else {
967                 if (*val != '\0')
968                         usage();
969                 value[symind] = NULL;
970         }
971 }
972
973 /*
974  * Compare s with n characters of t.
975  * The same as strncmp() except that it checks that s[n] == '\0'.
976  */
977 static int
978 strlcmp(const char *s, const char *t, size_t n)
979 {
980         while (n-- && *t != '\0')
981                 if (*s != *t)
982                         return ((unsigned char)*s - (unsigned char)*t);
983                 else
984                         ++s, ++t;
985         return ((unsigned char)*s);
986 }
987
988 /*
989  * Diagnostics.
990  */
991 static void
992 debug(const char *msg, ...)
993 {
994         va_list ap;
995
996         if (debugging) {
997                 va_start(ap, msg);
998                 vwarnx(msg, ap);
999                 va_end(ap);
1000         }
1001 }
1002
1003 static void
1004 error(const char *msg)
1005 {
1006         if (depth == 0)
1007                 warnx("%s: %d: %s", filename, linenum, msg);
1008         else
1009                 warnx("%s: %d: %s (#if line %d depth %d)",
1010                     filename, linenum, msg, stifline[depth], depth);
1011         errx(2, "output may be truncated");
1012 }