dc145a24232fc50bf0341fe1e1916be933f77a1c
[unifdef.git] / unifdef.c
1 /*
2  * Copyright (c) 2002 - 2020 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  * unifdef - remove ifdef'ed lines
28  *
29  * This code was derived from software contributed to Berkeley by Dave Yost.
30  * It was rewritten to support ANSI C by Tony Finch. The original version
31  * of unifdef carried the 4-clause BSD copyright licence. None of its code
32  * remains in this version (though some of the names remain) so it now
33  * carries a more liberal licence.
34  *
35  *  Wishlist:
36  *      provide an option which will append the name of the
37  *        appropriate symbol after #else's and #endif's
38  *      provide an option which will check symbols after
39  *        #else's and #endif's to see that they match their
40  *        corresponding #ifdef or #ifndef
41  *
42  *   These require better buffer handling, which would also make
43  *   it possible to handle all "dodgy" directives correctly.
44  */
45
46 #include "unifdef.h"
47
48 static const char copyright[] =
49     #include "version.h"
50     "@(#) $Author: Tony Finch (dot@dotat.at) $\n"
51     "@(#) $URL: http://dotat.at/prog/unifdef $\n"
52 ;
53
54 /* types of input lines: */
55 typedef enum {
56         LT_TRUEI,               /* a true #if with ignore flag */
57         LT_FALSEI,              /* a false #if with ignore flag */
58         LT_IF,                  /* an unknown #if */
59         LT_TRUE,                /* a true #if */
60         LT_FALSE,               /* a false #if */
61         LT_ELIF,                /* an unknown #elif */
62         LT_ELTRUE,              /* a true #elif */
63         LT_ELFALSE,             /* a false #elif */
64         LT_ELSE,                /* #else */
65         LT_ENDIF,               /* #endif */
66         LT_DODGY,               /* flag: directive is not on one line */
67         LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
68         LT_PLAIN,               /* ordinary line */
69         LT_EOF,                 /* end of file */
70         LT_ERROR,               /* unevaluable #if */
71         LT_COUNT
72 } Linetype;
73
74 static char const * const linetype_name[] = {
75         "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
76         "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
77         "DODGY TRUEI", "DODGY FALSEI",
78         "DODGY IF", "DODGY TRUE", "DODGY FALSE",
79         "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
80         "DODGY ELSE", "DODGY ENDIF",
81         "PLAIN", "EOF", "ERROR"
82 };
83
84 #define linetype_if2elif(lt) ((Linetype)(lt - LT_IF + LT_ELIF))
85 #define linetype_2dodgy(lt) ((Linetype)(lt + LT_DODGY))
86
87 /* state of #if processing */
88 typedef enum {
89         IS_OUTSIDE,
90         IS_FALSE_PREFIX,        /* false #if followed by false #elifs */
91         IS_TRUE_PREFIX,         /* first non-false #(el)if is true */
92         IS_PASS_MIDDLE,         /* first non-false #(el)if is unknown */
93         IS_FALSE_MIDDLE,        /* a false #elif after a pass state */
94         IS_TRUE_MIDDLE,         /* a true #elif after a pass state */
95         IS_PASS_ELSE,           /* an else after a pass state */
96         IS_FALSE_ELSE,          /* an else after a true state */
97         IS_TRUE_ELSE,           /* an else after only false states */
98         IS_FALSE_TRAILER,       /* #elifs after a true are false */
99         IS_COUNT
100 } Ifstate;
101
102 static char const * const ifstate_name[] = {
103         "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
104         "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
105         "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
106         "FALSE_TRAILER"
107 };
108
109 /* state of comment parser */
110 typedef enum {
111         NO_COMMENT = false,     /* outside a comment */
112         C_COMMENT,              /* in a comment like this one */
113         CXX_COMMENT,            /* between // and end of line */
114         STARTING_COMMENT,       /* just after slash-backslash-newline */
115         FINISHING_COMMENT,      /* star-backslash-newline in a C comment */
116         CHAR_LITERAL,           /* inside '' */
117         STRING_LITERAL,         /* inside "" */
118         RAW_STRING_LITERAL      /* inside R"()" */
119 } Comment_state;
120
121 static char const * const comment_name[] = {
122         "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
123 };
124
125 /* state of preprocessor line parser */
126 typedef enum {
127         LS_START,               /* only space and comments on this line */
128         LS_HASH,                /* only space, comments, and a hash */
129         LS_DIRTY                /* this line can't be a preprocessor line */
130 } Line_state;
131
132 static char const * const linestate_name[] = {
133         "START", "HASH", "DIRTY"
134 };
135
136 /*
137  * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
138  */
139 #define MAXDEPTH        64                      /* maximum #if nesting */
140 #define MAXLINE         4096                    /* maximum length of line */
141 #define MAXSYMS         16384                   /* maximum number of symbols */
142
143 /*
144  * Sometimes when editing a keyword the replacement text is longer, so
145  * we leave some space at the end of the tline buffer to accommodate this.
146  */
147 #define EDITSLOP        10
148
149 /*
150  * Globals.
151  */
152
153 static bool             compblank;              /* -B: compress blank lines */
154 static bool             lnblank;                /* -b: blank deleted lines */
155 static bool             complement;             /* -c: do the complement */
156 static bool             debugging;              /* -d: debugging reports */
157 static bool             inplace;                /* -m: modify in place */
158 static bool             iocccok;                /* -e: fewer IOCCC errors */
159 static bool             strictlogic;            /* -K: keep ambiguous #ifs */
160 static bool             killconsts;             /* -k: eval constant #ifs */
161 static bool             lnnum;                  /* -n: add #line directives */
162 static bool             symlist;                /* -s: output symbol list */
163 static bool             symdepth;               /* -S: output symbol depth */
164 static bool             text;                   /* -t: this is a text file */
165
166 static const char      *symname[MAXSYMS];       /* symbol name */
167 static const char      *value[MAXSYMS];         /* -Dsym=value */
168 static bool             ignore[MAXSYMS];        /* -iDsym or -iUsym */
169 static int              nsyms;                  /* number of symbols */
170
171 static FILE            *input;                  /* input file pointer */
172 static const char      *filename;               /* input file name */
173 static int              linenum;                /* current line number */
174 static const char      *linefile;               /* file name for #line */
175 static FILE            *output;                 /* output file pointer */
176 static const char      *ofilename;              /* output file name */
177 static const char      *backext;                /* backup extension */
178 static char            *tempname;               /* avoid splatting input */
179
180 static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */
181 static char            *keyword;                /* used for editing #elif's */
182
183 /*
184  * When processing a file, the output's newline style will match the
185  * input's, and unifdef correctly handles CRLF or LF endings whatever
186  * the platform's native style. The stdio streams are opened in binary
187  * mode to accommodate platforms whose native newline style is CRLF.
188  * When the output isn't a processed input file (when it is error /
189  * debug / diagnostic messages) then unifdef uses native line endings.
190  */
191
192 static const char      *newline;                /* input file format */
193 static const char       newline_unix[] = "\n";
194 static const char       newline_crlf[] = "\r\n";
195
196 static Comment_state    incomment;              /* comment parser state */
197 static Line_state       linestate;              /* #if line parser state */
198 static Ifstate          ifstate[MAXDEPTH];      /* #if processor state */
199 static bool             ignoring[MAXDEPTH];     /* ignore comments state */
200 static int              stifline[MAXDEPTH];     /* start of current #if */
201 static int              depth;                  /* current #if nesting */
202 static int              delcount;               /* count of deleted lines */
203 static unsigned         blankcount;             /* count of blank lines */
204 static unsigned         blankmax;               /* maximum recent blankcount */
205 static bool             constexpr;              /* constant #if expression */
206 static bool             zerosyms;               /* to format symdepth output */
207 static bool             firstsym;               /* ditto */
208
209 static int              exitmode;               /* exit status mode */
210 static int              exitstat;               /* program exit status */
211 static bool             altered;                /* was this file modified? */
212
213 static void             addsym1(bool, bool, char *);
214 static void             addsym2(bool, const char *, const char *);
215 static char            *astrcat(const char *, const char *);
216 static void             cleantemp(void);
217 static void             closeio(void);
218 static void             debug(const char *, ...);
219 static void             debugsym(const char *, int);
220 static bool             defundef(void);
221 static void             defundefile(const char *);
222 static void             done(void);
223 static void             error(const char *);
224 static int              findsym(const char **);
225 static void             flushline(bool);
226 static void             hashline(void);
227 static void             help(void);
228 static Linetype         ifeval(const char **);
229 static void             ignoreoff(void);
230 static void             ignoreon(void);
231 static void             indirectsym(void);
232 static void             keywordedit(const char *);
233 static const char      *matchsym(const char *, const char *);
234 static void             nest(void);
235 static Linetype         parseline(void);
236 static void             process(void);
237 static void             processinout(const char *, const char *);
238 static const char      *skipargs(const char *);
239 static const char      *skipcomment(const char *);
240 static const char      *skiphash(void);
241 static const char      *skipline(const char *);
242 static const char      *skipsym(const char *);
243 static void             state(Ifstate);
244 static void             unnest(void);
245 static void             usage(void);
246 static void             version(void);
247 static const char      *xstrdup(const char *, const char *);
248
249 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
250
251 /*
252  * The main program.
253  */
254 int
255 main(int argc, char *argv[])
256 {
257         int opt;
258
259         while ((opt = getopt(argc, argv, "i:D:U:f:I:M:o:x:bBcdehKklmnsStV")) != -1)
260                 switch (opt) {
261                 case 'i': /* treat stuff controlled by these symbols as text */
262                         /*
263                          * For strict backwards-compatibility the U or D
264                          * should be immediately after the -i but it doesn't
265                          * matter much if we relax that requirement.
266                          */
267                         opt = *optarg++;
268                         if (opt == 'D')
269                                 addsym1(true, true, optarg);
270                         else if (opt == 'U')
271                                 addsym1(true, false, optarg);
272                         else
273                                 usage();
274                         break;
275                 case 'D': /* define a symbol */
276                         addsym1(false, true, optarg);
277                         break;
278                 case 'U': /* undef a symbol */
279                         addsym1(false, false, optarg);
280                         break;
281                 case 'I': /* no-op for compatibility with cpp */
282                         break;
283                 case 'b': /* blank deleted lines instead of omitting them */
284                 case 'l': /* backwards compatibility */
285                         lnblank = true;
286                         break;
287                 case 'B': /* compress blank lines around removed section */
288                         compblank = true;
289                         break;
290                 case 'c': /* treat -D as -U and vice versa */
291                         complement = true;
292                         break;
293                 case 'd':
294                         debugging = true;
295                         break;
296                 case 'e': /* fewer errors from dodgy lines */
297                         iocccok = true;
298                         break;
299                 case 'f': /* definitions file */
300                         defundefile(optarg);
301                         break;
302                 case 'h':
303                         help();
304                         break;
305                 case 'K': /* keep ambiguous #ifs */
306                         strictlogic = true;
307                         break;
308                 case 'k': /* process constant #ifs */
309                         killconsts = true;
310                         break;
311                 case 'm': /* modify in place */
312                         inplace = true;
313                         break;
314                 case 'M': /* modify in place and keep backup */
315                         inplace = true;
316                         if (strlen(optarg) > 0)
317                                 backext = optarg;
318                         break;
319                 case 'n': /* add #line directive after deleted lines */
320                         lnnum = true;
321                         break;
322                 case 'o': /* output to a file */
323                         ofilename = optarg;
324                         break;
325                 case 's': /* only output list of symbols that control #ifs */
326                         symlist = true;
327                         break;
328                 case 'S': /* list symbols with their nesting depth */
329                         symlist = symdepth = true;
330                         break;
331                 case 't': /* don't parse C comments */
332                         text = true;
333                         break;
334                 case 'V':
335                         version();
336                         break;
337                 case 'x':
338                         exitmode = atoi(optarg);
339                         if(exitmode < 0 || exitmode > 2)
340                                 usage();
341                         break;
342                 default:
343                         usage();
344                 }
345         argc -= optind;
346         argv += optind;
347         if (compblank && lnblank)
348                 errx(2, "-B and -b are mutually exclusive");
349         if (symlist && (ofilename != NULL || inplace || argc > 1))
350                 errx(2, "-s only works with one input file");
351         if (argc > 1 && ofilename != NULL)
352                 errx(2, "-o cannot be used with multiple input files");
353         if (argc > 1 && !inplace)
354                 errx(2, "multiple input files require -m or -M");
355         if (argc == 0 && inplace)
356                 errx(2, "-m requires an input file");
357         if (argc == 0)
358                 argc = 1;
359         if (argc == 1 && !inplace && ofilename == NULL)
360                 ofilename = "-";
361         indirectsym();
362
363         atexit(cleantemp);
364         if (ofilename != NULL)
365                 processinout(*argv, ofilename);
366         else while (argc-- > 0) {
367                 processinout(*argv, *argv);
368                 argv++;
369         }
370         switch(exitmode) {
371         case(0): exit(exitstat);
372         case(1): exit(!exitstat);
373         case(2): exit(0);
374         default: abort(); /* bug */
375         }
376 }
377
378 /*
379  * File logistics.
380  */
381 static void
382 processinout(const char *ifn, const char *ofn)
383 {
384         struct stat st;
385
386         if (ifn == NULL || strcmp(ifn, "-") == 0) {
387                 filename = "[stdin]";
388                 linefile = NULL;
389                 input = fbinmode(stdin);
390         } else {
391                 filename = ifn;
392                 linefile = ifn;
393                 input = fopen(ifn, "rb");
394                 if (input == NULL)
395                         err(2, "can't open %s", ifn);
396         }
397         if (strcmp(ofn, "-") == 0) {
398                 output = fbinmode(stdout);
399                 process();
400                 return;
401         }
402         if (stat(ofn, &st) < 0) {
403                 output = fopen(ofn, "wb");
404                 if (output == NULL)
405                         err(2, "can't create %s", ofn);
406                 process();
407                 return;
408         }
409
410         tempname = astrcat(ofn, ".XXXXXX");
411         output = mktempmode(tempname, st.st_mode);
412         if (output == NULL)
413                 err(2, "can't create %s", tempname);
414
415         process();
416
417         if (backext != NULL) {
418                 char *backname = astrcat(ofn, backext);
419                 if (rename(ofn, backname) < 0)
420                         err(2, "can't rename \"%s\" to \"%s\"", ofn, backname);
421                 free(backname);
422         }
423         /* leave file unmodified if unifdef made no changes */
424         if (!altered && backext == NULL) {
425                 if (remove(tempname) < 0)
426                         warn("can't remove \"%s\"", tempname);
427         } else if (replace(tempname, ofn) < 0)
428                 err(2, "can't rename \"%s\" to \"%s\"", tempname, ofn);
429         free(tempname);
430         tempname = NULL;
431 }
432
433 /*
434  * For cleaning up if there is an error.
435  */
436 static void
437 cleantemp(void)
438 {
439         if (tempname != NULL)
440                 remove(tempname);
441 }
442
443 /*
444  * Self-identification functions.
445  */
446
447 static void
448 version(void)
449 {
450         const char *c = copyright;
451         for (;;) {
452                 while (*++c != '$')
453                         if (*c == '\0')
454                                 exit(0);
455                 while (*++c != '$')
456                         putc(*c, stderr);
457                 putc('\n', stderr);
458         }
459 }
460
461 static void
462 synopsis(FILE *fp)
463 {
464         fprintf(fp,
465             "usage:     unifdef [-bBcdehKkmnsStV] [-x{012}] [-Mext] [-opath] \\\n"
466             "           [-[i]Dsym[=val]] [-[i]Usym] [-fpath] ... [file] ...\n");
467 }
468
469 static void
470 usage(void)
471 {
472         synopsis(stderr);
473         exit(2);
474 }
475
476 static void
477 help(void)
478 {
479         synopsis(stdout);
480         printf(
481             "   -Dsym=val  define preprocessor symbol with given value\n"
482             "   -Dsym      define preprocessor symbol with value 1\n"
483             "   -Usym      preprocessor symbol is undefined\n"
484             "   -iDsym=val \\  ignore C strings and comments\n"
485             "   -iDsym      ) in sections controlled by these\n"
486             "   -iUsym     /  preprocessor symbols\n"
487             "   -fpath  file containing #define and #undef directives\n"
488             "   -b      blank lines instead of deleting them\n"
489             "   -B      compress blank lines around deleted section\n"
490             "   -c      complement (invert) keep vs. delete\n"
491             "   -d      debugging mode\n"
492             "   -e      ignore multiline preprocessor directives\n"
493             "   -h      print help\n"
494             "   -Ipath  extra include file path (ignored)\n"
495             "   -K      disable && and || short-circuiting\n"
496             "   -k      process constant #if expressions\n"
497             "   -Mext   modify in place and keep backups\n"
498             "   -m      modify input files in place\n"
499             "   -n      add #line directives to output\n"
500             "   -opath  output file name\n"
501             "   -S      list #if control symbols with nesting\n"
502             "   -s      list #if control symbols\n"
503             "   -t      ignore C strings and comments\n"
504             "   -V      print version\n"
505             "   -x{012} exit status mode\n"
506         );
507         exit(0);
508 }
509
510 /*
511  * A state transition function alters the global #if processing state
512  * in a particular way. The table below is indexed by the current
513  * processing state and the type of the current line.
514  *
515  * Nesting is handled by keeping a stack of states; some transition
516  * functions increase or decrease the depth. They also maintain the
517  * ignore state on a stack. In some complicated cases they have to
518  * alter the preprocessor directive, as follows.
519  *
520  * When we have processed a group that starts off with a known-false
521  * #if/#elif sequence (which has therefore been deleted) followed by a
522  * #elif that we don't understand and therefore must keep, we edit the
523  * latter into a #if to keep the nesting correct. We use memcpy() to
524  * overwrite the 4 byte token "elif" with "if  " without a '\0' byte.
525  *
526  * When we find a true #elif in a group, the following block will
527  * always be kept and the rest of the sequence after the next #elif or
528  * #else will be discarded. We edit the #elif into a #else and the
529  * following directive to #endif since this has the desired behaviour.
530  *
531  * "Dodgy" directives are split across multiple lines, the most common
532  * example being a multi-line comment hanging off the right of the
533  * directive. We can handle them correctly only if there is no change
534  * from printing to dropping (or vice versa) caused by that directive.
535  * If the directive is the first of a group we have a choice between
536  * failing with an error, or passing it through unchanged instead of
537  * evaluating it. The latter is not the default to avoid questions from
538  * users about unifdef unexpectedly leaving behind preprocessor directives.
539  */
540 typedef void state_fn(void);
541
542 /* report an error */
543 static void Eelif (void) { error("Inappropriate #elif"); }
544 static void Eelse (void) { error("Inappropriate #else"); }
545 static void Eendif(void) { error("Inappropriate #endif"); }
546 static void Eeof  (void) { error("Premature EOF"); }
547 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
548 /* plain line handling */
549 static void print (void) { flushline(true); }
550 static void drop  (void) { flushline(false); }
551 /* output lacks group's start line */
552 static void Strue (void) { drop();  ignoreoff(); state(IS_TRUE_PREFIX); }
553 static void Sfalse(void) { drop();  ignoreoff(); state(IS_FALSE_PREFIX); }
554 static void Selse (void) { drop();               state(IS_TRUE_ELSE); }
555 /* print/pass this block */
556 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
557 static void Pelse (void) { print();              state(IS_PASS_ELSE); }
558 static void Pendif(void) { print(); unnest(); }
559 /* discard this block */
560 static void Dfalse(void) { drop();  ignoreoff(); state(IS_FALSE_TRAILER); }
561 static void Delif (void) { drop();  ignoreoff(); state(IS_FALSE_MIDDLE); }
562 static void Delse (void) { drop();               state(IS_FALSE_ELSE); }
563 static void Dendif(void) { drop();  unnest(); }
564 /* first line of group */
565 static void Fdrop (void) { nest();  Dfalse(); }
566 static void Fpass (void) { nest();  Pelif(); }
567 static void Ftrue (void) { nest();  Strue(); }
568 static void Ffalse(void) { nest();  Sfalse(); }
569 /* variable pedantry for obfuscated lines */
570 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
571 static void Oif   (void) { if (!iocccok) Eioccc(); Fpass(); }
572 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
573 /* ignore comments in this block */
574 static void Idrop (void) { Fdrop();  ignoreon(); }
575 static void Itrue (void) { Ftrue();  ignoreon(); }
576 static void Ifalse(void) { Ffalse(); ignoreon(); }
577 /* modify this line */
578 static void Mpass (void) { memcpy(keyword, "if  ", 4); Pelif(); }
579 static void Mtrue (void) { keywordedit("else");  state(IS_TRUE_MIDDLE); }
580 static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
581 static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
582
583 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
584 /* IS_OUTSIDE */
585 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
586   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,
587   print, done,  abort },
588 /* IS_FALSE_PREFIX */
589 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
590   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
591   drop,  Eeof,  abort },
592 /* IS_TRUE_PREFIX */
593 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
594   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
595   print, Eeof,  abort },
596 /* IS_PASS_MIDDLE */
597 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
598   Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,
599   print, Eeof,  abort },
600 /* IS_FALSE_MIDDLE */
601 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
602   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
603   drop,  Eeof,  abort },
604 /* IS_TRUE_MIDDLE */
605 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
606   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
607   print, Eeof,  abort },
608 /* IS_PASS_ELSE */
609 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
610   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,
611   print, Eeof,  abort },
612 /* IS_FALSE_ELSE */
613 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
614   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
615   drop,  Eeof,  abort },
616 /* IS_TRUE_ELSE */
617 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
618   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,
619   print, Eeof,  abort },
620 /* IS_FALSE_TRAILER */
621 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
622   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
623   drop,  Eeof,  abort }
624 /*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF
625   TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)
626   PLAIN  EOF    ERROR */
627 };
628
629 /*
630  * State machine utility functions
631  */
632 static void
633 ignoreoff(void)
634 {
635         if (depth == 0)
636                 abort(); /* bug */
637         ignoring[depth] = ignoring[depth-1];
638 }
639 static void
640 ignoreon(void)
641 {
642         ignoring[depth] = true;
643 }
644 static void
645 keywordedit(const char *replacement)
646 {
647         snprintf(keyword, tline + sizeof(tline) - keyword,
648             "%s%s", replacement, newline);
649         altered = true;
650         print();
651 }
652 static void
653 nest(void)
654 {
655         if (depth > MAXDEPTH-1)
656                 abort(); /* bug */
657         if (depth == MAXDEPTH-1)
658                 error("Too many levels of nesting");
659         depth += 1;
660         stifline[depth] = linenum;
661 }
662 static void
663 unnest(void)
664 {
665         if (depth == 0)
666                 abort(); /* bug */
667         depth -= 1;
668 }
669 static void
670 state(Ifstate is)
671 {
672         ifstate[depth] = is;
673 }
674
675 /*
676  * The last state transition function. When this is called,
677  * lineval == LT_EOF, so the process() loop will terminate.
678  */
679 static void
680 done(void)
681 {
682         if (incomment)
683                 error("EOF in comment");
684         closeio();
685 }
686
687 /*
688  * Write a line to the output or not, according to command line options.
689  * If writing fails, closeio() will print the error and exit.
690  */
691 static void
692 flushline(bool keep)
693 {
694         if (symlist)
695                 return;
696         if (keep ^ complement) {
697                 bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
698                 if (blankline && compblank && blankcount != blankmax) {
699                         delcount += 1;
700                         blankcount += 1;
701                 } else {
702                         if (lnnum && delcount > 0)
703                                 hashline();
704                         if (fputs(tline, output) == EOF)
705                                 closeio();
706                         delcount = 0;
707                         blankmax = blankcount = blankline ? blankcount + 1 : 0;
708                 }
709         } else {
710                 if (lnblank && fputs(newline, output) == EOF)
711                         closeio();
712                 altered = true;
713                 delcount += 1;
714                 blankcount = 0;
715         }
716         if (debugging && fflush(output) == EOF)
717                 closeio();
718 }
719
720 /*
721  * Format of #line directives depends on whether we know the input filename.
722  */
723 static void
724 hashline(void)
725 {
726         int e;
727
728         if (linefile == NULL)
729                 e = fprintf(output, "#line %d%s", linenum, newline);
730         else
731                 e = fprintf(output, "#line %d \"%s\"%s",
732                     linenum, linefile, newline);
733         if (e < 0)
734                 closeio();
735 }
736
737 /*
738  * Flush the output and handle errors.
739  */
740 static void
741 closeio(void)
742 {
743         /* Tidy up after findsym(). */
744         if (symdepth && !zerosyms)
745                 printf("\n");
746         if (output != NULL && (ferror(output) || fclose(output) == EOF))
747                         err(2, "%s: can't write to output", filename);
748         fclose(input);
749 }
750
751 /*
752  * The driver for the state machine.
753  */
754 static void
755 process(void)
756 {
757         Linetype lineval = LT_PLAIN;
758         /* When compressing blank lines, act as if the file
759            is preceded by a large number of blank lines. */
760         blankmax = blankcount = 1000;
761         zerosyms = true;
762         newline = NULL;
763         linenum = 0;
764         altered = false;
765         while (lineval != LT_EOF) {
766                 lineval = parseline();
767                 trans_table[ifstate[depth]][lineval]();
768                 debug("process line %d %s -> %s depth %d",
769                     linenum, linetype_name[lineval],
770                     ifstate_name[ifstate[depth]], depth);
771         }
772         exitstat |= altered;
773 }
774
775 /*
776  * Parse a line and determine its type. We keep the preprocessor line
777  * parser state between calls in the global variable linestate, with
778  * help from skipcomment().
779  */
780 static Linetype
781 parseline(void)
782 {
783         const char *cp;
784         int cursym;
785         Linetype retval;
786         Comment_state wascomment;
787
788         wascomment = incomment;
789         cp = skiphash();
790         if (cp == NULL)
791                 return (LT_EOF);
792         if (newline == NULL) {
793                 if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
794                         newline = newline_crlf;
795                 else
796                         newline = newline_unix;
797         }
798         if (*cp == '\0') {
799                 retval = LT_PLAIN;
800                 goto done;
801         }
802         keyword = tline + (cp - tline);
803         if ((cp = matchsym("ifdef", keyword)) != NULL ||
804             (cp = matchsym("ifndef", keyword)) != NULL) {
805                 cp = skipcomment(cp);
806                 if ((cursym = findsym(&cp)) < 0)
807                         retval = LT_IF;
808                 else {
809                         retval = (keyword[2] == 'n')
810                             ? LT_FALSE : LT_TRUE;
811                         if (value[cursym] == NULL)
812                                 retval = (retval == LT_TRUE)
813                                     ? LT_FALSE : LT_TRUE;
814                         if (ignore[cursym])
815                                 retval = (retval == LT_TRUE)
816                                     ? LT_TRUEI : LT_FALSEI;
817                 }
818         } else if ((cp = matchsym("if", keyword)) != NULL)
819                 retval = ifeval(&cp);
820         else if ((cp = matchsym("elif", keyword)) != NULL)
821                 retval = linetype_if2elif(ifeval(&cp));
822         else if ((cp = matchsym("else", keyword)) != NULL)
823                 retval = LT_ELSE;
824         else if ((cp = matchsym("endif", keyword)) != NULL)
825                 retval = LT_ENDIF;
826         else {
827                 cp = skipsym(keyword);
828                 /* no way can we deal with a continuation inside a keyword */
829                 if (strncmp(cp, "\\\r\n", 3) == 0 ||
830                     strncmp(cp, "\\\n", 2) == 0)
831                         Eioccc();
832                 cp = skipline(cp);
833                 retval = LT_PLAIN;
834                 goto done;
835         }
836         cp = skipcomment(cp);
837         if (*cp != '\0') {
838                 cp = skipline(cp);
839                 if (retval == LT_TRUE || retval == LT_FALSE ||
840                     retval == LT_TRUEI || retval == LT_FALSEI)
841                         retval = LT_IF;
842                 if (retval == LT_ELTRUE || retval == LT_ELFALSE)
843                         retval = LT_ELIF;
844         }
845         /* the following can happen if the last line of the file lacks a
846            newline or if there is too much whitespace in a directive */
847         if (linestate == LS_HASH) {
848                 long len = cp - tline;
849                 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
850                         if (ferror(input))
851                                 err(2, "can't read %s", filename);
852                         debug("parser insert newline at EOF", linenum);
853                         strcpy(tline + len, newline);
854                         cp += strlen(newline);
855                         linestate = LS_START;
856                 } else {
857                         debug("parser concatenate dangling whitespace");
858                         ++linenum;
859                         cp = skipcomment(cp);
860                 }
861         }
862         if (retval != LT_PLAIN && (wascomment || linestate != LS_START)) {
863                 retval = linetype_2dodgy(retval);
864                 linestate = LS_DIRTY;
865         }
866 done:
867         debug("parser line %d state %s comment %s line", linenum,
868             comment_name[incomment], linestate_name[linestate]);
869         return (retval);
870 }
871
872 /*
873  * These are the binary operators that are supported by the expression
874  * evaluator.
875  */
876 static Linetype op_strict(long *p, long v, Linetype at, Linetype bt) {
877         if(at == LT_IF || bt == LT_IF) return (LT_IF);
878         return (*p = v, v ? LT_TRUE : LT_FALSE);
879 }
880 static Linetype op_lt(long *p, Linetype at, long a, Linetype bt, long b) {
881         return op_strict(p, a < b, at, bt);
882 }
883 static Linetype op_gt(long *p, Linetype at, long a, Linetype bt, long b) {
884         return op_strict(p, a > b, at, bt);
885 }
886 static Linetype op_le(long *p, Linetype at, long a, Linetype bt, long b) {
887         return op_strict(p, a <= b, at, bt);
888 }
889 static Linetype op_ge(long *p, Linetype at, long a, Linetype bt, long b) {
890         return op_strict(p, a >= b, at, bt);
891 }
892 static Linetype op_eq(long *p, Linetype at, long a, Linetype bt, long b) {
893         return op_strict(p, a == b, at, bt);
894 }
895 static Linetype op_ne(long *p, Linetype at, long a, Linetype bt, long b) {
896         return op_strict(p, a != b, at, bt);
897 }
898 static Linetype op_or(long *p, Linetype at, long a, Linetype bt, long b) {
899         if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
900                 return (*p = 1, LT_TRUE);
901         return op_strict(p, a || b, at, bt);
902 }
903 static Linetype op_and(long *p, Linetype at, long a, Linetype bt, long b) {
904         if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
905                 return (*p = 0, LT_FALSE);
906         return op_strict(p, a && b, at, bt);
907 }
908 static Linetype op_blsh(long *p, Linetype at, long a, Linetype bt, long b) {
909         return op_strict(p, a << b, at, bt);
910 }
911 static Linetype op_brsh(long *p, Linetype at, long a, Linetype bt, long b) {
912         return op_strict(p, a >> b, at, bt);
913 }
914 static Linetype op_add(long *p, Linetype at, long a, Linetype bt, long b) {
915         return op_strict(p, a + b, at, bt);
916 }
917 static Linetype op_sub(long *p, Linetype at, long a, Linetype bt, long b) {
918         return op_strict(p, a - b, at, bt);
919 }
920 static Linetype op_mul(long *p, Linetype at, long a, Linetype bt, long b) {
921         return op_strict(p, a * b, at, bt);
922 }
923 static Linetype op_div(long *p, Linetype at, long a, Linetype bt, long b) {
924         if (bt != LT_TRUE) {
925                 debug("eval division by zero");
926                 return (LT_ERROR);
927         }
928         return op_strict(p, a / b, at, bt);
929 }
930 static Linetype op_mod(long *p, Linetype at, long a, Linetype bt, long b) {
931         return op_strict(p, a % b, at, bt);
932 }
933 static Linetype op_bor(long *p, Linetype at, long a, Linetype bt, long b) {
934         return op_strict(p, a | b, at, bt);
935 }
936 static Linetype op_bxor(long *p, Linetype at, long a, Linetype bt, long b) {
937         return op_strict(p, a ^ b, at, bt);
938 }
939 static Linetype op_band(long *p, Linetype at, long a, Linetype bt, long b) {
940         return op_strict(p, a & b, at, bt);
941 }
942
943 /*
944  * An evaluation function takes three arguments, as follows: (1) a pointer to
945  * an element of the precedence table which lists the operators at the current
946  * level of precedence; (2) a pointer to an integer which will receive the
947  * value of the expression; and (3) a pointer to a char* that points to the
948  * expression to be evaluated and that is updated to the end of the expression
949  * when evaluation is complete. The function returns LT_FALSE if the value of
950  * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
951  * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
952  */
953 struct ops;
954
955 typedef Linetype eval_fn(const struct ops *, long *, const char **);
956
957 static eval_fn eval_table, eval_unary;
958
959 /*
960  * The precedence table. Expressions involving binary operators are evaluated
961  * in a table-driven way by eval_table. When it evaluates a subexpression it
962  * calls the inner function with its first argument pointing to the next
963  * element of the table. Innermost expressions have special non-table-driven
964  * handling.
965  *
966  * The stop characters help with lexical analysis: an operator is not
967  * recognized if it is followed by one of the stop characters because
968  * that would make it a different operator.
969  */
970 struct op {
971         const char *str;
972         Linetype (*fn)(long *, Linetype, long, Linetype, long);
973         const char *stop;
974 };
975 struct ops {
976         eval_fn *inner;
977         struct op op[5];
978 };
979 static const struct ops eval_ops[] = {
980         { eval_table, { { "||", op_or,   NULL } } },
981         { eval_table, { { "&&", op_and,  NULL } } },
982         { eval_table, { { "|",  op_bor,  "|" } } },
983         { eval_table, { { "^",  op_bxor, NULL } } },
984         { eval_table, { { "&",  op_band, "&" } } },
985         { eval_table, { { "==", op_eq,   NULL },
986                         { "!=", op_ne,   NULL } } },
987         { eval_table, { { "<=", op_le,   NULL },
988                         { ">=", op_ge,   NULL },
989                         { "<",  op_lt,   "<=" },
990                         { ">",  op_gt,   ">=" } } },
991         { eval_table, { { "<<", op_blsh, NULL },
992                         { ">>", op_brsh, NULL } } },
993         { eval_table, { { "+",  op_add,  NULL },
994                         { "-",  op_sub,  NULL } } },
995         { eval_unary, { { "*",  op_mul,  NULL },
996                         { "/",  op_div,  NULL },
997                         { "%",  op_mod,  NULL } } },
998 };
999
1000 /* Current operator precedence level */
1001 static long prec(const struct ops *ops)
1002 {
1003         return (ops - eval_ops);
1004 }
1005
1006 /*
1007  * Function for evaluating the innermost parts of expressions,
1008  * viz. !expr (expr) number defined(symbol) symbol
1009  * We reset the constexpr flag in the last two cases.
1010  */
1011 static Linetype
1012 eval_unary(const struct ops *ops, long *valp, const char **cpp)
1013 {
1014         const char *cp;
1015         char *ep;
1016         int sym;
1017         bool defparen;
1018         Linetype lt;
1019
1020         cp = skipcomment(*cpp);
1021         if (*cp == '!') {
1022                 debug("eval%d !", prec(ops));
1023                 cp++;
1024                 lt = eval_unary(ops, valp, &cp);
1025                 if (lt == LT_ERROR)
1026                         return (LT_ERROR);
1027                 if (lt != LT_IF) {
1028                         *valp = !*valp;
1029                         lt = *valp ? LT_TRUE : LT_FALSE;
1030                 }
1031         } else if (*cp == '~') {
1032                 debug("eval%d ~", prec(ops));
1033                 cp++;
1034                 lt = eval_unary(ops, valp, &cp);
1035                 if (lt == LT_ERROR)
1036                         return (LT_ERROR);
1037                 if (lt != LT_IF) {
1038                         *valp = ~(*valp);
1039                         lt = *valp ? LT_TRUE : LT_FALSE;
1040                 }
1041         } else if (*cp == '-') {
1042                 debug("eval%d -", prec(ops));
1043                 cp++;
1044                 lt = eval_unary(ops, valp, &cp);
1045                 if (lt == LT_ERROR)
1046                         return (LT_ERROR);
1047                 if (lt != LT_IF) {
1048                         *valp = -(*valp);
1049                         lt = *valp ? LT_TRUE : LT_FALSE;
1050                 }
1051         } else if (*cp == '(') {
1052                 cp++;
1053                 debug("eval%d (", prec(ops));
1054                 lt = eval_table(eval_ops, valp, &cp);
1055                 if (lt == LT_ERROR)
1056                         return (LT_ERROR);
1057                 cp = skipcomment(cp);
1058                 if (*cp++ != ')')
1059                         return (LT_ERROR);
1060         } else if (isdigit((unsigned char)*cp)) {
1061                 debug("eval%d number", prec(ops));
1062                 *valp = strtol(cp, &ep, 0);
1063                 if (ep == cp)
1064                         return (LT_ERROR);
1065                 lt = *valp ? LT_TRUE : LT_FALSE;
1066                 cp = ep;
1067         } else if (matchsym("defined", cp) != NULL) {
1068                 cp = skipcomment(cp+7);
1069                 if (*cp == '(') {
1070                         cp = skipcomment(cp+1);
1071                         defparen = true;
1072                 } else {
1073                         defparen = false;
1074                 }
1075                 sym = findsym(&cp);
1076                 cp = skipcomment(cp);
1077                 if (defparen && *cp++ != ')') {
1078                         debug("eval%d defined missing ')'", prec(ops));
1079                         return (LT_ERROR);
1080                 }
1081                 if (sym < 0) {
1082                         debug("eval%d defined unknown", prec(ops));
1083                         lt = LT_IF;
1084                 } else {
1085                         debug("eval%d defined %s", prec(ops), symname[sym]);
1086                         *valp = (value[sym] != NULL);
1087                         lt = *valp ? LT_TRUE : LT_FALSE;
1088                 }
1089                 constexpr = false;
1090         } else if (!endsym(*cp)) {
1091                 debug("eval%d symbol", prec(ops));
1092                 sym = findsym(&cp);
1093                 if (sym < 0) {
1094                         lt = LT_IF;
1095                         cp = skipargs(cp);
1096                 } else if (value[sym] == NULL) {
1097                         *valp = 0;
1098                         lt = LT_FALSE;
1099                 } else {
1100                         *valp = strtol(value[sym], &ep, 0);
1101                         if (*ep != '\0' || ep == value[sym])
1102                                 return (LT_ERROR);
1103                         lt = *valp ? LT_TRUE : LT_FALSE;
1104                         cp = skipargs(cp);
1105                 }
1106                 constexpr = false;
1107         } else {
1108                 debug("eval%d bad expr", prec(ops));
1109                 return (LT_ERROR);
1110         }
1111
1112         *cpp = cp;
1113         debug("eval%d = %d", prec(ops), *valp);
1114         return (lt);
1115 }
1116
1117 /*
1118  * Table-driven evaluation of binary operators.
1119  */
1120 static Linetype
1121 eval_table(const struct ops *ops, long *valp, const char **cpp)
1122 {
1123         const struct op *op;
1124         const char *cp;
1125         long val = 0;
1126         Linetype lt, rt;
1127
1128         debug("eval%d", prec(ops));
1129         cp = *cpp;
1130         lt = ops->inner(ops+1, valp, &cp);
1131         if (lt == LT_ERROR)
1132                 return (LT_ERROR);
1133         for (;;) {
1134                 cp = skipcomment(cp);
1135                 for (op = ops->op; op->str != NULL; op++) {
1136                         if (strncmp(cp, op->str, strlen(op->str)) == 0) {
1137                                 /* assume only one-char operators have stop chars */
1138                                 if (op->stop != NULL && cp[1] != '\0' &&
1139                                     strchr(op->stop, cp[1]) != NULL)
1140                                         continue;
1141                                 else
1142                                         break;
1143                         }
1144                 }
1145                 if (op->str == NULL)
1146                         break;
1147                 cp += strlen(op->str);
1148                 debug("eval%d %s", prec(ops), op->str);
1149                 rt = ops->inner(ops+1, &val, &cp);
1150                 if (rt == LT_ERROR)
1151                         return (LT_ERROR);
1152                 lt = op->fn(valp, lt, *valp, rt, val);
1153         }
1154
1155         *cpp = cp;
1156         debug("eval%d = %d", prec(ops), *valp);
1157         debug("eval%d lt = %s", prec(ops), linetype_name[lt]);
1158         return (lt);
1159 }
1160
1161 /*
1162  * Evaluate the expression on a #if or #elif line. If we can work out
1163  * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
1164  * return just a generic LT_IF.
1165  */
1166 static Linetype
1167 ifeval(const char **cpp)
1168 {
1169         Linetype ret;
1170         long val = 0;
1171
1172         debug("eval %s", *cpp);
1173         constexpr = killconsts ? false : true;
1174         ret = eval_table(eval_ops, &val, cpp);
1175         debug("eval = %d", val);
1176         return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
1177 }
1178
1179 /*
1180  * Read a line and examine its initial part to determine if it is a
1181  * preprocessor directive. Returns NULL on EOF, or a pointer to a
1182  * preprocessor directive name, or a pointer to the zero byte at the
1183  * end of the line.
1184  */
1185 static const char *
1186 skiphash(void)
1187 {
1188         const char *cp;
1189
1190         linenum++;
1191         if (fgets(tline, MAXLINE, input) == NULL) {
1192                 if (ferror(input))
1193                         err(2, "can't read %s", filename);
1194                 else
1195                         return (NULL);
1196         }
1197         cp = skipcomment(tline);
1198         if (linestate == LS_START && *cp == '#') {
1199                 linestate = LS_HASH;
1200                 return (skipcomment(cp + 1));
1201         } else if (*cp == '\0') {
1202                 return (cp);
1203         } else {
1204                 return (skipline(cp));
1205         }
1206 }
1207
1208 /*
1209  * Mark a line dirty and consume the rest of it, keeping track of the
1210  * lexical state.
1211  */
1212 static const char *
1213 skipline(const char *cp)
1214 {
1215         const char *pcp;
1216         if (*cp != '\0')
1217                 linestate = LS_DIRTY;
1218         while (*cp != '\0') {
1219                 cp = skipcomment(pcp = cp);
1220                 if (pcp == cp)
1221                         cp++;
1222         }
1223         return (cp);
1224 }
1225
1226 /*
1227  * Skip over comments, strings, and character literals and stop at the
1228  * next character position that is not whitespace. Between calls we keep
1229  * the comment state in the global variable incomment, and we also adjust
1230  * the global variable linestate when we see a newline.
1231  * XXX: doesn't cope with the buffer splitting inside a state transition.
1232  */
1233 static const char *
1234 skipcomment(const char *cp)
1235 {
1236         if (text || ignoring[depth]) {
1237                 for (; isspace((unsigned char)*cp); cp++)
1238                         if (*cp == '\n')
1239                                 linestate = LS_START;
1240                 return (cp);
1241         }
1242         while (*cp != '\0')
1243                 /* don't reset to LS_START after a line continuation */
1244                 if (strncmp(cp, "\\\r\n", 3) == 0)
1245                         cp += 3;
1246                 else if (strncmp(cp, "\\\n", 2) == 0)
1247                         cp += 2;
1248                 else switch (incomment) {
1249                 case NO_COMMENT:
1250                         if (strncmp(cp, "/\\\r\n", 4) == 0) {
1251                                 incomment = STARTING_COMMENT;
1252                                 cp += 4;
1253                         } else if (strncmp(cp, "/\\\n", 3) == 0) {
1254                                 incomment = STARTING_COMMENT;
1255                                 cp += 3;
1256                         } else if (strncmp(cp, "/*", 2) == 0) {
1257                                 incomment = C_COMMENT;
1258                                 cp += 2;
1259                         } else if (strncmp(cp, "//", 2) == 0) {
1260                                 incomment = CXX_COMMENT;
1261                                 cp += 2;
1262                         } else if (strncmp(cp, "\'", 1) == 0) {
1263                                 incomment = CHAR_LITERAL;
1264                                 linestate = LS_DIRTY;
1265                                 cp += 1;
1266                         } else if (strncmp(cp, "\"", 1) == 0) {
1267                                 incomment = STRING_LITERAL;
1268                                 linestate = LS_DIRTY;
1269                                 cp += 1;
1270                         } else if (strncmp(cp, "R\"(", 3) == 0) {
1271                                 incomment = RAW_STRING_LITERAL;
1272                                 linestate = LS_DIRTY;
1273                                 cp += 3;
1274                         } else if (strncmp(cp, "\n", 1) == 0) {
1275                                 linestate = LS_START;
1276                                 cp += 1;
1277                         } else if (strchr(" \r\t", *cp) != NULL) {
1278                                 cp += 1;
1279                         } else
1280                                 return (cp);
1281                         continue;
1282                 case CXX_COMMENT:
1283                         if (strncmp(cp, "\n", 1) == 0) {
1284                                 incomment = NO_COMMENT;
1285                                 linestate = LS_START;
1286                         }
1287                         cp += 1;
1288                         continue;
1289                 case CHAR_LITERAL:
1290                 case STRING_LITERAL:
1291                         if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
1292                             (incomment == STRING_LITERAL && cp[0] == '\"')) {
1293                                 incomment = NO_COMMENT;
1294                                 cp += 1;
1295                         } else if (cp[0] == '\\') {
1296                                 if (cp[1] == '\0')
1297                                         cp += 1;
1298                                 else
1299                                         cp += 2;
1300                         } else if (strncmp(cp, "\n", 1) == 0) {
1301                                 if (incomment == CHAR_LITERAL)
1302                                         error("Unterminated char literal");
1303                                 else
1304                                         error("Unterminated string literal");
1305                         } else
1306                                 cp += 1;
1307                         continue;
1308                 case RAW_STRING_LITERAL:
1309                         if (strncmp(cp, ")\"", 2) == 0) {
1310                                 incomment = NO_COMMENT;
1311                                 cp += 2;
1312                         } else
1313                                 cp += 1;
1314                         continue;
1315                 case C_COMMENT:
1316                         if (strncmp(cp, "*\\\r\n", 4) == 0) {
1317                                 incomment = FINISHING_COMMENT;
1318                                 cp += 4;
1319                         } else if (strncmp(cp, "*\\\n", 3) == 0) {
1320                                 incomment = FINISHING_COMMENT;
1321                                 cp += 3;
1322                         } else if (strncmp(cp, "*/", 2) == 0) {
1323                                 incomment = NO_COMMENT;
1324                                 cp += 2;
1325                         } else
1326                                 cp += 1;
1327                         continue;
1328                 case STARTING_COMMENT:
1329                         if (*cp == '*') {
1330                                 incomment = C_COMMENT;
1331                                 cp += 1;
1332                         } else if (*cp == '/') {
1333                                 incomment = CXX_COMMENT;
1334                                 cp += 1;
1335                         } else {
1336                                 incomment = NO_COMMENT;
1337                                 linestate = LS_DIRTY;
1338                         }
1339                         continue;
1340                 case FINISHING_COMMENT:
1341                         if (*cp == '/') {
1342                                 incomment = NO_COMMENT;
1343                                 cp += 1;
1344                         } else
1345                                 incomment = C_COMMENT;
1346                         continue;
1347                 default:
1348                         abort(); /* bug */
1349                 }
1350         return (cp);
1351 }
1352
1353 /*
1354  * Skip macro arguments.
1355  */
1356 static const char *
1357 skipargs(const char *cp)
1358 {
1359         const char *ocp = cp;
1360         int level = 0;
1361         cp = skipcomment(cp);
1362         if (*cp != '(')
1363                 return (cp);
1364         do {
1365                 if (*cp == '(')
1366                         level++;
1367                 if (*cp == ')')
1368                         level--;
1369                 cp = skipcomment(cp+1);
1370         } while (level != 0 && *cp != '\0');
1371         if (level == 0)
1372                 return (cp);
1373         else
1374         /* Rewind and re-detect the syntax error later. */
1375                 return (ocp);
1376 }
1377
1378 /*
1379  * Skip over an identifier.
1380  */
1381 static const char *
1382 skipsym(const char *cp)
1383 {
1384         while (!endsym(*cp))
1385                 ++cp;
1386         return (cp);
1387 }
1388
1389 /*
1390  * Skip whitespace and take a copy of any following identifier.
1391  */
1392 static const char *
1393 getsym(const char **cpp)
1394 {
1395         const char *cp = *cpp, *sym;
1396
1397         cp = skipcomment(cp);
1398         cp = skipsym(sym = cp);
1399         if (cp == sym)
1400                 return NULL;
1401         *cpp = cp;
1402         return (xstrdup(sym, cp));
1403 }
1404
1405 /*
1406  * Check that s (a symbol) matches the start of t, and that the
1407  * following character in t is not a symbol character. Returns a
1408  * pointer to the following character in t if there is a match,
1409  * otherwise NULL.
1410  */
1411 static const char *
1412 matchsym(const char *s, const char *t)
1413 {
1414         while (*s != '\0' && *t != '\0')
1415                 if (*s != *t)
1416                         return (NULL);
1417                 else
1418                         ++s, ++t;
1419         if (*s == '\0' && endsym(*t))
1420                 return(t);
1421         else
1422                 return(NULL);
1423 }
1424
1425 /*
1426  * Look for the symbol in the symbol table. If it is found, we return
1427  * the symbol table index, else we return -1.
1428  */
1429 static int
1430 findsym(const char **strp)
1431 {
1432         const char *str;
1433         int symind;
1434
1435         str = *strp;
1436         *strp = skipsym(str);
1437         if (symlist) {
1438                 if (*strp == str)
1439                         return (-1);
1440                 if (symdepth && firstsym)
1441                         printf("%s%3d", zerosyms ? "" : "\n", depth);
1442                 firstsym = zerosyms = false;
1443                 printf("%s%.*s%s",
1444                        symdepth ? " " : "",
1445                        (int)(*strp-str), str,
1446                        symdepth ? "" : "\n");
1447                 /* we don't care about the value of the symbol */
1448                 return (0);
1449         }
1450         for (symind = 0; symind < nsyms; ++symind) {
1451                 if (matchsym(symname[symind], str) != NULL) {
1452                         debugsym("findsym", symind);
1453                         return (symind);
1454                 }
1455         }
1456         return (-1);
1457 }
1458
1459 /*
1460  * Resolve indirect symbol values to their final definitions.
1461  */
1462 static void
1463 indirectsym(void)
1464 {
1465         const char *cp;
1466         int changed, sym, ind;
1467
1468         do {
1469                 changed = 0;
1470                 for (sym = 0; sym < nsyms; ++sym) {
1471                         if (value[sym] == NULL)
1472                                 continue;
1473                         cp = value[sym];
1474                         ind = findsym(&cp);
1475                         if (ind == -1 || ind == sym ||
1476                             *cp != '\0' ||
1477                             value[ind] == NULL ||
1478                             value[ind] == value[sym])
1479                                 continue;
1480                         debugsym("indir...", sym);
1481                         value[sym] = value[ind];
1482                         debugsym("...ectsym", sym);
1483                         changed++;
1484                 }
1485         } while (changed);
1486 }
1487
1488 /*
1489  * Add a symbol to the symbol table, specified with the format sym=val
1490  */
1491 static void
1492 addsym1(bool ignorethis, bool definethis, char *symval)
1493 {
1494         const char *sym, *val;
1495
1496         sym = symval;
1497         val = skipsym(sym);
1498         if (definethis && *val == '=') {
1499                 symval[val - sym] = '\0';
1500                 val = val + 1;
1501         } else if (*val == '\0') {
1502                 val = definethis ? "1" : NULL;
1503         } else {
1504                 usage();
1505         }
1506         addsym2(ignorethis, sym, val);
1507 }
1508
1509 /*
1510  * Add a symbol to the symbol table.
1511  */
1512 static void
1513 addsym2(bool ignorethis, const char *sym, const char *val)
1514 {
1515         const char *cp = sym;
1516         int symind;
1517
1518         symind = findsym(&cp);
1519         if (symind < 0) {
1520                 if (nsyms >= MAXSYMS)
1521                         errx(2, "too many symbols");
1522                 symind = nsyms++;
1523         }
1524         ignore[symind] = ignorethis;
1525         symname[symind] = sym;
1526         value[symind] = val;
1527         debugsym("addsym", symind);
1528 }
1529
1530 static void
1531 debugsym(const char *why, int symind)
1532 {
1533         debug("%s %s%c%s", why, symname[symind],
1534             value[symind] ? '=' : ' ',
1535             value[symind] ? value[symind] : "undef");
1536 }
1537
1538 /*
1539  * Add symbols to the symbol table from a file containing
1540  * #define and #undef preprocessor directives.
1541  */
1542 static void
1543 defundefile(const char *fn)
1544 {
1545         filename = fn;
1546         input = fopen(fn, "rb");
1547         if (input == NULL)
1548                 err(2, "can't open %s", fn);
1549         linenum = 0;
1550         while (defundef())
1551                 ;
1552         if (ferror(input))
1553                 err(2, "can't read %s", filename);
1554         else
1555                 fclose(input);
1556         if (incomment)
1557                 error("EOF in comment");
1558 }
1559
1560 /*
1561  * Read and process one #define or #undef directive
1562  */
1563 static bool
1564 defundef(void)
1565 {
1566         const char *cp, *kw, *sym, *val, *end;
1567
1568         cp = skiphash();
1569         if (cp == NULL)
1570                 return (false);
1571         if (*cp == '\0')
1572                 goto done;
1573         /* strip trailing whitespace, and do a fairly rough check to
1574            avoid unsupported multi-line preprocessor directives */
1575         end = cp + strlen(cp);
1576         while (end > tline && strchr(" \t\n\r", end[-1]) != NULL)
1577                 --end;
1578         if (end > tline && end[-1] == '\\')
1579                 Eioccc();
1580
1581         kw = cp;
1582         if ((cp = matchsym("define", kw)) != NULL) {
1583                 sym = getsym(&cp);
1584                 if (sym == NULL)
1585                         error("Missing macro name in #define");
1586                 if (*cp == '(') {
1587                         val = "1";
1588                 } else {
1589                         cp = skipcomment(cp);
1590                         val = (cp < end) ? xstrdup(cp, end) : "";
1591                 }
1592                 debug("#define");
1593                 addsym2(false, sym, val);
1594         } else if ((cp = matchsym("undef", kw)) != NULL) {
1595                 sym = getsym(&cp);
1596                 if (sym == NULL)
1597                         error("Missing macro name in #undef");
1598                 cp = skipcomment(cp);
1599                 debug("#undef");
1600                 addsym2(false, sym, NULL);
1601         } else {
1602                 error("Unrecognized preprocessor directive");
1603         }
1604         skipline(cp);
1605 done:
1606         debug("parser line %d state %s comment %s line", linenum,
1607             comment_name[incomment], linestate_name[linestate]);
1608         return (true);
1609 }
1610
1611 /*
1612  * Concatenate two strings into new memory, checking for failure.
1613  */
1614 static char *
1615 astrcat(const char *s1, const char *s2)
1616 {
1617         char *s;
1618         int len;
1619         size_t size;
1620
1621         len = snprintf(NULL, 0, "%s%s", s1, s2);
1622         if (len < 0)
1623                 err(2, "snprintf");
1624         size = (size_t)len + 1;
1625         s = (char *)malloc(size);
1626         if (s == NULL)
1627                 err(2, "malloc");
1628         snprintf(s, size, "%s%s", s1, s2);
1629         return (s);
1630 }
1631
1632 /*
1633  * Duplicate a segment of a string, checking for failure.
1634  */
1635 static const char *
1636 xstrdup(const char *start, const char *end)
1637 {
1638         size_t n;
1639         char *s;
1640
1641         if (end < start) abort(); /* bug */
1642         n = (size_t)(end - start) + 1;
1643         s = (char *)malloc(n);
1644         if (s == NULL)
1645                 err(2, "malloc");
1646         snprintf(s, n, "%s", start);
1647         return (s);
1648 }
1649
1650 /*
1651  * Diagnostics.
1652  */
1653 static void
1654 debug(const char *msg, ...)
1655 {
1656         va_list ap;
1657
1658         if (debugging) {
1659                 va_start(ap, msg);
1660                 vwarnx(msg, ap);
1661                 va_end(ap);
1662         }
1663 }
1664
1665 static void
1666 error(const char *msg)
1667 {
1668         if (depth == 0)
1669                 warnx("%s: %d: %s", filename, linenum, msg);
1670         else
1671                 warnx("%s: %d: %s (#if line %d depth %d)",
1672                     filename, linenum, msg, stifline[depth], depth);
1673         closeio();
1674         errx(2, "Output may be truncated");
1675 }