Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.145
      1 /*	$NetBSD: indent.c,v 1.145 2021/10/24 11:17:05 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.145 2021/10/24 11:17:05 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 blank_lines_to_output;
    106 bool blank_line_before;
    107 bool blank_line_after;
    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     /* XXX: buffer overflow? This is essentially a strcpy. */
    268     for (const char *t_ptr = token.s; *t_ptr != '\0'; ++t_ptr)
    269 	*sc_end++ = *t_ptr;
    270     return true;
    271 }
    272 
    273 static void
    274 switch_buffer(void)
    275 {
    276     ps.search_brace = false;	/* stop looking for start of stmt */
    277     saved_inp_s = inp.s;	/* save current input buffer */
    278     saved_inp_e = inp.e;
    279     inp.s = save_com;		/* fix so that subsequent calls to lexi will
    280 				 * take tokens out of save_com */
    281     *sc_end++ = ' ';		/* add trailing blank, just in case */
    282     inp.e = sc_end;
    283     sc_end = NULL;
    284     debug_println("switched inp.s to save_com");
    285 }
    286 
    287 static void
    288 search_brace_lookahead(token_type *ttype)
    289 {
    290     if (*ttype == end_of_file)
    291 	return;
    292 
    293     /*
    294      * The only intended purpose of calling lexi() below is to categorize
    295      * the next token in order to decide whether to continue buffering
    296      * forthcoming tokens. Once the buffering is over, lexi() will be
    297      * called again elsewhere on all of the tokens - this time for normal
    298      * processing.
    299      *
    300      * Calling it for this purpose is a bug, because lexi() also changes
    301      * the parser state and discards leading whitespace, which is needed
    302      * mostly for comment-related considerations.
    303      *
    304      * Work around the former problem by giving lexi() a copy of the
    305      * current parser state and discard it if the call turned out to be
    306      * just a lookahead.
    307      *
    308      * Work around the latter problem by copying all whitespace characters
    309      * into the buffer so that the later lexi() call will read them.
    310      */
    311     if (sc_end != NULL) {
    312 	while (is_hspace(*inp.s)) {
    313 	    *sc_end++ = *inp.s++;
    314 	    if (sc_end >= &save_com[sc_size])
    315 		errx(1, "input too long");
    316 	}
    317 	if (inp.s >= inp.e)
    318 	    inbuf_read_line();
    319     }
    320 
    321     struct parser_state transient_state;
    322     transient_state = ps;
    323     *ttype = lexi(&transient_state);	/* read another token */
    324     if (*ttype != newline && *ttype != form_feed &&
    325 	*ttype != comment && !transient_state.search_brace) {
    326 	ps = transient_state;
    327     }
    328 }
    329 
    330 static void
    331 search_brace(token_type *ttype, bool *force_nl,
    332     bool *comment_buffered, bool *last_else)
    333 {
    334     while (ps.search_brace) {
    335 	switch (*ttype) {
    336 	case newline:
    337 	    search_brace_newline(force_nl);
    338 	    break;
    339 	case form_feed:
    340 	    break;
    341 	case comment:
    342 	    search_brace_comment(comment_buffered);
    343 	    break;
    344 	case lbrace:
    345 	    if (search_brace_lbrace())
    346 		goto switch_buffer;
    347 	    /* FALLTHROUGH */
    348 	default:		/* it is the start of a normal statement */
    349 	    if (!search_brace_other(*ttype, force_nl,
    350 		    *comment_buffered, *last_else))
    351 		return;
    352 	switch_buffer:
    353 	    switch_buffer();
    354 	}
    355 	search_brace_lookahead(ttype);
    356     }
    357 
    358     *last_else = false;
    359 }
    360 
    361 static void
    362 buf_init(struct buffer *buf)
    363 {
    364     size_t size = 200;
    365     buf->buf = xmalloc(size);
    366     buf->buf[0] = ' ';		/* allow accessing buf->e[-1] */
    367     buf->buf[1] = '\0';
    368     buf->s = buf->buf + 1;
    369     buf->e = buf->s;
    370     buf->l = buf->buf + size - 5;	/* safety margin */
    371 }
    372 
    373 static size_t
    374 buf_len(const struct buffer *buf)
    375 {
    376     return (size_t)(buf->e - buf->s);
    377 }
    378 
    379 void
    380 buf_expand(struct buffer *buf, size_t desired_size)
    381 {
    382     size_t nsize = (size_t)(buf->l - buf->s) + 400 + desired_size;
    383     size_t len = buf_len(buf);
    384     buf->buf = xrealloc(buf->buf, nsize);
    385     buf->e = buf->buf + len + 1;
    386     buf->l = buf->buf + nsize - 5;
    387     buf->s = buf->buf + 1;
    388 }
    389 
    390 static void
    391 buf_reserve(struct buffer *buf, size_t n)
    392 {
    393     if (buf->e + n >= buf->l)
    394 	buf_expand(buf, n);
    395 }
    396 
    397 static void
    398 buf_add_char(struct buffer *buf, char ch)
    399 {
    400     buf_reserve(buf, 1);
    401     *buf->e++ = ch;
    402 }
    403 
    404 static void
    405 buf_add_buf(struct buffer *buf, const struct buffer *add)
    406 {
    407     size_t len = buf_len(add);
    408     buf_reserve(buf, len);
    409     memcpy(buf->e, add->s, len);
    410     buf->e += len;
    411 }
    412 
    413 static void
    414 buf_terminate(struct buffer *buf)
    415 {
    416     buf_reserve(buf, 1);
    417     *buf->e = '\0';
    418 }
    419 
    420 static void
    421 buf_reset(struct buffer *buf)
    422 {
    423     buf->e = buf->s;
    424 }
    425 
    426 static void
    427 main_init_globals(void)
    428 {
    429     found_err = false;
    430 
    431     ps.s_ttype[0] = stmt;
    432     ps.last_nl = true;
    433     ps.last_token = semicolon;
    434     buf_init(&com);
    435     buf_init(&lab);
    436     buf_init(&code);
    437     buf_init(&token);
    438 
    439     opt.else_if = true;		/* XXX: redundant? */
    440 
    441     inp.buf = xmalloc(10);
    442     inp.l = inp.buf + 8;
    443     inp.s = inp.e = inp.buf;
    444     line_no = 1;
    445     had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
    446 
    447     ps.init_or_struct = false;
    448     ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
    449     ps.is_case_label = false;
    450 
    451     sc_end = NULL;
    452     saved_inp_s = NULL;
    453     saved_inp_e = NULL;
    454 
    455     output = NULL;
    456 
    457     const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
    458     if (suffix != NULL)
    459 	backup_suffix = suffix;
    460 }
    461 
    462 /*
    463  * Copy the input file to the backup file, then make the backup file the input
    464  * and the original input file the output.
    465  */
    466 static void
    467 bakcopy(void)
    468 {
    469     ssize_t n;
    470     int bak_fd;
    471     char buff[8 * 1024];
    472 
    473     const char *last_slash = strrchr(in_name, '/');
    474     snprintf(bakfile, sizeof(bakfile), "%s%s",
    475 	     last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
    476 
    477     /* copy in_name to backup file */
    478     bak_fd = creat(bakfile, 0600);
    479     if (bak_fd < 0)
    480 	err(1, "%s", bakfile);
    481 
    482     while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
    483 	if (write(bak_fd, buff, (size_t)n) != n)
    484 	    err(1, "%s", bakfile);
    485     if (n < 0)
    486 	err(1, "%s", in_name);
    487 
    488     close(bak_fd);
    489     (void)fclose(input);
    490 
    491     /* re-open backup file as the input file */
    492     input = fopen(bakfile, "r");
    493     if (input == NULL)
    494 	err(1, "%s", bakfile);
    495     /* now the original input file will be the output */
    496     output = fopen(in_name, "w");
    497     if (output == NULL) {
    498 	unlink(bakfile);
    499 	err(1, "%s", in_name);
    500     }
    501 }
    502 
    503 static void
    504 main_parse_command_line(int argc, char **argv)
    505 {
    506     int i;
    507     const char *profile_name = NULL;
    508 
    509     for (i = 1; i < argc; ++i)
    510 	if (strcmp(argv[i], "-npro") == 0)
    511 	    break;
    512 	else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0')
    513 	    profile_name = argv[i] + 2;	/* non-empty -P (set profile) */
    514     if (i >= argc)
    515 	load_profiles(profile_name);
    516 
    517     for (i = 1; i < argc; ++i) {
    518 	if (argv[i][0] == '-') {
    519 	    set_option(argv[i], "Command line");
    520 
    521 	} else if (input == NULL) {
    522 	    in_name = argv[i];
    523 	    input = fopen(in_name, "r");
    524 	    if (input == NULL)
    525 		err(1, "%s", in_name);
    526 
    527 	} else if (output == NULL) {
    528 	    out_name = argv[i];
    529 	    if (strcmp(in_name, out_name) == 0)
    530 		errx(1, "input and output files must be different");
    531 	    output = fopen(out_name, "w");
    532 	    if (output == NULL)
    533 		err(1, "%s", out_name);
    534 
    535 	} else
    536 	    errx(1, "unknown parameter: %s", argv[i]);
    537     }
    538 
    539     if (input == NULL)
    540 	input = stdin;
    541     if (output == NULL) {
    542 	if (input == stdin)
    543 	    output = stdout;
    544 	else {
    545 	    out_name = in_name;
    546 	    bakcopy();
    547 	}
    548     }
    549 
    550     if (opt.comment_column <= 1)
    551 	opt.comment_column = 2;	/* don't put normal comments before column 2 */
    552     if (opt.block_comment_max_line_length <= 0)
    553 	opt.block_comment_max_line_length = opt.max_line_length;
    554     if (opt.local_decl_indent < 0)	/* if not specified by user, set this */
    555 	opt.local_decl_indent = opt.decl_indent;
    556     if (opt.decl_comment_column <= 0)	/* if not specified by user, set this */
    557 	opt.decl_comment_column = opt.ljust_decl
    558 	    ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
    559 	    : opt.comment_column;
    560     if (opt.continuation_indent == 0)
    561 	opt.continuation_indent = opt.indent_size;
    562 }
    563 
    564 static void
    565 main_prepare_parsing(void)
    566 {
    567     inbuf_read_line();
    568 
    569     parse(semicolon);
    570 
    571     int ind = 0;
    572     for (const char *p = inp.s;; p++) {
    573 	if (*p == ' ')
    574 	    ind++;
    575 	else if (*p == '\t')
    576 	    ind = next_tab(ind);
    577 	else
    578 	    break;
    579     }
    580 
    581     if (ind >= opt.indent_size)
    582 	ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
    583 }
    584 
    585 static void
    586 indent_declaration(int cur_decl_ind, bool tabs_to_var)
    587 {
    588     int ind = (int)buf_len(&code);
    589     char *orig_code_e = code.e;
    590 
    591     /*
    592      * get the tab math right for indentations that are not multiples of
    593      * tabsize
    594      */
    595     if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
    596 	ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
    597 	cur_decl_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
    598     }
    599 
    600     if (tabs_to_var) {
    601 	for (int next; (next = next_tab(ind)) <= cur_decl_ind; ind = next)
    602 	    buf_add_char(&code, '\t');
    603     }
    604 
    605     for (; ind < cur_decl_ind; ind++)
    606 	buf_add_char(&code, ' ');
    607 
    608     if (code.e == orig_code_e && ps.want_blank) {
    609 	*code.e++ = ' ';
    610 	ps.want_blank = false;
    611     }
    612 }
    613 
    614 static void __attribute__((__noreturn__))
    615 process_end_of_file(void)
    616 {
    617     if (lab.s != lab.e || code.s != code.e || com.s != com.e)
    618 	dump_line();
    619 
    620     if (ps.tos > 1)		/* check for balanced braces */
    621 	diag(1, "Stuff missing from end of file");
    622 
    623     if (opt.verbose) {
    624 	printf("There were %d output lines and %d comments\n",
    625 	    ps.stats.lines, ps.stats.comments);
    626 	printf("(Lines with comments)/(Lines with code): %6.3f\n",
    627 	    (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
    628     }
    629 
    630     fflush(output);
    631     exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
    632 }
    633 
    634 static void
    635 process_comment_in_code(token_type ttype, bool *force_nl)
    636 {
    637     if (*force_nl &&
    638 	ttype != semicolon &&
    639 	(ttype != lbrace || !opt.brace_same_line)) {
    640 
    641 	/* we should force a broken line here */
    642 	if (opt.verbose)
    643 	    diag(0, "Line broken");
    644 	dump_line();
    645 	ps.want_blank = false;	/* don't insert blank at line start */
    646 	*force_nl = false;
    647     }
    648 
    649     /* add an extra level of indentation; turned off again by a ';' or '}' */
    650     ps.in_stmt = true;
    651 
    652     if (com.s != com.e) {	/* a comment embedded in a line */
    653 	buf_add_char(&code, ' ');
    654 	buf_add_buf(&code, &com);
    655 	buf_add_char(&code, ' ');
    656 	buf_terminate(&code);
    657 	buf_reset(&com);
    658 	ps.want_blank = false;
    659     }
    660 }
    661 
    662 static void
    663 process_form_feed(void)
    664 {
    665     dump_line_ff();
    666     ps.want_blank = false;
    667 }
    668 
    669 static void
    670 process_newline(void)
    671 {
    672     if (ps.last_token == comma && ps.p_l_follow == 0 && !ps.block_init &&
    673 	!opt.break_after_comma && break_comma &&
    674 	com.s == com.e)
    675 	goto stay_in_line;
    676 
    677     dump_line();
    678     ps.want_blank = false;
    679 
    680 stay_in_line:
    681     ++line_no;
    682 }
    683 
    684 static bool
    685 want_blank_before_lparen(void)
    686 {
    687     if (!ps.want_blank)
    688 	return false;
    689     if (ps.last_token == rparen_or_rbracket)
    690 	return false;
    691     if (ps.last_token != ident && ps.last_token != funcname)
    692 	return true;
    693     if (opt.proc_calls_space)
    694 	return true;
    695     if (ps.keyword == kw_sizeof)
    696 	return opt.blank_after_sizeof;
    697     return ps.keyword != kw_0 && ps.keyword != kw_offsetof;
    698 }
    699 
    700 static void
    701 process_lparen_or_lbracket(int decl_ind, bool tabs_to_var, bool sp_sw)
    702 {
    703     if (++ps.p_l_follow == nitems(ps.paren_indents)) {
    704 	diag(0, "Reached internal limit of %zu unclosed parens",
    705 	    nitems(ps.paren_indents));
    706 	ps.p_l_follow--;
    707     }
    708 
    709     if (token.s[0] == '(' && ps.in_decl
    710 	&& !ps.block_init && !ps.dumped_decl_indent &&
    711 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    712 	/* function pointer declarations */
    713 	indent_declaration(decl_ind, tabs_to_var);
    714 	ps.dumped_decl_indent = true;
    715     } else if (want_blank_before_lparen())
    716 	*code.e++ = ' ';
    717     ps.want_blank = false;
    718     *code.e++ = token.s[0];
    719 
    720     ps.paren_indents[ps.p_l_follow - 1] =
    721 	(short)indentation_after_range(0, code.s, code.e);
    722     debug_println("paren_indents[%d] is now %d",
    723 	ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
    724 
    725     if (sp_sw && ps.p_l_follow == 1 && opt.extra_expr_indent
    726 	    && ps.paren_indents[0] < 2 * opt.indent_size) {
    727 	ps.paren_indents[0] = (short)(2 * opt.indent_size);
    728 	debug_println("paren_indents[0] is now %d", ps.paren_indents[0]);
    729     }
    730 
    731     if (ps.init_or_struct && *token.s == '(' && ps.tos <= 2) {
    732 	/*
    733 	 * this is a kluge to make sure that declarations will be aligned
    734 	 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
    735 	 */
    736 	parse(semicolon);	/* I said this was a kluge... */
    737 	ps.init_or_struct = false;
    738     }
    739 
    740     /* parenthesized type following sizeof or offsetof is not a cast */
    741     if (ps.keyword == kw_offsetof || ps.keyword == kw_sizeof)
    742 	ps.not_cast_mask |= 1 << ps.p_l_follow;
    743 }
    744 
    745 static void
    746 process_rparen_or_rbracket(bool *sp_sw, bool *force_nl,
    747     token_type hd_type)
    748 {
    749     if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
    750 	ps.next_unary = true;
    751 	ps.cast_mask &= (1 << ps.p_l_follow) - 1;
    752 	ps.want_blank = opt.space_after_cast;
    753     } else
    754 	ps.want_blank = true;
    755     ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
    756 
    757     if (--ps.p_l_follow < 0) {
    758 	ps.p_l_follow = 0;
    759 	diag(0, "Extra %c", *token.s);
    760     }
    761 
    762     if (code.e == code.s)	/* if the paren starts the line */
    763 	ps.paren_level = ps.p_l_follow;	/* then indent it */
    764 
    765     *code.e++ = token.s[0];
    766 
    767     if (*sp_sw && ps.p_l_follow == 0) {	/* check for end of if (...), or some
    768 					 * such */
    769 	*sp_sw = false;
    770 	*force_nl = true;	/* must force newline after if */
    771 	ps.next_unary = true;
    772 	ps.in_stmt = false;	/* don't use stmt continuation indentation */
    773 
    774 	parse(hd_type);		/* let parser worry about if, or whatever */
    775     }
    776 
    777     /*
    778      * This should ensure that constructs such as main(){...} and int[]{...}
    779      * have their braces put in the right place.
    780      */
    781     ps.search_brace = opt.brace_same_line;
    782 }
    783 
    784 static void
    785 process_unary_op(int decl_ind, bool tabs_to_var)
    786 {
    787     if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
    788 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    789 	/* pointer declarations */
    790 	indent_declaration(decl_ind - (int)buf_len(&token), tabs_to_var);
    791 	ps.dumped_decl_indent = true;
    792     } else if (ps.want_blank)
    793 	*code.e++ = ' ';
    794 
    795     buf_add_buf(&code, &token);
    796     ps.want_blank = false;
    797 }
    798 
    799 static void
    800 process_binary_op(void)
    801 {
    802     if (ps.want_blank)
    803 	buf_add_char(&code, ' ');
    804     buf_add_buf(&code, &token);
    805     ps.want_blank = true;
    806 }
    807 
    808 static void
    809 process_postfix_op(void)
    810 {
    811     *code.e++ = token.s[0];
    812     *code.e++ = token.s[1];
    813     ps.want_blank = true;
    814 }
    815 
    816 static void
    817 process_question(int *seen_quest)
    818 {
    819     (*seen_quest)++;
    820     if (ps.want_blank)
    821 	*code.e++ = ' ';
    822     *code.e++ = '?';
    823     ps.want_blank = true;
    824 }
    825 
    826 static void
    827 process_colon(int *seen_quest, bool *force_nl, bool *seen_case)
    828 {
    829     if (*seen_quest > 0) {	/* part of a '?:' operator */
    830 	--*seen_quest;
    831 	if (ps.want_blank)
    832 	    *code.e++ = ' ';
    833 	*code.e++ = ':';
    834 	ps.want_blank = true;
    835 	return;
    836     }
    837 
    838     if (ps.init_or_struct) {		/* bit-field */
    839 	*code.e++ = ':';
    840 	ps.want_blank = false;
    841 	return;
    842     }
    843 
    844     buf_add_buf(&lab, &code);	/* 'case' or 'default' or named label */
    845     buf_add_char(&lab, ':');
    846     buf_terminate(&lab);
    847     buf_reset(&code);
    848 
    849     ps.in_stmt = false;
    850     ps.is_case_label = *seen_case;
    851     *force_nl = *seen_case;
    852     *seen_case = false;
    853     ps.want_blank = false;
    854 }
    855 
    856 static void
    857 process_semicolon(bool *seen_case, int *seen_quest, int decl_ind,
    858     bool tabs_to_var, bool *sp_sw,
    859     token_type hd_type,
    860     bool *force_nl)
    861 {
    862     if (ps.decl_nest == 0)
    863 	ps.init_or_struct = false;
    864     *seen_case = false;		/* these will only need resetting in an error */
    865     *seen_quest = 0;
    866     if (ps.last_token == rparen_or_rbracket)
    867 	ps.in_parameter_declaration = false;
    868     ps.cast_mask = 0;
    869     ps.not_cast_mask = 0;
    870     ps.block_init = false;
    871     ps.block_init_level = 0;
    872     ps.just_saw_decl--;
    873 
    874     if (ps.in_decl && code.s == code.e && !ps.block_init &&
    875 	!ps.dumped_decl_indent && ps.paren_level == 0) {
    876 	/* indent stray semicolons in declarations */
    877 	indent_declaration(decl_ind - 1, tabs_to_var);
    878 	ps.dumped_decl_indent = true;
    879     }
    880 
    881     ps.in_decl = ps.decl_nest > 0;	/* if we were in a first level
    882 					 * structure declaration, we aren't
    883 					 * anymore */
    884 
    885     if ((!*sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
    886 
    887 	/*
    888 	 * There were unbalanced parens in the statement. It is a bit
    889 	 * complicated, because the semicolon might be in a for statement.
    890 	 */
    891 	diag(1, "Unbalanced parens");
    892 	ps.p_l_follow = 0;
    893 	if (*sp_sw) {		/* this is a check for an if, while, etc. with
    894 				 * unbalanced parens */
    895 	    *sp_sw = false;
    896 	    parse(hd_type);	/* don't lose the 'if', or whatever */
    897 	}
    898     }
    899     *code.e++ = ';';
    900     ps.want_blank = true;
    901     ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in the middle of a
    902 					 * stmt */
    903 
    904     if (!*sp_sw) {		/* if not if for (;;) */
    905 	parse(semicolon);	/* let parser know about end of stmt */
    906 	*force_nl = true;	/* force newline after an end of stmt */
    907     }
    908 }
    909 
    910 static void
    911 process_lbrace(bool *force_nl, bool *sp_sw, token_type hd_type,
    912     int *di_stack, int di_stack_cap, int *decl_ind)
    913 {
    914     ps.in_stmt = false;		/* don't indent the {} */
    915 
    916     if (!ps.block_init)
    917 	*force_nl = true;	/* force other stuff on same line as '{' onto
    918 				 * new line */
    919     else if (ps.block_init_level <= 0)
    920 	ps.block_init_level = 1;
    921     else
    922 	ps.block_init_level++;
    923 
    924     if (code.s != code.e && !ps.block_init) {
    925 	if (!opt.brace_same_line) {
    926 	    dump_line();
    927 	    ps.want_blank = false;
    928 	} else if (ps.in_parameter_declaration && !ps.init_or_struct) {
    929 	    ps.ind_level_follow = 0;
    930 	    if (opt.function_brace_split) {	/* dump the line prior to the
    931 						 * brace ... */
    932 		dump_line();
    933 		ps.want_blank = false;
    934 	    } else		/* add a space between the decl and brace */
    935 		ps.want_blank = true;
    936 	}
    937     }
    938 
    939     if (ps.in_parameter_declaration)
    940 	blank_line_before = false;
    941 
    942     if (ps.p_l_follow > 0) {	/* check for preceding unbalanced parens */
    943 	diag(1, "Unbalanced parens");
    944 	ps.p_l_follow = 0;
    945 	if (*sp_sw) {		/* check for unclosed if, for, etc. */
    946 	    *sp_sw = false;
    947 	    parse(hd_type);
    948 	    ps.ind_level = ps.ind_level_follow;
    949 	}
    950     }
    951 
    952     if (code.s == code.e)
    953 	ps.ind_stmt = false;	/* don't indent the '{' itself */
    954     if (ps.in_decl && ps.init_or_struct) {
    955 	di_stack[ps.decl_nest] = *decl_ind;
    956 	if (++ps.decl_nest == di_stack_cap) {
    957 	    diag(0, "Reached internal limit of %d struct levels",
    958 		di_stack_cap);
    959 	    ps.decl_nest--;
    960 	}
    961     } else {
    962 	ps.decl_on_line = false;	/* we can't be in the middle of a
    963 					 * declaration, so don't do special
    964 					 * indentation of comments */
    965 	if (opt.blanklines_after_decl_at_top && ps.in_parameter_declaration)
    966 	    blank_line_after = true;
    967 	ps.in_parameter_declaration = false;
    968 	ps.in_decl = false;
    969     }
    970 
    971     *decl_ind = 0;
    972     parse(lbrace);
    973     if (ps.want_blank)
    974 	*code.e++ = ' ';
    975     ps.want_blank = false;
    976     *code.e++ = '{';
    977     ps.just_saw_decl = 0;
    978 }
    979 
    980 static void
    981 process_rbrace(bool *sp_sw, int *decl_ind, const int *di_stack)
    982 {
    983     if (ps.s_ttype[ps.tos] == decl && !ps.block_init)	/* semicolons can be
    984 							 * omitted in
    985 							 * declarations */
    986 	parse(semicolon);
    987 
    988     if (ps.p_l_follow != 0) {	/* check for unclosed if, for, else. */
    989 	diag(1, "Unbalanced parens");
    990 	ps.p_l_follow = 0;
    991 	*sp_sw = false;
    992     }
    993 
    994     ps.just_saw_decl = 0;
    995     ps.block_init_level--;
    996 
    997     if (code.s != code.e && !ps.block_init) {	/* '}' must be first on line */
    998 	if (opt.verbose)
    999 	    diag(0, "Line broken");
   1000 	dump_line();
   1001     }
   1002 
   1003     *code.e++ = '}';
   1004     ps.want_blank = true;
   1005     ps.in_stmt = ps.ind_stmt = false;
   1006 
   1007     if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
   1008 	*decl_ind = di_stack[--ps.decl_nest];
   1009 	if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
   1010 	    ps.just_saw_decl = 2;
   1011 	ps.in_decl = true;
   1012     }
   1013 
   1014     blank_line_before = false;
   1015     parse(rbrace);		/* let parser know about this */
   1016     ps.search_brace = opt.cuddle_else
   1017 	&& ps.s_ttype[ps.tos] == if_expr_stmt
   1018 	&& ps.s_ind_level[ps.tos] >= ps.ind_level;
   1019 
   1020     if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
   1021 	blank_line_after = true;
   1022 }
   1023 
   1024 static void
   1025 process_keyword_do(bool *force_nl, bool *last_else)
   1026 {
   1027     ps.in_stmt = false;
   1028 
   1029     if (code.e != code.s) {	/* make sure this starts a line */
   1030 	if (opt.verbose)
   1031 	    diag(0, "Line broken");
   1032 	dump_line();
   1033 	ps.want_blank = false;
   1034     }
   1035 
   1036     *force_nl = true;		/* following stuff must go onto new line */
   1037     *last_else = false;
   1038     parse(keyword_do);
   1039 }
   1040 
   1041 static void
   1042 process_keyword_else(bool *force_nl, bool *last_else)
   1043 {
   1044     ps.in_stmt = false;
   1045 
   1046     if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
   1047 	if (opt.verbose)
   1048 	    diag(0, "Line broken");
   1049 	dump_line();		/* make sure this starts a line */
   1050 	ps.want_blank = false;
   1051     }
   1052 
   1053     *force_nl = true;		/* following stuff must go onto new line */
   1054     *last_else = true;
   1055     parse(keyword_else);
   1056 }
   1057 
   1058 static void
   1059 process_decl(int *decl_ind, bool *tabs_to_var)
   1060 {
   1061     parse(decl);		/* let parser worry about indentation */
   1062 
   1063     if (ps.last_token == rparen_or_rbracket && ps.tos <= 1) {
   1064 	if (code.s != code.e) {
   1065 	    dump_line();
   1066 	    ps.want_blank = false;
   1067 	}
   1068     }
   1069 
   1070     if (ps.in_parameter_declaration && opt.indent_parameters &&
   1071 	ps.decl_nest == 0) {
   1072 	ps.ind_level = ps.ind_level_follow = 1;
   1073 	ps.ind_stmt = false;
   1074     }
   1075 
   1076     ps.init_or_struct = /* maybe */ true;
   1077     ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
   1078     if (ps.decl_nest <= 0)
   1079 	ps.just_saw_decl = 2;
   1080 
   1081     blank_line_before = false;
   1082 
   1083     int len = (int)buf_len(&token) + 1;
   1084     int ind = ps.ind_level == 0 || ps.decl_nest > 0
   1085 	    ? opt.decl_indent		/* global variable or local member */
   1086 	    : opt.local_decl_indent;	/* local variable */
   1087     *decl_ind = ind > 0 ? ind : len;
   1088     *tabs_to_var = opt.use_tabs && ind > 0;
   1089 }
   1090 
   1091 static void
   1092 process_ident(token_type ttype, int decl_ind, bool tabs_to_var,
   1093     bool *sp_sw, bool *force_nl, token_type hd_type)
   1094 {
   1095     if (ps.in_decl) {
   1096 	if (ttype == funcname) {
   1097 	    ps.in_decl = false;
   1098 	    if (opt.procnames_start_line && code.s != code.e) {
   1099 		*code.e = '\0';
   1100 		dump_line();
   1101 	    } else if (ps.want_blank) {
   1102 		*code.e++ = ' ';
   1103 	    }
   1104 	    ps.want_blank = false;
   1105 
   1106 	} else if (!ps.block_init && !ps.dumped_decl_indent &&
   1107 	    ps.paren_level == 0) {	/* if we are in a declaration, we must
   1108 					 * indent identifier */
   1109 	    indent_declaration(decl_ind, tabs_to_var);
   1110 	    ps.dumped_decl_indent = true;
   1111 	    ps.want_blank = false;
   1112 	}
   1113 
   1114     } else if (*sp_sw && ps.p_l_follow == 0) {
   1115 	*sp_sw = false;
   1116 	*force_nl = true;
   1117 	ps.next_unary = true;
   1118 	ps.in_stmt = false;
   1119 	parse(hd_type);
   1120     }
   1121 }
   1122 
   1123 static void
   1124 copy_token(void)
   1125 {
   1126     if (ps.want_blank)
   1127 	buf_add_char(&code, ' ');
   1128     buf_add_buf(&code, &token);
   1129 }
   1130 
   1131 static void
   1132 process_string_prefix(void)
   1133 {
   1134     copy_token();
   1135     ps.want_blank = false;
   1136 }
   1137 
   1138 static void
   1139 process_period(void)
   1140 {
   1141     if (code.e[-1] == ',')
   1142 	*code.e++ = ' ';
   1143     *code.e++ = '.';
   1144     ps.want_blank = false;
   1145 }
   1146 
   1147 static void
   1148 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
   1149 {
   1150     ps.want_blank = code.s != code.e;	/* only put blank after comma if comma
   1151 					 * does not start the line */
   1152 
   1153     if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
   1154 	!ps.dumped_decl_indent && ps.paren_level == 0) {
   1155 	/* indent leading commas and not the actual identifiers */
   1156 	indent_declaration(decl_ind - 1, tabs_to_var);
   1157 	ps.dumped_decl_indent = true;
   1158     }
   1159 
   1160     *code.e++ = ',';
   1161 
   1162     if (ps.p_l_follow == 0) {
   1163 	if (ps.block_init_level <= 0)
   1164 	    ps.block_init = false;
   1165 	if (break_comma && (opt.break_after_comma ||
   1166 			    indentation_after_range(
   1167 				    compute_code_indent(), code.s, code.e)
   1168 			    >= opt.max_line_length - opt.tabsize))
   1169 	    *force_nl = true;
   1170     }
   1171 }
   1172 
   1173 /* move the whole line to the 'label' buffer */
   1174 static void
   1175 read_preprocessing_line(void)
   1176 {
   1177     enum {
   1178 	PLAIN, STR, CHR, COMM
   1179     } state;
   1180 
   1181     buf_add_char(&lab, '#');
   1182 
   1183     state = PLAIN;
   1184     int com_start = 0, com_end = 0;
   1185 
   1186     while (is_hspace(*inp.s))
   1187 	inbuf_skip();
   1188 
   1189     while (*inp.s != '\n' || (state == COMM && !had_eof)) {
   1190 	buf_reserve(&lab, 2);
   1191 	*lab.e++ = inbuf_next();
   1192 	switch (lab.e[-1]) {
   1193 	case '\\':
   1194 	    if (state != COMM)
   1195 		*lab.e++ = inbuf_next();
   1196 	    break;
   1197 	case '/':
   1198 	    if (*inp.s == '*' && state == PLAIN) {
   1199 		state = COMM;
   1200 		*lab.e++ = *inp.s++;
   1201 		com_start = (int)buf_len(&lab) - 2;
   1202 	    }
   1203 	    break;
   1204 	case '"':
   1205 	    if (state == STR)
   1206 		state = PLAIN;
   1207 	    else if (state == PLAIN)
   1208 		state = STR;
   1209 	    break;
   1210 	case '\'':
   1211 	    if (state == CHR)
   1212 		state = PLAIN;
   1213 	    else if (state == PLAIN)
   1214 		state = CHR;
   1215 	    break;
   1216 	case '*':
   1217 	    if (*inp.s == '/' && state == COMM) {
   1218 		state = PLAIN;
   1219 		*lab.e++ = *inp.s++;
   1220 		com_end = (int)buf_len(&lab);
   1221 	    }
   1222 	    break;
   1223 	}
   1224     }
   1225 
   1226     while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1227 	lab.e--;
   1228     if (lab.e - lab.s == com_end && saved_inp_s == NULL) {
   1229 	/* comment on preprocessor line */
   1230 	if (sc_end == NULL) {	/* if this is the first comment, we must set
   1231 				 * up the buffer */
   1232 	    save_com = sc_buf;
   1233 	    sc_end = save_com;
   1234 	} else {
   1235 	    *sc_end++ = '\n';	/* add newline between comments */
   1236 	    *sc_end++ = ' ';
   1237 	    --line_no;
   1238 	}
   1239 	if (sc_end - save_com + com_end - com_start > sc_size)
   1240 	    errx(1, "input too long");
   1241 	memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
   1242 	sc_end += com_end - com_start;
   1243 	lab.e = lab.s + com_start;
   1244 	while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1245 	    lab.e--;
   1246 	saved_inp_s = inp.s;	/* save current input buffer */
   1247 	saved_inp_e = inp.e;
   1248 	inp.s = save_com;	/* fix so that subsequent calls to lexi will
   1249 				 * take tokens out of save_com */
   1250 	*sc_end++ = ' ';	/* add trailing blank, just in case */
   1251 	inp.e = sc_end;
   1252 	sc_end = NULL;
   1253 	debug_println("switched inp.s to save_com");
   1254     }
   1255     buf_terminate(&lab);
   1256 }
   1257 
   1258 static void
   1259 process_preprocessing(void)
   1260 {
   1261     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
   1262 	dump_line();
   1263 
   1264     read_preprocessing_line();
   1265 
   1266     ps.is_case_label = false;
   1267 
   1268     if (strncmp(lab.s, "#if", 3) == 0) {	/* also ifdef, ifndef */
   1269 	if ((size_t)ifdef_level < nitems(state_stack))
   1270 	    state_stack[ifdef_level++] = ps;
   1271 	else
   1272 	    diag(1, "#if stack overflow");
   1273 
   1274     } else if (strncmp(lab.s, "#el", 3) == 0) {	/* else, elif */
   1275 	if (ifdef_level <= 0)
   1276 	    diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
   1277 	else
   1278 	    ps = state_stack[ifdef_level - 1];
   1279 
   1280     } else if (strncmp(lab.s, "#endif", 6) == 0) {
   1281 	if (ifdef_level <= 0)
   1282 	    diag(1, "Unmatched #endif");
   1283 	else
   1284 	    ifdef_level--;
   1285 
   1286     } else {
   1287 	if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
   1288 	    strncmp(lab.s + 1, "error", 5) != 0 &&
   1289 	    strncmp(lab.s + 1, "line", 4) != 0 &&
   1290 	    strncmp(lab.s + 1, "undef", 5) != 0 &&
   1291 	    strncmp(lab.s + 1, "define", 6) != 0 &&
   1292 	    strncmp(lab.s + 1, "include", 7) != 0) {
   1293 	    diag(1, "Unrecognized cpp directive");
   1294 	    return;
   1295 	}
   1296     }
   1297 
   1298     if (opt.blanklines_around_conditional_compilation) {
   1299 	blank_line_after = true;
   1300 	blank_lines_to_output = 0;
   1301     } else {
   1302 	blank_line_after = false;
   1303 	blank_line_before = false;
   1304     }
   1305 
   1306     /*
   1307      * subsequent processing of the newline character will cause the line to
   1308      * be printed
   1309      */
   1310 }
   1311 
   1312 static void __attribute__((__noreturn__))
   1313 main_loop(void)
   1314 {
   1315     token_type ttype;
   1316     bool force_nl;		/* when true, code must be broken */
   1317     bool last_else = false;	/* true iff last keyword was an else */
   1318     int decl_ind;		/* current indentation for declarations */
   1319     int di_stack[20];		/* a stack of structure indentation levels */
   1320     bool tabs_to_var;		/* true if using tabs to indent to var name */
   1321     bool sp_sw;			/* when true, we are in the expression of
   1322 				 * if(...), while(...), etc. */
   1323     token_type hd_type = end_of_file;	/* the type of statement for if (...),
   1324 				 * for (...), etc */
   1325     int seen_quest;		/* when this is positive, we have seen a '?'
   1326 				 * without the matching ':' in a <c>?<s>:<s>
   1327 				 * construct */
   1328     bool seen_case;		/* set to true when we see a 'case', so we
   1329 				 * know what to do with the following colon */
   1330 
   1331     sp_sw = force_nl = false;
   1332     decl_ind = 0;
   1333     di_stack[ps.decl_nest = 0] = 0;
   1334     seen_case = false;
   1335     seen_quest = 0;
   1336     tabs_to_var = false;
   1337 
   1338     for (;;) {			/* this is the main loop.  it will go until we
   1339 				 * reach eof */
   1340 	bool comment_buffered = false;
   1341 
   1342 	ttype = lexi(&ps);	/* Read the next token.  The actual characters
   1343 				 * read are stored in "token". */
   1344 
   1345 	/*
   1346 	 * Move newlines and comments following an if (), while (), else, etc.
   1347 	 * up to the start of the following stmt to a buffer. This allows
   1348 	 * proper handling of both kinds of brace placement (-br, -bl) and
   1349 	 * cuddling "else" (-ce).
   1350 	 */
   1351 	search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
   1352 
   1353 	if (ttype == end_of_file) {
   1354 	    process_end_of_file();
   1355 	    /* NOTREACHED */
   1356 	}
   1357 
   1358 	if (ttype == newline || ttype == form_feed || ttype == preprocessing)
   1359 	    force_nl = false;
   1360 	else if (ttype != comment)
   1361 	    process_comment_in_code(ttype, &force_nl);
   1362 
   1363 	buf_reserve(&code, 3);	/* space for 2 characters plus '\0' */
   1364 
   1365 	switch (ttype) {
   1366 
   1367 	case form_feed:
   1368 	    process_form_feed();
   1369 	    break;
   1370 
   1371 	case newline:
   1372 	    process_newline();
   1373 	    break;
   1374 
   1375 	case lparen_or_lbracket:
   1376 	    process_lparen_or_lbracket(decl_ind, tabs_to_var, sp_sw);
   1377 	    break;
   1378 
   1379 	case rparen_or_rbracket:
   1380 	    process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
   1381 	    break;
   1382 
   1383 	case unary_op:
   1384 	    process_unary_op(decl_ind, tabs_to_var);
   1385 	    break;
   1386 
   1387 	case binary_op:
   1388 	    process_binary_op();
   1389 	    break;
   1390 
   1391 	case postfix_op:
   1392 	    process_postfix_op();
   1393 	    break;
   1394 
   1395 	case question:
   1396 	    process_question(&seen_quest);
   1397 	    break;
   1398 
   1399 	case case_label:	/* got word 'case' or 'default' */
   1400 	    seen_case = true;
   1401 	    goto copy_token;
   1402 
   1403 	case colon:
   1404 	    process_colon(&seen_quest, &force_nl, &seen_case);
   1405 	    break;
   1406 
   1407 	case semicolon:
   1408 	    process_semicolon(&seen_case, &seen_quest, decl_ind, tabs_to_var,
   1409 		&sp_sw, hd_type, &force_nl);
   1410 	    break;
   1411 
   1412 	case lbrace:
   1413 	    process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
   1414 		(int)nitems(di_stack), &decl_ind);
   1415 	    break;
   1416 
   1417 	case rbrace:
   1418 	    process_rbrace(&sp_sw, &decl_ind, di_stack);
   1419 	    break;
   1420 
   1421 	case switch_expr:	/* got keyword "switch" */
   1422 	    sp_sw = true;
   1423 	    hd_type = switch_expr;	/* keep this for when we have seen the
   1424 					 * expression */
   1425 	    goto copy_token;
   1426 
   1427 	case keyword_for_if_while:
   1428 	    sp_sw = true;	/* the interesting stuff is done after the
   1429 				 * expression is scanned */
   1430 	    hd_type = *token.s == 'i' ? if_expr :
   1431 		*token.s == 'w' ? while_expr : for_exprs;
   1432 
   1433 	    /* remember the type of header for later use by parser */
   1434 	    goto copy_token;
   1435 
   1436 	case keyword_do_else:
   1437 	    if (*token.s == 'd')
   1438 		process_keyword_do(&force_nl, &last_else);
   1439 	    else
   1440 		process_keyword_else(&force_nl, &last_else);
   1441 	    goto copy_token;
   1442 
   1443 	case type_def:
   1444 	case storage_class:
   1445 	    blank_line_before = false;
   1446 	    goto copy_token;
   1447 
   1448 	case keyword_struct_union_enum:
   1449 	    if (ps.p_l_follow > 0)
   1450 		goto copy_token;
   1451 	    /* FALLTHROUGH */
   1452 	case decl:		/* a declaration type (int, etc.) */
   1453 	    process_decl(&decl_ind, &tabs_to_var);
   1454 	    goto copy_token;
   1455 
   1456 	case funcname:
   1457 	case ident:		/* an identifier, constant or string */
   1458 	    process_ident(ttype, decl_ind, tabs_to_var, &sp_sw, &force_nl,
   1459 		hd_type);
   1460     copy_token:
   1461 	    copy_token();
   1462 	    if (ttype != funcname)
   1463 		ps.want_blank = true;
   1464 	    break;
   1465 
   1466 	case string_prefix:
   1467 	    process_string_prefix();
   1468 	    break;
   1469 
   1470 	case period:
   1471 	    process_period();
   1472 	    break;
   1473 
   1474 	case comma:
   1475 	    process_comma(decl_ind, tabs_to_var, &force_nl);
   1476 	    break;
   1477 
   1478 	case preprocessing:	/* the initial '#' */
   1479 	    process_preprocessing();
   1480 	    break;
   1481 
   1482 	case comment:		/* the initial '/' '*' or '//' of a comment */
   1483 	    process_comment();
   1484 	    break;
   1485 
   1486 	default:
   1487 	    break;
   1488 	}
   1489 
   1490 	*code.e = '\0';
   1491 	if (ttype != comment && ttype != newline && ttype != preprocessing)
   1492 	    ps.last_token = ttype;
   1493     }
   1494 }
   1495 
   1496 int
   1497 main(int argc, char **argv)
   1498 {
   1499     main_init_globals();
   1500     main_parse_command_line(argc, argv);
   1501 #if HAVE_CAPSICUM
   1502     init_capsicum();
   1503 #endif
   1504     main_prepare_parsing();
   1505     main_loop();
   1506 }
   1507 
   1508 #ifdef debug
   1509 void
   1510 debug_printf(const char *fmt, ...)
   1511 {
   1512     FILE *f = output == stdout ? stderr : stdout;
   1513     va_list ap;
   1514 
   1515     va_start(ap, fmt);
   1516     vfprintf(f, fmt, ap);
   1517     va_end(ap);
   1518 }
   1519 
   1520 void
   1521 debug_println(const char *fmt, ...)
   1522 {
   1523     FILE *f = output == stdout ? stderr : stdout;
   1524     va_list ap;
   1525 
   1526     va_start(ap, fmt);
   1527     vfprintf(f, fmt, ap);
   1528     va_end(ap);
   1529     fprintf(f, "\n");
   1530 }
   1531 
   1532 void
   1533 debug_vis_range(const char *prefix, const char *s, const char *e,
   1534     const char *suffix)
   1535 {
   1536     debug_printf("%s", prefix);
   1537     for (const char *p = s; p < e; p++) {
   1538 	if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
   1539 	    debug_printf("%c", *p);
   1540 	else if (*p == '\n')
   1541 	    debug_printf("\\n");
   1542 	else if (*p == '\t')
   1543 	    debug_printf("\\t");
   1544 	else
   1545 	    debug_printf("\\x%02x", *p);
   1546     }
   1547     debug_printf("%s", suffix);
   1548 }
   1549 #endif
   1550 
   1551 static void *
   1552 nonnull(void *p)
   1553 {
   1554     if (p == NULL)
   1555 	err(EXIT_FAILURE, NULL);
   1556     return p;
   1557 }
   1558 
   1559 void *
   1560 xmalloc(size_t size)
   1561 {
   1562     return nonnull(malloc(size));
   1563 }
   1564 
   1565 void *
   1566 xrealloc(void *p, size_t new_size)
   1567 {
   1568     return nonnull(realloc(p, new_size));
   1569 }
   1570 
   1571 char *
   1572 xstrdup(const char *s)
   1573 {
   1574     return nonnull(strdup(s));
   1575 }
   1576