Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.131
      1 /*	$NetBSD: indent.c,v 1.131 2021/10/08 20:33:18 rillig Exp $	*/
      2 
      3 /*-
      4  * SPDX-License-Identifier: BSD-4-Clause
      5  *
      6  * Copyright (c) 1985 Sun Microsystems, Inc.
      7  * Copyright (c) 1976 Board of Trustees of the University of Illinois.
      8  * Copyright (c) 1980, 1993
      9  *	The Regents of the University of California.  All rights reserved.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the University of
     22  *	California, Berkeley and its contributors.
     23  * 4. Neither the name of the University nor the names of its contributors
     24  *    may be used to endorse or promote products derived from this software
     25  *    without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     37  * SUCH DAMAGE.
     38  */
     39 
     40 #if 0
     41 static char sccsid[] = "@(#)indent.c	5.17 (Berkeley) 6/7/93";
     42 #endif
     43 
     44 #include <sys/cdefs.h>
     45 #if defined(__NetBSD__)
     46 __RCSID("$NetBSD: indent.c,v 1.131 2021/10/08 20:33:18 rillig Exp $");
     47 #elif defined(__FreeBSD__)
     48 __FBSDID("$FreeBSD: head/usr.bin/indent/indent.c 340138 2018-11-04 19:24:49Z oshogbo $");
     49 #endif
     50 
     51 #include <sys/param.h>
     52 #if HAVE_CAPSICUM
     53 #include <sys/capsicum.h>
     54 #include <capsicum_helpers.h>
     55 #endif
     56 #include <ctype.h>
     57 #include <err.h>
     58 #include <errno.h>
     59 #include <fcntl.h>
     60 #include <stdio.h>
     61 #include <stdlib.h>
     62 #include <string.h>
     63 #include <unistd.h>
     64 
     65 #include "indent.h"
     66 
     67 struct options opt = {
     68     .brace_same_line = true,
     69     .comment_delimiter_on_blankline = true,
     70     .cuddle_else = true,
     71     .comment_column = 33,
     72     .decl_indent = 16,
     73     .else_if = true,
     74     .function_brace_split = true,
     75     .format_col1_comments = true,
     76     .format_block_comments = true,
     77     .indent_parameters = true,
     78     .indent_size = 8,
     79     .local_decl_indent = -1,
     80     .lineup_to_parens = true,
     81     .procnames_start_line = true,
     82     .star_comment_cont = true,
     83     .tabsize = 8,
     84     .max_line_length = 78,
     85     .use_tabs = true,
     86 };
     87 
     88 struct parser_state ps;
     89 
     90 struct buffer lab;
     91 struct buffer code;
     92 struct buffer com;
     93 struct buffer token;
     94 
     95 struct buffer inp;
     96 
     97 char sc_buf[sc_size];
     98 char *save_com;
     99 static char *sc_end;		/* pointer into save_com buffer */
    100 
    101 char *saved_inp_s;
    102 char *saved_inp_e;
    103 
    104 bool found_err;
    105 int next_blank_lines;
    106 bool prefix_blankline_requested;
    107 bool postfix_blankline_requested;
    108 bool break_comma;
    109 float case_ind;
    110 bool had_eof;
    111 int line_no;
    112 bool inhibit_formatting;
    113 
    114 static int ifdef_level;
    115 static struct parser_state state_stack[5];
    116 
    117 FILE *input;
    118 FILE *output;
    119 
    120 static const char *in_name = "Standard Input";
    121 static const char *out_name = "Standard Output";
    122 static const char *backup_suffix = ".BAK";
    123 static char bakfile[MAXPATHLEN] = "";
    124 
    125 #if HAVE_CAPSICUM
    126 static void
    127 init_capsicum(void)
    128 {
    129     cap_rights_t rights;
    130 
    131     /* Restrict input/output descriptors and enter Capsicum sandbox. */
    132     cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
    133     if (caph_rights_limit(fileno(output), &rights) < 0)
    134 	err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
    135     cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
    136     if (caph_rights_limit(fileno(input), &rights) < 0)
    137 	err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
    138     if (caph_enter() < 0)
    139 	err(EXIT_FAILURE, "unable to enter capability mode");
    140 }
    141 #endif
    142 
    143 static void
    144 search_brace_newline(bool *force_nl)
    145 {
    146     if (sc_end == NULL) {
    147 	save_com = sc_buf;
    148 	save_com[0] = save_com[1] = ' ';
    149 	sc_end = &save_com[2];
    150     }
    151     *sc_end++ = '\n';
    152 
    153     /*
    154      * We may have inherited a force_nl == true from the previous token (like
    155      * a semicolon). But once we know that a newline has been scanned in this
    156      * loop, force_nl should be false.
    157      *
    158      * However, the force_nl == true must be preserved if newline is never
    159      * scanned in this loop, so this assignment cannot be done earlier.
    160      */
    161     *force_nl = false;
    162 }
    163 
    164 static void
    165 search_brace_comment(bool *comment_buffered)
    166 {
    167     if (sc_end == NULL) {
    168 	/*
    169 	 * Copy everything from the start of the line, because
    170 	 * process_comment() will use that to calculate original indentation
    171 	 * of a boxed comment.
    172 	 */
    173 	memcpy(sc_buf, inp.buf, (size_t)(inp.s - inp.buf) - 4);
    174 	save_com = sc_buf + (inp.s - inp.buf - 4);
    175 	save_com[0] = save_com[1] = ' ';
    176 	sc_end = &save_com[2];
    177     }
    178 
    179     *comment_buffered = true;
    180     *sc_end++ = '/';		/* copy in start of comment */
    181     *sc_end++ = '*';
    182 
    183     for (;;) {			/* loop until the end of the comment */
    184 	*sc_end++ = inbuf_next();
    185 	if (sc_end[-1] == '*' && *inp.s == '/')
    186 	    break;		/* we are at end of comment */
    187 	if (sc_end >= &save_com[sc_size]) {	/* check for temp buffer
    188 						 * overflow */
    189 	    diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
    190 	    fflush(output);
    191 	    exit(1);
    192 	}
    193     }
    194 
    195     *sc_end++ = '/';		/* add ending slash */
    196     inbuf_skip();		/* get past / in buffer */
    197 }
    198 
    199 static bool
    200 search_brace_lbrace(void)
    201 {
    202     /*
    203      * Put KNF-style lbraces before the buffered up tokens and jump out of
    204      * this loop in order to avoid copying the token again.
    205      */
    206     if (sc_end != NULL && opt.brace_same_line) {
    207 	save_com[0] = '{';
    208 	/*
    209 	 * Originally the lbrace may have been alone on its own line, but it
    210 	 * will be moved into "the else's line", so if there was a newline
    211 	 * resulting from the "{" before, it must be scanned now and ignored.
    212 	 */
    213 	while (isspace((unsigned char)*inp.s)) {
    214 	    inbuf_skip();
    215 	    if (*inp.s == '\n')
    216 		break;
    217 	}
    218 	return true;
    219     }
    220     return false;
    221 }
    222 
    223 static bool
    224 search_brace_other(token_type ttype, bool *force_nl,
    225     bool comment_buffered, bool last_else)
    226 {
    227     bool remove_newlines;
    228 
    229     remove_newlines =
    230 	    /* "} else" */
    231 	    (ttype == keyword_do_else && *token.s == 'e' &&
    232 	     code.e != code.s && code.e[-1] == '}')
    233 	    /* "else if" */
    234 	    || (ttype == keyword_for_if_while &&
    235 		*token.s == 'i' && last_else && opt.else_if);
    236     if (remove_newlines)
    237 	*force_nl = false;
    238 
    239     if (sc_end == NULL) {	/* ignore buffering if comment wasn't saved
    240 				 * up */
    241 	ps.search_brace = false;
    242 	return false;
    243     }
    244 
    245     while (sc_end > save_com && isblank((unsigned char)sc_end[-1]))
    246 	sc_end--;
    247 
    248     if (opt.swallow_optional_blanklines ||
    249 	(!comment_buffered && remove_newlines)) {
    250 	*force_nl = !remove_newlines;
    251 	while (sc_end > save_com && sc_end[-1] == '\n') {
    252 	    sc_end--;
    253 	}
    254     }
    255 
    256     if (*force_nl) {		/* if we should insert a nl here, put it into
    257 				 * the buffer */
    258 	*force_nl = false;
    259 	--line_no;		/* this will be re-increased when the newline
    260 				 * is read from the buffer */
    261 	*sc_end++ = '\n';
    262 	*sc_end++ = ' ';
    263 	if (opt.verbose)	/* warn if the line was not already broken */
    264 	    diag(0, "Line broken");
    265     }
    266 
    267     for (const char *t_ptr = token.s; *t_ptr != '\0'; ++t_ptr)
    268 	*sc_end++ = *t_ptr;
    269     return true;
    270 }
    271 
    272 static void
    273 switch_buffer(void)
    274 {
    275     ps.search_brace = false;	/* stop looking for start of stmt */
    276     saved_inp_s = inp.s;		/* save current input buffer */
    277     saved_inp_e = inp.e;
    278     inp.s = save_com;		/* fix so that subsequent calls to lexi will
    279 				 * take tokens out of save_com */
    280     *sc_end++ = ' ';		/* add trailing blank, just in case */
    281     inp.e = sc_end;
    282     sc_end = NULL;
    283     debug_println("switched inp.s to save_com");
    284 }
    285 
    286 static void
    287 search_brace_lookahead(token_type *ttype)
    288 {
    289     if (*ttype == end_of_file)
    290 	return;
    291 
    292     /*
    293      * The only intended purpose of calling lexi() below is to categorize
    294      * the next token in order to decide whether to continue buffering
    295      * forthcoming tokens. Once the buffering is over, lexi() will be
    296      * called again elsewhere on all of the tokens - this time for normal
    297      * processing.
    298      *
    299      * Calling it for this purpose is a bug, because lexi() also changes
    300      * the parser state and discards leading whitespace, which is needed
    301      * mostly for comment-related considerations.
    302      *
    303      * Work around the former problem by giving lexi() a copy of the
    304      * current parser state and discard it if the call turned out to be
    305      * just a lookahead.
    306      *
    307      * Work around the latter problem by copying all whitespace characters
    308      * into the buffer so that the later lexi() call will read them.
    309      */
    310     if (sc_end != NULL) {
    311 	while (is_hspace(*inp.s)) {
    312 	    *sc_end++ = *inp.s++;
    313 	    if (sc_end >= &save_com[sc_size])
    314 		errx(1, "input too long");
    315 	}
    316 	if (inp.s >= inp.e)
    317 	    fill_buffer();
    318     }
    319 
    320     struct parser_state transient_state;
    321     transient_state = ps;
    322     *ttype = lexi(&transient_state);	/* read another token */
    323     if (*ttype != newline && *ttype != form_feed &&
    324 	*ttype != comment && !transient_state.search_brace) {
    325 	ps = transient_state;
    326     }
    327 }
    328 
    329 static void
    330 search_brace(token_type *ttype, bool *force_nl,
    331     bool *comment_buffered, bool *last_else)
    332 {
    333     while (ps.search_brace) {
    334 	switch (*ttype) {
    335 	case newline:
    336 	    search_brace_newline(force_nl);
    337 	    break;
    338 	case form_feed:
    339 	    break;
    340 	case comment:
    341 	    search_brace_comment(comment_buffered);
    342 	    break;
    343 	case lbrace:
    344 	    if (search_brace_lbrace())
    345 		goto switch_buffer;
    346 	    /* FALLTHROUGH */
    347 	default:		/* it is the start of a normal statement */
    348 	    if (!search_brace_other(*ttype, force_nl,
    349 		    *comment_buffered, *last_else))
    350 		return;
    351 	switch_buffer:
    352 	    switch_buffer();
    353 	}
    354 	search_brace_lookahead(ttype);
    355     }
    356 
    357     *last_else = false;
    358 }
    359 
    360 static void
    361 buf_init(struct buffer *buf)
    362 {
    363     size_t size = 200;
    364     buf->buf = xmalloc(size);
    365     buf->buf[0] = ' ';		/* allow accessing buf->e[-1] */
    366     buf->buf[1] = '\0';
    367     buf->s = buf->buf + 1;
    368     buf->e = buf->s;
    369     buf->l = buf->buf + size - 5;	/* safety margin */
    370 }
    371 
    372 static size_t
    373 buf_len(const struct buffer *buf)
    374 {
    375     return (size_t)(buf->e - buf->s);
    376 }
    377 
    378 void
    379 buf_expand(struct buffer *buf, size_t desired_size)
    380 {
    381     size_t nsize = (size_t)(buf->l - buf->s) + 400 + desired_size;
    382     size_t len = buf_len(buf);
    383     buf->buf = xrealloc(buf->buf, nsize);
    384     buf->e = buf->buf + len + 1;
    385     buf->l = buf->buf + nsize - 5;
    386     buf->s = buf->buf + 1;
    387 }
    388 
    389 static void
    390 buf_reserve(struct buffer *buf, size_t n)
    391 {
    392     if (buf->e + n >= buf->l)
    393 	buf_expand(buf, n);
    394 }
    395 
    396 static void
    397 buf_add_char(struct buffer *buf, char ch)
    398 {
    399     buf_reserve(buf, 1);
    400     *buf->e++ = ch;
    401 }
    402 
    403 static void
    404 buf_add_buf(struct buffer *buf, const struct buffer *add)
    405 {
    406     size_t len = buf_len(add);
    407     buf_reserve(buf, len);
    408     memcpy(buf->e, add->s, len);
    409     buf->e += len;
    410 }
    411 
    412 static void
    413 buf_terminate(struct buffer *buf)
    414 {
    415     buf_reserve(buf, 1);
    416     *buf->e = '\0';
    417 }
    418 
    419 static void
    420 buf_reset(struct buffer *buf)
    421 {
    422     buf->e = buf->s;
    423 }
    424 
    425 static void
    426 main_init_globals(void)
    427 {
    428     found_err = false;
    429 
    430     ps.p_stack[0] = stmt;
    431     ps.last_nl = true;
    432     ps.last_token = semicolon;
    433     buf_init(&com);
    434     buf_init(&lab);
    435     buf_init(&code);
    436     buf_init(&token);
    437 
    438     opt.else_if = true;		/* XXX: redundant? */
    439 
    440     inp.buf = xmalloc(10);
    441     inp.l = inp.buf + 8;
    442     inp.s = inp.e = inp.buf;
    443     line_no = 1;
    444     had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
    445 
    446     ps.in_or_st = false;
    447     ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
    448     ps.is_case_label = false;
    449 
    450     sc_end = NULL;
    451     saved_inp_s = NULL;
    452     saved_inp_e = NULL;
    453 
    454     output = NULL;
    455 
    456     const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
    457     if (suffix != NULL)
    458 	backup_suffix = suffix;
    459 }
    460 
    461 /*
    462  * Copy the input file to the backup file, then make the backup file the input
    463  * and the original input file the output.
    464  */
    465 static void
    466 bakcopy(void)
    467 {
    468     ssize_t n;
    469     int bak_fd;
    470     char buff[8 * 1024];
    471 
    472     const char *last_slash = strrchr(in_name, '/');
    473     snprintf(bakfile, sizeof(bakfile), "%s%s",
    474 	     last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
    475 
    476     /* copy in_name to backup file */
    477     bak_fd = creat(bakfile, 0600);
    478     if (bak_fd < 0)
    479 	err(1, "%s", bakfile);
    480 
    481     while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
    482 	if (write(bak_fd, buff, (size_t)n) != n)
    483 	    err(1, "%s", bakfile);
    484     if (n < 0)
    485 	err(1, "%s", in_name);
    486 
    487     close(bak_fd);
    488     (void)fclose(input);
    489 
    490     /* re-open backup file as the input file */
    491     input = fopen(bakfile, "r");
    492     if (input == NULL)
    493 	err(1, "%s", bakfile);
    494     /* now the original input file will be the output */
    495     output = fopen(in_name, "w");
    496     if (output == NULL) {
    497 	unlink(bakfile);
    498 	err(1, "%s", in_name);
    499     }
    500 }
    501 
    502 static void
    503 main_parse_command_line(int argc, char **argv)
    504 {
    505     int i;
    506     const char *profile_name = NULL;
    507 
    508     for (i = 1; i < argc; ++i)
    509 	if (strcmp(argv[i], "-npro") == 0)
    510 	    break;
    511 	else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0')
    512 	    profile_name = argv[i] + 2;	/* non-empty -P (set profile) */
    513     if (i >= argc)
    514 	load_profiles(profile_name);
    515 
    516     for (i = 1; i < argc; ++i) {
    517 	if (argv[i][0] == '-') {
    518 	    set_option(argv[i], "Command line");
    519 
    520 	} else if (input == NULL) {
    521 	    in_name = argv[i];
    522 	    input = fopen(in_name, "r");
    523 	    if (input == NULL)
    524 		err(1, "%s", in_name);
    525 
    526 	} else if (output == NULL) {
    527 	    out_name = argv[i];
    528 	    if (strcmp(in_name, out_name) == 0)
    529 		errx(1, "input and output files must be different");
    530 	    output = fopen(out_name, "w");
    531 	    if (output == NULL)
    532 		err(1, "%s", out_name);
    533 
    534 	} else
    535 	    errx(1, "unknown parameter: %s", argv[i]);
    536     }
    537 
    538     if (input == NULL)
    539 	input = stdin;
    540     if (output == NULL) {
    541 	if (input == stdin)
    542 	    output = stdout;
    543 	else {
    544 	    out_name = in_name;
    545 	    bakcopy();
    546 	}
    547     }
    548 
    549     if (opt.comment_column <= 1)
    550 	opt.comment_column = 2;	/* don't put normal comments before column 2 */
    551     if (opt.block_comment_max_line_length <= 0)
    552 	opt.block_comment_max_line_length = opt.max_line_length;
    553     if (opt.local_decl_indent < 0)	/* if not specified by user, set this */
    554 	opt.local_decl_indent = opt.decl_indent;
    555     if (opt.decl_comment_column <= 0)	/* if not specified by user, set this */
    556 	opt.decl_comment_column = opt.ljust_decl
    557 	    ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
    558 	    : opt.comment_column;
    559     if (opt.continuation_indent == 0)
    560 	opt.continuation_indent = opt.indent_size;
    561     if (!(1 <= opt.tabsize && opt.tabsize <= 80))
    562 	errx(EXIT_FAILURE, "invalid tabsize %d", opt.tabsize);
    563     if (!(1 <= opt.indent_size && opt.indent_size <= 80))
    564 	errx(EXIT_FAILURE, "invalid indentation %d", opt.indent_size);
    565 }
    566 
    567 static void
    568 main_prepare_parsing(void)
    569 {
    570     fill_buffer();		/* get first batch of stuff into input buffer */
    571 
    572     parse(semicolon);
    573 
    574     char *p = inp.s;
    575     int ind = 0;
    576 
    577     for (;;) {
    578 	if (*p == ' ')
    579 	    ind++;
    580 	else if (*p == '\t')
    581 	    ind = opt.tabsize * (1 + ind / opt.tabsize);
    582 	else
    583 	    break;
    584 	p++;
    585     }
    586     if (ind >= opt.indent_size)
    587 	ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
    588 }
    589 
    590 static void
    591 indent_declaration(int cur_decl_ind, bool tabs_to_var)
    592 {
    593     int pos = (int)buf_len(&code);
    594     char *orig_code_e = code.e;
    595 
    596     /*
    597      * get the tab math right for indentations that are not multiples of
    598      * tabsize
    599      */
    600     if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
    601 	pos += (ps.ind_level * opt.indent_size) % opt.tabsize;
    602 	cur_decl_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
    603     }
    604 
    605     if (tabs_to_var) {
    606 	int tpos;
    607 
    608 	while ((tpos = opt.tabsize * (1 + pos / opt.tabsize)) <= cur_decl_ind) {
    609 	    buf_add_char(&code, '\t');
    610 	    pos = tpos;
    611 	}
    612     }
    613 
    614     while (pos < cur_decl_ind) {
    615 	buf_add_char(&code, ' ');
    616 	pos++;
    617     }
    618 
    619     if (code.e == orig_code_e && ps.want_blank) {
    620 	*code.e++ = ' ';
    621 	ps.want_blank = false;
    622     }
    623 }
    624 
    625 static void __attribute__((__noreturn__))
    626 process_end_of_file(void)
    627 {
    628     if (lab.s != lab.e || code.s != code.e || com.s != com.e)
    629 	dump_line();
    630 
    631     if (ps.tos > 1)		/* check for balanced braces */
    632 	diag(1, "Stuff missing from end of file");
    633 
    634     if (opt.verbose) {
    635 	printf("There were %d output lines and %d comments\n",
    636 	    ps.stats.lines, ps.stats.comments);
    637 	printf("(Lines with comments)/(Lines with code): %6.3f\n",
    638 	    (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
    639     }
    640 
    641     fflush(output);
    642     exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
    643 }
    644 
    645 static void
    646 process_comment_in_code(token_type ttype, bool *force_nl)
    647 {
    648     if (*force_nl &&
    649 	ttype != semicolon &&
    650 	(ttype != lbrace || !opt.brace_same_line)) {
    651 
    652 	/* we should force a broken line here */
    653 	if (opt.verbose)
    654 	    diag(0, "Line broken");
    655 	dump_line();
    656 	ps.want_blank = false;	/* don't insert blank at line start */
    657 	*force_nl = false;
    658     }
    659 
    660     /* add an extra level of indentation; turned off again by a ';' or '}' */
    661     ps.in_stmt = true;
    662 
    663     if (com.s != com.e) {	/* a comment embedded in a line */
    664 	buf_add_char(&code, ' ');
    665 	buf_add_buf(&code, &com);
    666 	buf_add_char(&code, ' ');
    667 	buf_terminate(&code);
    668 	buf_reset(&com);
    669 	ps.want_blank = false;
    670     }
    671 }
    672 
    673 static void
    674 process_form_feed(void)
    675 {
    676     ps.use_ff = true;
    677     dump_line();
    678     ps.want_blank = false;
    679 }
    680 
    681 static void
    682 process_newline(void)
    683 {
    684     if (ps.last_token != comma || ps.p_l_follow > 0 || opt.break_after_comma
    685 	|| ps.block_init || !break_comma || com.s != com.e) {
    686 	dump_line();
    687 	ps.want_blank = false;
    688     }
    689     ++line_no;
    690 }
    691 
    692 static bool
    693 want_blank_before_lparen(void)
    694 {
    695     if (!ps.want_blank)
    696 	return false;
    697     if (ps.last_token == rparen_or_rbracket)
    698 	return false;
    699     if (ps.last_token != ident && ps.last_token != funcname)
    700 	return true;
    701     if (opt.proc_calls_space)
    702 	return true;
    703     if (ps.keyword == kw_sizeof)
    704 	return opt.blank_after_sizeof;
    705     return ps.keyword != kw_0 && ps.keyword != kw_offsetof;
    706 }
    707 
    708 static void
    709 process_lparen_or_lbracket(int decl_ind, bool tabs_to_var, bool sp_sw)
    710 {
    711     if (++ps.p_l_follow == nitems(ps.paren_indents)) {
    712 	diag(0, "Reached internal limit of %zu unclosed parens",
    713 	    nitems(ps.paren_indents));
    714 	ps.p_l_follow--;
    715     }
    716 
    717     if (token.s[0] == '(' && ps.in_decl
    718 	&& !ps.block_init && !ps.dumped_decl_indent &&
    719 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    720 	/* function pointer declarations */
    721 	indent_declaration(decl_ind, tabs_to_var);
    722 	ps.dumped_decl_indent = true;
    723     } else if (want_blank_before_lparen())
    724 	*code.e++ = ' ';
    725     ps.want_blank = false;
    726     *code.e++ = token.s[0];
    727 
    728     ps.paren_indents[ps.p_l_follow - 1] =
    729 	(short)indentation_after_range(0, code.s, code.e);
    730     debug_println("paren_indent[%d] is now %d",
    731 	ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
    732 
    733     if (sp_sw && ps.p_l_follow == 1 && opt.extra_expr_indent
    734 	    && ps.paren_indents[0] < 2 * opt.indent_size) {
    735 	ps.paren_indents[0] = (short)(2 * opt.indent_size);
    736 	debug_println("paren_indent[0] is now %d", ps.paren_indents[0]);
    737     }
    738 
    739     if (ps.in_or_st && *token.s == '(' && ps.tos <= 2) {
    740 	/*
    741 	 * this is a kluge to make sure that declarations will be aligned
    742 	 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
    743 	 */
    744 	parse(semicolon);	/* I said this was a kluge... */
    745 	ps.in_or_st = false;	/* turn off flag for structure decl or
    746 				 * initialization */
    747     }
    748 
    749     /* parenthesized type following sizeof or offsetof is not a cast */
    750     if (ps.keyword == kw_offsetof || ps.keyword == kw_sizeof)
    751 	ps.not_cast_mask |= 1 << ps.p_l_follow;
    752 }
    753 
    754 static void
    755 process_rparen_or_rbracket(bool *sp_sw, bool *force_nl,
    756     token_type hd_type)
    757 {
    758     if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
    759 	ps.last_u_d = true;
    760 	ps.cast_mask &= (1 << ps.p_l_follow) - 1;
    761 	ps.want_blank = opt.space_after_cast;
    762     } else
    763 	ps.want_blank = true;
    764     ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
    765 
    766     if (--ps.p_l_follow < 0) {
    767 	ps.p_l_follow = 0;
    768 	diag(0, "Extra %c", *token.s);
    769     }
    770 
    771     if (code.e == code.s)	/* if the paren starts the line */
    772 	ps.paren_level = ps.p_l_follow;	/* then indent it */
    773 
    774     *code.e++ = token.s[0];
    775 
    776     if (*sp_sw && (ps.p_l_follow == 0)) {	/* check for end of if (...),
    777 						 * or some such */
    778 	*sp_sw = false;
    779 	*force_nl = true;	/* must force newline after if */
    780 	ps.last_u_d = true;	/* inform lexi that a following operator is
    781 				 * unary */
    782 	ps.in_stmt = false;	/* don't use stmt continuation indentation */
    783 
    784 	parse(hd_type);		/* let parser worry about if, or whatever */
    785     }
    786 
    787     /*
    788      * This should ensure that constructs such as main(){...} and int[]{...}
    789      * have their braces put in the right place.
    790      */
    791     ps.search_brace = opt.brace_same_line;
    792 }
    793 
    794 static void
    795 process_unary_op(int decl_ind, bool tabs_to_var)
    796 {
    797     if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
    798 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    799 	/* pointer declarations */
    800 	indent_declaration(decl_ind - (int)strlen(token.s), tabs_to_var);
    801 	ps.dumped_decl_indent = true;
    802     } else if (ps.want_blank)
    803 	*code.e++ = ' ';
    804 
    805     buf_add_buf(&code, &token);
    806     ps.want_blank = false;
    807 }
    808 
    809 static void
    810 process_binary_op(void)
    811 {
    812     if (ps.want_blank)
    813 	buf_add_char(&code, ' ');
    814     buf_add_buf(&code, &token);
    815     ps.want_blank = true;
    816 }
    817 
    818 static void
    819 process_postfix_op(void)
    820 {
    821     *code.e++ = token.s[0];
    822     *code.e++ = token.s[1];
    823     ps.want_blank = true;
    824 }
    825 
    826 static void
    827 process_question(int *seen_quest)
    828 {
    829     (*seen_quest)++;		/* this will be used when a later colon
    830 				 * appears, so we can distinguish the
    831 				 * <c>?<n>:<n> construct */
    832     if (ps.want_blank)
    833 	*code.e++ = ' ';
    834     *code.e++ = '?';
    835     ps.want_blank = true;
    836 }
    837 
    838 static void
    839 process_colon(int *seen_quest, bool *force_nl, bool *seen_case)
    840 {
    841     if (*seen_quest > 0) {	/* part of a '?:' operator */
    842 	--*seen_quest;
    843 	if (ps.want_blank)
    844 	    *code.e++ = ' ';
    845 	*code.e++ = ':';
    846 	ps.want_blank = true;
    847 	return;
    848     }
    849 
    850     if (ps.in_or_st) {		/* bit-field */
    851 	*code.e++ = ':';
    852 	ps.want_blank = false;
    853 	return;
    854     }
    855 
    856     buf_add_buf(&lab, &code);	/* 'case' or 'default' or named label */
    857     buf_add_char(&lab, ':');
    858     buf_terminate(&lab);
    859     buf_reset(&code);
    860 
    861     ps.in_stmt = false;
    862     ps.is_case_label = *seen_case;
    863     *force_nl = *seen_case;
    864     *seen_case = false;
    865     ps.want_blank = false;
    866 }
    867 
    868 static void
    869 process_semicolon(bool *seen_case, int *seen_quest, int decl_ind,
    870     bool tabs_to_var, bool *sp_sw,
    871     token_type hd_type,
    872     bool *force_nl)
    873 {
    874     if (ps.decl_nest == 0)
    875 	ps.in_or_st = false;	/* we are not in an initialization or
    876 				 * structure declaration */
    877     *seen_case = false;		/* these will only need resetting in an error */
    878     *seen_quest = 0;
    879     if (ps.last_token == rparen_or_rbracket)
    880 	ps.in_parameter_declaration = false;
    881     ps.cast_mask = 0;
    882     ps.not_cast_mask = 0;
    883     ps.block_init = false;
    884     ps.block_init_level = 0;
    885     ps.just_saw_decl--;
    886 
    887     if (ps.in_decl && code.s == code.e && !ps.block_init &&
    888 	!ps.dumped_decl_indent && ps.paren_level == 0) {
    889 	/* indent stray semicolons in declarations */
    890 	indent_declaration(decl_ind - 1, tabs_to_var);
    891 	ps.dumped_decl_indent = true;
    892     }
    893 
    894     ps.in_decl = (ps.decl_nest > 0);	/* if we were in a first level
    895 					 * structure declaration, we aren't
    896 					 * anymore */
    897 
    898     if ((!*sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
    899 
    900 	/*
    901 	 * This should be true iff there were unbalanced parens in the stmt.
    902 	 * It is a bit complicated, because the semicolon might be in a for
    903 	 * stmt
    904 	 */
    905 	diag(1, "Unbalanced parens");
    906 	ps.p_l_follow = 0;
    907 	if (*sp_sw) {		/* this is a check for an if, while, etc. with
    908 				 * unbalanced parens */
    909 	    *sp_sw = false;
    910 	    parse(hd_type);	/* don't lose the 'if', or whatever */
    911 	}
    912     }
    913     *code.e++ = ';';
    914     ps.want_blank = true;
    915     ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in the middle of a
    916 					 * stmt */
    917 
    918     if (!*sp_sw) {		/* if not if for (;;) */
    919 	parse(semicolon);	/* let parser know about end of stmt */
    920 	*force_nl = true;	/* force newline after an end of stmt */
    921     }
    922 }
    923 
    924 static void
    925 process_lbrace(bool *force_nl, bool *sp_sw, token_type hd_type,
    926     int *di_stack, int di_stack_cap, int *decl_ind)
    927 {
    928     ps.in_stmt = false;		/* don't indent the {} */
    929 
    930     if (!ps.block_init)
    931 	*force_nl = true;	/* force other stuff on same line as '{' onto
    932 				 * new line */
    933     else if (ps.block_init_level <= 0)
    934 	ps.block_init_level = 1;
    935     else
    936 	ps.block_init_level++;
    937 
    938     if (code.s != code.e && !ps.block_init) {
    939 	if (!opt.brace_same_line) {
    940 	    dump_line();
    941 	    ps.want_blank = false;
    942 	} else if (ps.in_parameter_declaration && !ps.in_or_st) {
    943 	    ps.ind_level_follow = 0;
    944 	    if (opt.function_brace_split) {	/* dump the line prior to the
    945 						 * brace ... */
    946 		dump_line();
    947 		ps.want_blank = false;
    948 	    } else		/* add a space between the decl and brace */
    949 		ps.want_blank = true;
    950 	}
    951     }
    952 
    953     if (ps.in_parameter_declaration)
    954 	prefix_blankline_requested = false;
    955 
    956     if (ps.p_l_follow > 0) {	/* check for preceding unbalanced parens */
    957 	diag(1, "Unbalanced parens");
    958 	ps.p_l_follow = 0;
    959 	if (*sp_sw) {		/* check for unclosed if, for, etc. */
    960 	    *sp_sw = false;
    961 	    parse(hd_type);
    962 	    ps.ind_level = ps.ind_level_follow;
    963 	}
    964     }
    965 
    966     if (code.s == code.e)
    967 	ps.ind_stmt = false;	/* don't indent the '{' itself */
    968     if (ps.in_decl && ps.in_or_st) {	/* this is either a structure
    969 					 * declaration or an init */
    970 	di_stack[ps.decl_nest] = *decl_ind;
    971 	if (++ps.decl_nest == di_stack_cap) {
    972 	    diag(0, "Reached internal limit of %d struct levels",
    973 		di_stack_cap);
    974 	    ps.decl_nest--;
    975 	}
    976     } else {
    977 	ps.decl_on_line = false;	/* we can't be in the middle of a
    978 					 * declaration, so don't do special
    979 					 * indentation of comments */
    980 	if (opt.blanklines_after_decl_at_top && ps.in_parameter_declaration)
    981 	    postfix_blankline_requested = true;
    982 	ps.in_parameter_declaration = false;
    983 	ps.in_decl = false;
    984     }
    985 
    986     *decl_ind = 0;
    987     parse(lbrace);
    988     if (ps.want_blank)
    989 	*code.e++ = ' ';
    990     ps.want_blank = false;
    991     *code.e++ = '{';
    992     ps.just_saw_decl = 0;
    993 }
    994 
    995 static void
    996 process_rbrace(bool *sp_sw, int *decl_ind, const int *di_stack)
    997 {
    998     if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
    999 							 * omitted in
   1000 							 * declarations */
   1001 	parse(semicolon);
   1002 
   1003     if (ps.p_l_follow != 0) {	/* check for unclosed if, for, else. */
   1004 	diag(1, "Unbalanced parens");
   1005 	ps.p_l_follow = 0;
   1006 	*sp_sw = false;
   1007     }
   1008 
   1009     ps.just_saw_decl = 0;
   1010     ps.block_init_level--;
   1011 
   1012     if (code.s != code.e && !ps.block_init) {	/* '}' must be first on line */
   1013 	if (opt.verbose)
   1014 	    diag(0, "Line broken");
   1015 	dump_line();
   1016     }
   1017 
   1018     *code.e++ = '}';
   1019     ps.want_blank = true;
   1020     ps.in_stmt = ps.ind_stmt = false;
   1021 
   1022     if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
   1023 	*decl_ind = di_stack[--ps.decl_nest];
   1024 	if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
   1025 	    ps.just_saw_decl = 2;
   1026 	ps.in_decl = true;
   1027     }
   1028 
   1029     prefix_blankline_requested = false;
   1030     parse(rbrace);		/* let parser know about this */
   1031     ps.search_brace = opt.cuddle_else
   1032 	&& ps.p_stack[ps.tos] == if_expr_stmt
   1033 	&& ps.il[ps.tos] >= ps.ind_level;
   1034 
   1035     if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
   1036 	postfix_blankline_requested = true;
   1037 }
   1038 
   1039 static void
   1040 process_keyword_do(bool *force_nl, bool *last_else)
   1041 {
   1042     ps.in_stmt = false;
   1043 
   1044     if (code.e != code.s) {	/* make sure this starts a line */
   1045 	if (opt.verbose)
   1046 	    diag(0, "Line broken");
   1047 	dump_line();
   1048 	ps.want_blank = false;
   1049     }
   1050 
   1051     *force_nl = true;		/* following stuff must go onto new line */
   1052     *last_else = false;
   1053     parse(keyword_do);
   1054 }
   1055 
   1056 static void
   1057 process_keyword_else(bool *force_nl, bool *last_else)
   1058 {
   1059     ps.in_stmt = false;
   1060 
   1061     if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
   1062 	if (opt.verbose)
   1063 	    diag(0, "Line broken");
   1064 	dump_line();		/* make sure this starts a line */
   1065 	ps.want_blank = false;
   1066     }
   1067 
   1068     *force_nl = true;		/* following stuff must go onto new line */
   1069     *last_else = true;
   1070     parse(keyword_else);
   1071 }
   1072 
   1073 static void
   1074 process_decl(int *out_decl_ind, bool *out_tabs_to_var)
   1075 {
   1076     parse(decl);		/* let parser worry about indentation */
   1077 
   1078     if (ps.last_token == rparen_or_rbracket && ps.tos <= 1) {
   1079 	if (code.s != code.e) {
   1080 	    dump_line();
   1081 	    ps.want_blank = false;
   1082 	}
   1083     }
   1084 
   1085     if (ps.in_parameter_declaration && opt.indent_parameters &&
   1086 	ps.decl_nest == 0) {
   1087 	ps.ind_level = ps.ind_level_follow = 1;
   1088 	ps.ind_stmt = false;
   1089     }
   1090 
   1091     ps.in_or_st = true;		/* this might be a structure or initialization
   1092 				 * declaration */
   1093     ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
   1094     if ( /* !ps.in_or_st && */ ps.decl_nest <= 0)
   1095 	ps.just_saw_decl = 2;
   1096 
   1097     prefix_blankline_requested = false;
   1098 
   1099     int len = (int)strlen(token.s) + 1;
   1100     int ind = ps.ind_level == 0 || ps.decl_nest > 0
   1101 	    ? opt.decl_indent		/* global variable or local member */
   1102 	    : opt.local_decl_indent;	/* local variable */
   1103     *out_decl_ind = ind > 0 ? ind : len;
   1104     *out_tabs_to_var = opt.use_tabs ? ind > 0 : false;
   1105 }
   1106 
   1107 static void
   1108 process_ident(token_type ttype, int decl_ind, bool tabs_to_var,
   1109     bool *sp_sw, bool *force_nl, token_type hd_type)
   1110 {
   1111     if (ps.in_decl) {
   1112 	if (ttype == funcname) {
   1113 	    ps.in_decl = false;
   1114 	    if (opt.procnames_start_line && code.s != code.e) {
   1115 		*code.e = '\0';
   1116 		dump_line();
   1117 	    } else if (ps.want_blank) {
   1118 		*code.e++ = ' ';
   1119 	    }
   1120 	    ps.want_blank = false;
   1121 
   1122 	} else if (!ps.block_init && !ps.dumped_decl_indent &&
   1123 	    ps.paren_level == 0) {	/* if we are in a declaration, we must
   1124 					 * indent identifier */
   1125 	    indent_declaration(decl_ind, tabs_to_var);
   1126 	    ps.dumped_decl_indent = true;
   1127 	    ps.want_blank = false;
   1128 	}
   1129 
   1130     } else if (*sp_sw && ps.p_l_follow == 0) {
   1131 	*sp_sw = false;
   1132 	*force_nl = true;
   1133 	ps.last_u_d = true;
   1134 	ps.in_stmt = false;
   1135 	parse(hd_type);
   1136     }
   1137 }
   1138 
   1139 static void
   1140 copy_token(void)
   1141 {
   1142     if (ps.want_blank)
   1143 	buf_add_char(&code, ' ');
   1144     buf_add_buf(&code, &token);
   1145 }
   1146 
   1147 static void
   1148 process_string_prefix(void)
   1149 {
   1150     copy_token();
   1151     ps.want_blank = false;
   1152 }
   1153 
   1154 static void
   1155 process_period(void)
   1156 {
   1157     if (code.e[-1] == ',')
   1158 	*code.e++ = ' ';
   1159     *code.e++ = '.';
   1160     ps.want_blank = false;
   1161 }
   1162 
   1163 static void
   1164 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
   1165 {
   1166     ps.want_blank = (code.s != code.e);	/* only put blank after comma if comma
   1167 					 * does not start the line */
   1168 
   1169     if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
   1170 	!ps.dumped_decl_indent && ps.paren_level == 0) {
   1171 	/* indent leading commas and not the actual identifiers */
   1172 	indent_declaration(decl_ind - 1, tabs_to_var);
   1173 	ps.dumped_decl_indent = true;
   1174     }
   1175 
   1176     *code.e++ = ',';
   1177 
   1178     if (ps.p_l_follow == 0) {
   1179 	if (ps.block_init_level <= 0)
   1180 	    ps.block_init = false;
   1181 	if (break_comma && (opt.break_after_comma ||
   1182 			    indentation_after_range(
   1183 				    compute_code_indent(), code.s, code.e)
   1184 			    >= opt.max_line_length - opt.tabsize))
   1185 	    *force_nl = true;
   1186     }
   1187 }
   1188 
   1189 /* move the whole line to the 'label' buffer */
   1190 static void
   1191 read_preprocessing_line(void)
   1192 {
   1193     enum {
   1194 	PLAIN, STR, CHR, COMM
   1195     } state;
   1196 
   1197     buf_add_char(&lab, '#');
   1198 
   1199     state = PLAIN;
   1200     int com_start = 0, com_end = 0;
   1201 
   1202     while (is_hspace(*inp.s))
   1203 	inbuf_skip();
   1204 
   1205     while (*inp.s != '\n' || (state == COMM && !had_eof)) {
   1206 	buf_reserve(&lab, 2);
   1207 	*lab.e++ = inbuf_next();
   1208 	switch (lab.e[-1]) {
   1209 	case '\\':
   1210 	    if (state != COMM)
   1211 		*lab.e++ = inbuf_next();
   1212 	    break;
   1213 	case '/':
   1214 	    if (*inp.s == '*' && state == PLAIN) {
   1215 		state = COMM;
   1216 		*lab.e++ = *inp.s++;
   1217 		com_start = (int)buf_len(&lab) - 2;
   1218 	    }
   1219 	    break;
   1220 	case '"':
   1221 	    if (state == STR)
   1222 		state = PLAIN;
   1223 	    else if (state == PLAIN)
   1224 		state = STR;
   1225 	    break;
   1226 	case '\'':
   1227 	    if (state == CHR)
   1228 		state = PLAIN;
   1229 	    else if (state == PLAIN)
   1230 		state = CHR;
   1231 	    break;
   1232 	case '*':
   1233 	    if (*inp.s == '/' && state == COMM) {
   1234 		state = PLAIN;
   1235 		*lab.e++ = *inp.s++;
   1236 		com_end = (int)buf_len(&lab);
   1237 	    }
   1238 	    break;
   1239 	}
   1240     }
   1241 
   1242     while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1243 	lab.e--;
   1244     if (lab.e - lab.s == com_end && saved_inp_s == NULL) {
   1245 	/* comment on preprocessor line */
   1246 	if (sc_end == NULL) {	/* if this is the first comment, we must set
   1247 				 * up the buffer */
   1248 	    save_com = sc_buf;
   1249 	    sc_end = save_com;
   1250 	} else {
   1251 	    *sc_end++ = '\n';	/* add newline between comments */
   1252 	    *sc_end++ = ' ';
   1253 	    --line_no;
   1254 	}
   1255 	if (sc_end - save_com + com_end - com_start > sc_size)
   1256 	    errx(1, "input too long");
   1257 	memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
   1258 	sc_end += com_end - com_start;
   1259 	lab.e = lab.s + com_start;
   1260 	while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1261 	    lab.e--;
   1262 	saved_inp_s = inp.s;	/* save current input buffer */
   1263 	saved_inp_e = inp.e;
   1264 	inp.s = save_com;	/* fix so that subsequent calls to lexi will
   1265 				 * take tokens out of save_com */
   1266 	*sc_end++ = ' ';	/* add trailing blank, just in case */
   1267 	inp.e = sc_end;
   1268 	sc_end = NULL;
   1269 	debug_println("switched inp.s to save_com");
   1270     }
   1271     buf_terminate(&lab);
   1272 }
   1273 
   1274 static void
   1275 process_preprocessing(void)
   1276 {
   1277     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
   1278 	dump_line();
   1279 
   1280     read_preprocessing_line();
   1281 
   1282     ps.is_case_label = false;
   1283 
   1284     if (strncmp(lab.s, "#if", 3) == 0) {	/* also ifdef, ifndef */
   1285 	if ((size_t)ifdef_level < nitems(state_stack))
   1286 	    state_stack[ifdef_level++] = ps;
   1287 	else
   1288 	    diag(1, "#if stack overflow");
   1289 
   1290     } else if (strncmp(lab.s, "#el", 3) == 0) {	/* else, elif */
   1291 	if (ifdef_level <= 0)
   1292 	    diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
   1293 	else
   1294 	    ps = state_stack[ifdef_level - 1];
   1295 
   1296     } else if (strncmp(lab.s, "#endif", 6) == 0) {
   1297 	if (ifdef_level <= 0)
   1298 	    diag(1, "Unmatched #endif");
   1299 	else
   1300 	    ifdef_level--;
   1301 
   1302     } else {
   1303 	if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
   1304 	    strncmp(lab.s + 1, "error", 5) != 0 &&
   1305 	    strncmp(lab.s + 1, "line", 4) != 0 &&
   1306 	    strncmp(lab.s + 1, "undef", 5) != 0 &&
   1307 	    strncmp(lab.s + 1, "define", 6) != 0 &&
   1308 	    strncmp(lab.s + 1, "include", 7) != 0) {
   1309 	    diag(1, "Unrecognized cpp directive");
   1310 	    return;
   1311 	}
   1312     }
   1313 
   1314     if (opt.blanklines_around_conditional_compilation) {
   1315 	postfix_blankline_requested = true;
   1316 	next_blank_lines = 0;
   1317     } else {
   1318 	postfix_blankline_requested = false;
   1319 	prefix_blankline_requested = false;
   1320     }
   1321 
   1322     /*
   1323      * subsequent processing of the newline character will cause the line to
   1324      * be printed
   1325      */
   1326 }
   1327 
   1328 static void __attribute__((__noreturn__))
   1329 main_loop(void)
   1330 {
   1331     token_type ttype;
   1332     bool force_nl;		/* when true, code must be broken */
   1333     bool last_else = false;	/* true iff last keyword was an else */
   1334     int decl_ind;		/* current indentation for declarations */
   1335     int di_stack[20];		/* a stack of structure indentation levels */
   1336     bool tabs_to_var;		/* true if using tabs to indent to var name */
   1337     bool sp_sw;			/* when true, we are in the expression of
   1338 				 * if(...), while(...), etc. */
   1339     token_type hd_type = end_of_file;	/* used to store type of stmt for if
   1340 					 * (...), for (...), etc */
   1341     int seen_quest;		/* when this is positive, we have seen a '?'
   1342 				 * without the matching ':' in a <c>?<s>:<s>
   1343 				 * construct */
   1344     bool seen_case;		/* set to true when we see a 'case', so we
   1345 				 * know what to do with the following colon */
   1346 
   1347     sp_sw = force_nl = false;
   1348     decl_ind = 0;
   1349     di_stack[ps.decl_nest = 0] = 0;
   1350     seen_case = false;
   1351     seen_quest = 0;
   1352     tabs_to_var = false;
   1353 
   1354     for (;;) {			/* this is the main loop.  it will go until we
   1355 				 * reach eof */
   1356 	bool comment_buffered = false;
   1357 
   1358 	ttype = lexi(&ps);	/* Read the next token.  The actual characters
   1359 				 * read are stored in "token". */
   1360 
   1361 	/*
   1362 	 * Move newlines and comments following an if (), while (), else, etc.
   1363 	 * up to the start of the following stmt to a buffer. This allows
   1364 	 * proper handling of both kinds of brace placement (-br, -bl) and
   1365 	 * cuddling "else" (-ce).
   1366 	 */
   1367 	search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
   1368 
   1369 	if (ttype == end_of_file) {
   1370 	    process_end_of_file();
   1371 	    /* NOTREACHED */
   1372 	}
   1373 
   1374 	if (ttype == newline || ttype == form_feed || ttype == preprocessing)
   1375 	    force_nl = false;
   1376 	else if (ttype != comment)
   1377 	    process_comment_in_code(ttype, &force_nl);
   1378 
   1379 	buf_reserve(&code, 3);	/* space for 2 characters plus '\0' */
   1380 
   1381 	switch (ttype) {
   1382 
   1383 	case form_feed:
   1384 	    process_form_feed();
   1385 	    break;
   1386 
   1387 	case newline:
   1388 	    process_newline();
   1389 	    break;
   1390 
   1391 	case lparen_or_lbracket:
   1392 	    process_lparen_or_lbracket(decl_ind, tabs_to_var, sp_sw);
   1393 	    break;
   1394 
   1395 	case rparen_or_rbracket:
   1396 	    process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
   1397 	    break;
   1398 
   1399 	case unary_op:
   1400 	    process_unary_op(decl_ind, tabs_to_var);
   1401 	    break;
   1402 
   1403 	case binary_op:
   1404 	    process_binary_op();
   1405 	    break;
   1406 
   1407 	case postfix_op:
   1408 	    process_postfix_op();
   1409 	    break;
   1410 
   1411 	case question:
   1412 	    process_question(&seen_quest);
   1413 	    break;
   1414 
   1415 	case case_label:	/* got word 'case' or 'default' */
   1416 	    seen_case = true;
   1417 	    goto copy_token;
   1418 
   1419 	case colon:
   1420 	    process_colon(&seen_quest, &force_nl, &seen_case);
   1421 	    break;
   1422 
   1423 	case semicolon:
   1424 	    process_semicolon(&seen_case, &seen_quest, decl_ind, tabs_to_var,
   1425 		&sp_sw, hd_type, &force_nl);
   1426 	    break;
   1427 
   1428 	case lbrace:
   1429 	    process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
   1430 		(int)nitems(di_stack), &decl_ind);
   1431 	    break;
   1432 
   1433 	case rbrace:
   1434 	    process_rbrace(&sp_sw, &decl_ind, di_stack);
   1435 	    break;
   1436 
   1437 	case switch_expr:	/* got keyword "switch" */
   1438 	    sp_sw = true;
   1439 	    hd_type = switch_expr;	/* keep this for when we have seen the
   1440 					 * expression */
   1441 	    goto copy_token;
   1442 
   1443 	case keyword_for_if_while:
   1444 	    sp_sw = true;	/* the interesting stuff is done after the
   1445 				 * expression is scanned */
   1446 	    hd_type = (*token.s == 'i' ? if_expr :
   1447 		(*token.s == 'w' ? while_expr : for_exprs));
   1448 
   1449 	    /* remember the type of header for later use by parser */
   1450 	    goto copy_token;
   1451 
   1452 	case keyword_do_else:
   1453 	    if (*token.s == 'd')
   1454 		process_keyword_do(&force_nl, &last_else);
   1455 	    else
   1456 		process_keyword_else(&force_nl, &last_else);
   1457 	    goto copy_token;
   1458 
   1459 	case type_def:
   1460 	case storage_class:
   1461 	    prefix_blankline_requested = false;
   1462 	    goto copy_token;
   1463 
   1464 	case keyword_struct_union_enum:
   1465 	    if (ps.p_l_follow > 0)
   1466 		goto copy_token;
   1467 	    /* FALLTHROUGH */
   1468 	case decl:		/* a declaration type (int, etc.) */
   1469 	    process_decl(&decl_ind, &tabs_to_var);
   1470 	    goto copy_token;
   1471 
   1472 	case funcname:
   1473 	case ident:		/* an identifier, constant or string */
   1474 	    process_ident(ttype, decl_ind, tabs_to_var, &sp_sw, &force_nl,
   1475 		hd_type);
   1476     copy_token:
   1477 	    copy_token();
   1478 	    if (ttype != funcname)
   1479 		ps.want_blank = true;
   1480 	    break;
   1481 
   1482 	case string_prefix:
   1483 	    process_string_prefix();
   1484 	    break;
   1485 
   1486 	case period:
   1487 	    process_period();
   1488 	    break;
   1489 
   1490 	case comma:
   1491 	    process_comma(decl_ind, tabs_to_var, &force_nl);
   1492 	    break;
   1493 
   1494 	case preprocessing:	/* the initial '#' */
   1495 	    process_preprocessing();
   1496 	    break;
   1497 
   1498 	case comment:		/* the initial '/' '*' or '//' of a comment */
   1499 	    process_comment();
   1500 	    break;
   1501 
   1502 	default:
   1503 	    break;
   1504 	}
   1505 
   1506 	*code.e = '\0';
   1507 	if (ttype != comment && ttype != newline && ttype != preprocessing)
   1508 	    ps.last_token = ttype;
   1509     }
   1510 }
   1511 
   1512 int
   1513 main(int argc, char **argv)
   1514 {
   1515     main_init_globals();
   1516     main_parse_command_line(argc, argv);
   1517 #if HAVE_CAPSICUM
   1518     init_capsicum();
   1519 #endif
   1520     main_prepare_parsing();
   1521     main_loop();
   1522 }
   1523 
   1524 #ifdef debug
   1525 void
   1526 debug_printf(const char *fmt, ...)
   1527 {
   1528     FILE *f = output == stdout ? stderr : stdout;
   1529     va_list ap;
   1530 
   1531     va_start(ap, fmt);
   1532     vfprintf(f, fmt, ap);
   1533     va_end(ap);
   1534 }
   1535 
   1536 void
   1537 debug_println(const char *fmt, ...)
   1538 {
   1539     FILE *f = output == stdout ? stderr : stdout;
   1540     va_list ap;
   1541 
   1542     va_start(ap, fmt);
   1543     vfprintf(f, fmt, ap);
   1544     va_end(ap);
   1545     fprintf(f, "\n");
   1546 }
   1547 
   1548 void
   1549 debug_vis_range(const char *prefix, const char *s, const char *e,
   1550     const char *suffix)
   1551 {
   1552     debug_printf("%s", prefix);
   1553     for (const char *p = s; p < e; p++) {
   1554 	if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
   1555 	    debug_printf("%c", *p);
   1556 	else if (*p == '\n')
   1557 	    debug_printf("\\n");
   1558 	else if (*p == '\t')
   1559 	    debug_printf("\\t");
   1560 	else
   1561 	    debug_printf("\\x%02x", *p);
   1562     }
   1563     debug_printf("%s", suffix);
   1564 }
   1565 #endif
   1566 
   1567 static void *
   1568 nonnull(void *p)
   1569 {
   1570     if (p == NULL)
   1571 	err(EXIT_FAILURE, NULL);
   1572     return p;
   1573 }
   1574 
   1575 void *
   1576 xmalloc(size_t size)
   1577 {
   1578     return nonnull(malloc(size));
   1579 }
   1580 
   1581 void *
   1582 xrealloc(void *p, size_t new_size)
   1583 {
   1584     return nonnull(realloc(p, new_size));
   1585 }
   1586 
   1587 char *
   1588 xstrdup(const char *s)
   1589 {
   1590     return nonnull(strdup(s));
   1591 }
   1592