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