Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.144
      1 /*	$NetBSD: indent.c,v 1.144 2021/10/20 05:37:21 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.144 2021/10/20 05:37:21 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     ps.use_ff = true;
    666     dump_line();
    667     ps.want_blank = false;
    668 }
    669 
    670 static void
    671 process_newline(void)
    672 {
    673     if (ps.last_token == comma && ps.p_l_follow == 0 && !ps.block_init &&
    674 	!opt.break_after_comma && break_comma &&
    675 	com.s == com.e)
    676 	goto stay_in_line;
    677 
    678     dump_line();
    679     ps.want_blank = false;
    680 
    681 stay_in_line:
    682     ++line_no;
    683 }
    684 
    685 static bool
    686 want_blank_before_lparen(void)
    687 {
    688     if (!ps.want_blank)
    689 	return false;
    690     if (ps.last_token == rparen_or_rbracket)
    691 	return false;
    692     if (ps.last_token != ident && ps.last_token != funcname)
    693 	return true;
    694     if (opt.proc_calls_space)
    695 	return true;
    696     if (ps.keyword == kw_sizeof)
    697 	return opt.blank_after_sizeof;
    698     return ps.keyword != kw_0 && ps.keyword != kw_offsetof;
    699 }
    700 
    701 static void
    702 process_lparen_or_lbracket(int decl_ind, bool tabs_to_var, bool sp_sw)
    703 {
    704     if (++ps.p_l_follow == nitems(ps.paren_indents)) {
    705 	diag(0, "Reached internal limit of %zu unclosed parens",
    706 	    nitems(ps.paren_indents));
    707 	ps.p_l_follow--;
    708     }
    709 
    710     if (token.s[0] == '(' && ps.in_decl
    711 	&& !ps.block_init && !ps.dumped_decl_indent &&
    712 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    713 	/* function pointer declarations */
    714 	indent_declaration(decl_ind, tabs_to_var);
    715 	ps.dumped_decl_indent = true;
    716     } else if (want_blank_before_lparen())
    717 	*code.e++ = ' ';
    718     ps.want_blank = false;
    719     *code.e++ = token.s[0];
    720 
    721     ps.paren_indents[ps.p_l_follow - 1] =
    722 	(short)indentation_after_range(0, code.s, code.e);
    723     debug_println("paren_indents[%d] is now %d",
    724 	ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
    725 
    726     if (sp_sw && ps.p_l_follow == 1 && opt.extra_expr_indent
    727 	    && ps.paren_indents[0] < 2 * opt.indent_size) {
    728 	ps.paren_indents[0] = (short)(2 * opt.indent_size);
    729 	debug_println("paren_indents[0] is now %d", ps.paren_indents[0]);
    730     }
    731 
    732     if (ps.init_or_struct && *token.s == '(' && ps.tos <= 2) {
    733 	/*
    734 	 * this is a kluge to make sure that declarations will be aligned
    735 	 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
    736 	 */
    737 	parse(semicolon);	/* I said this was a kluge... */
    738 	ps.init_or_struct = false;
    739     }
    740 
    741     /* parenthesized type following sizeof or offsetof is not a cast */
    742     if (ps.keyword == kw_offsetof || ps.keyword == kw_sizeof)
    743 	ps.not_cast_mask |= 1 << ps.p_l_follow;
    744 }
    745 
    746 static void
    747 process_rparen_or_rbracket(bool *sp_sw, bool *force_nl,
    748     token_type hd_type)
    749 {
    750     if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
    751 	ps.next_unary = true;
    752 	ps.cast_mask &= (1 << ps.p_l_follow) - 1;
    753 	ps.want_blank = opt.space_after_cast;
    754     } else
    755 	ps.want_blank = true;
    756     ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
    757 
    758     if (--ps.p_l_follow < 0) {
    759 	ps.p_l_follow = 0;
    760 	diag(0, "Extra %c", *token.s);
    761     }
    762 
    763     if (code.e == code.s)	/* if the paren starts the line */
    764 	ps.paren_level = ps.p_l_follow;	/* then indent it */
    765 
    766     *code.e++ = token.s[0];
    767 
    768     if (*sp_sw && ps.p_l_follow == 0) {	/* check for end of if (...), or some
    769 					 * such */
    770 	*sp_sw = false;
    771 	*force_nl = true;	/* must force newline after if */
    772 	ps.next_unary = true;
    773 	ps.in_stmt = false;	/* don't use stmt continuation indentation */
    774 
    775 	parse(hd_type);		/* let parser worry about if, or whatever */
    776     }
    777 
    778     /*
    779      * This should ensure that constructs such as main(){...} and int[]{...}
    780      * have their braces put in the right place.
    781      */
    782     ps.search_brace = opt.brace_same_line;
    783 }
    784 
    785 static void
    786 process_unary_op(int decl_ind, bool tabs_to_var)
    787 {
    788     if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
    789 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    790 	/* pointer declarations */
    791 	indent_declaration(decl_ind - (int)buf_len(&token), tabs_to_var);
    792 	ps.dumped_decl_indent = true;
    793     } else if (ps.want_blank)
    794 	*code.e++ = ' ';
    795 
    796     buf_add_buf(&code, &token);
    797     ps.want_blank = false;
    798 }
    799 
    800 static void
    801 process_binary_op(void)
    802 {
    803     if (ps.want_blank)
    804 	buf_add_char(&code, ' ');
    805     buf_add_buf(&code, &token);
    806     ps.want_blank = true;
    807 }
    808 
    809 static void
    810 process_postfix_op(void)
    811 {
    812     *code.e++ = token.s[0];
    813     *code.e++ = token.s[1];
    814     ps.want_blank = true;
    815 }
    816 
    817 static void
    818 process_question(int *seen_quest)
    819 {
    820     (*seen_quest)++;
    821     if (ps.want_blank)
    822 	*code.e++ = ' ';
    823     *code.e++ = '?';
    824     ps.want_blank = true;
    825 }
    826 
    827 static void
    828 process_colon(int *seen_quest, bool *force_nl, bool *seen_case)
    829 {
    830     if (*seen_quest > 0) {	/* part of a '?:' operator */
    831 	--*seen_quest;
    832 	if (ps.want_blank)
    833 	    *code.e++ = ' ';
    834 	*code.e++ = ':';
    835 	ps.want_blank = true;
    836 	return;
    837     }
    838 
    839     if (ps.init_or_struct) {		/* bit-field */
    840 	*code.e++ = ':';
    841 	ps.want_blank = false;
    842 	return;
    843     }
    844 
    845     buf_add_buf(&lab, &code);	/* 'case' or 'default' or named label */
    846     buf_add_char(&lab, ':');
    847     buf_terminate(&lab);
    848     buf_reset(&code);
    849 
    850     ps.in_stmt = false;
    851     ps.is_case_label = *seen_case;
    852     *force_nl = *seen_case;
    853     *seen_case = false;
    854     ps.want_blank = false;
    855 }
    856 
    857 static void
    858 process_semicolon(bool *seen_case, int *seen_quest, int decl_ind,
    859     bool tabs_to_var, bool *sp_sw,
    860     token_type hd_type,
    861     bool *force_nl)
    862 {
    863     if (ps.decl_nest == 0)
    864 	ps.init_or_struct = false;
    865     *seen_case = false;		/* these will only need resetting in an error */
    866     *seen_quest = 0;
    867     if (ps.last_token == rparen_or_rbracket)
    868 	ps.in_parameter_declaration = false;
    869     ps.cast_mask = 0;
    870     ps.not_cast_mask = 0;
    871     ps.block_init = false;
    872     ps.block_init_level = 0;
    873     ps.just_saw_decl--;
    874 
    875     if (ps.in_decl && code.s == code.e && !ps.block_init &&
    876 	!ps.dumped_decl_indent && ps.paren_level == 0) {
    877 	/* indent stray semicolons in declarations */
    878 	indent_declaration(decl_ind - 1, tabs_to_var);
    879 	ps.dumped_decl_indent = true;
    880     }
    881 
    882     ps.in_decl = ps.decl_nest > 0;	/* if we were in a first level
    883 					 * structure declaration, we aren't
    884 					 * anymore */
    885 
    886     if ((!*sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
    887 
    888 	/*
    889 	 * There were unbalanced parens in the statement. It is a bit
    890 	 * complicated, because the semicolon might be in a for statement.
    891 	 */
    892 	diag(1, "Unbalanced parens");
    893 	ps.p_l_follow = 0;
    894 	if (*sp_sw) {		/* this is a check for an if, while, etc. with
    895 				 * unbalanced parens */
    896 	    *sp_sw = false;
    897 	    parse(hd_type);	/* don't lose the 'if', or whatever */
    898 	}
    899     }
    900     *code.e++ = ';';
    901     ps.want_blank = true;
    902     ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in the middle of a
    903 					 * stmt */
    904 
    905     if (!*sp_sw) {		/* if not if for (;;) */
    906 	parse(semicolon);	/* let parser know about end of stmt */
    907 	*force_nl = true;	/* force newline after an end of stmt */
    908     }
    909 }
    910 
    911 static void
    912 process_lbrace(bool *force_nl, bool *sp_sw, token_type hd_type,
    913     int *di_stack, int di_stack_cap, int *decl_ind)
    914 {
    915     ps.in_stmt = false;		/* don't indent the {} */
    916 
    917     if (!ps.block_init)
    918 	*force_nl = true;	/* force other stuff on same line as '{' onto
    919 				 * new line */
    920     else if (ps.block_init_level <= 0)
    921 	ps.block_init_level = 1;
    922     else
    923 	ps.block_init_level++;
    924 
    925     if (code.s != code.e && !ps.block_init) {
    926 	if (!opt.brace_same_line) {
    927 	    dump_line();
    928 	    ps.want_blank = false;
    929 	} else if (ps.in_parameter_declaration && !ps.init_or_struct) {
    930 	    ps.ind_level_follow = 0;
    931 	    if (opt.function_brace_split) {	/* dump the line prior to the
    932 						 * brace ... */
    933 		dump_line();
    934 		ps.want_blank = false;
    935 	    } else		/* add a space between the decl and brace */
    936 		ps.want_blank = true;
    937 	}
    938     }
    939 
    940     if (ps.in_parameter_declaration)
    941 	blank_line_before = false;
    942 
    943     if (ps.p_l_follow > 0) {	/* check for preceding unbalanced parens */
    944 	diag(1, "Unbalanced parens");
    945 	ps.p_l_follow = 0;
    946 	if (*sp_sw) {		/* check for unclosed if, for, etc. */
    947 	    *sp_sw = false;
    948 	    parse(hd_type);
    949 	    ps.ind_level = ps.ind_level_follow;
    950 	}
    951     }
    952 
    953     if (code.s == code.e)
    954 	ps.ind_stmt = false;	/* don't indent the '{' itself */
    955     if (ps.in_decl && ps.init_or_struct) {
    956 	di_stack[ps.decl_nest] = *decl_ind;
    957 	if (++ps.decl_nest == di_stack_cap) {
    958 	    diag(0, "Reached internal limit of %d struct levels",
    959 		di_stack_cap);
    960 	    ps.decl_nest--;
    961 	}
    962     } else {
    963 	ps.decl_on_line = false;	/* we can't be in the middle of a
    964 					 * declaration, so don't do special
    965 					 * indentation of comments */
    966 	if (opt.blanklines_after_decl_at_top && ps.in_parameter_declaration)
    967 	    blank_line_after = true;
    968 	ps.in_parameter_declaration = false;
    969 	ps.in_decl = false;
    970     }
    971 
    972     *decl_ind = 0;
    973     parse(lbrace);
    974     if (ps.want_blank)
    975 	*code.e++ = ' ';
    976     ps.want_blank = false;
    977     *code.e++ = '{';
    978     ps.just_saw_decl = 0;
    979 }
    980 
    981 static void
    982 process_rbrace(bool *sp_sw, int *decl_ind, const int *di_stack)
    983 {
    984     if (ps.s_ttype[ps.tos] == decl && !ps.block_init)	/* semicolons can be
    985 							 * omitted in
    986 							 * declarations */
    987 	parse(semicolon);
    988 
    989     if (ps.p_l_follow != 0) {	/* check for unclosed if, for, else. */
    990 	diag(1, "Unbalanced parens");
    991 	ps.p_l_follow = 0;
    992 	*sp_sw = false;
    993     }
    994 
    995     ps.just_saw_decl = 0;
    996     ps.block_init_level--;
    997 
    998     if (code.s != code.e && !ps.block_init) {	/* '}' must be first on line */
    999 	if (opt.verbose)
   1000 	    diag(0, "Line broken");
   1001 	dump_line();
   1002     }
   1003 
   1004     *code.e++ = '}';
   1005     ps.want_blank = true;
   1006     ps.in_stmt = ps.ind_stmt = false;
   1007 
   1008     if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
   1009 	*decl_ind = di_stack[--ps.decl_nest];
   1010 	if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
   1011 	    ps.just_saw_decl = 2;
   1012 	ps.in_decl = true;
   1013     }
   1014 
   1015     blank_line_before = false;
   1016     parse(rbrace);		/* let parser know about this */
   1017     ps.search_brace = opt.cuddle_else
   1018 	&& ps.s_ttype[ps.tos] == if_expr_stmt
   1019 	&& ps.s_ind_level[ps.tos] >= ps.ind_level;
   1020 
   1021     if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
   1022 	blank_line_after = true;
   1023 }
   1024 
   1025 static void
   1026 process_keyword_do(bool *force_nl, bool *last_else)
   1027 {
   1028     ps.in_stmt = false;
   1029 
   1030     if (code.e != code.s) {	/* make sure this starts a line */
   1031 	if (opt.verbose)
   1032 	    diag(0, "Line broken");
   1033 	dump_line();
   1034 	ps.want_blank = false;
   1035     }
   1036 
   1037     *force_nl = true;		/* following stuff must go onto new line */
   1038     *last_else = false;
   1039     parse(keyword_do);
   1040 }
   1041 
   1042 static void
   1043 process_keyword_else(bool *force_nl, bool *last_else)
   1044 {
   1045     ps.in_stmt = false;
   1046 
   1047     if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
   1048 	if (opt.verbose)
   1049 	    diag(0, "Line broken");
   1050 	dump_line();		/* make sure this starts a line */
   1051 	ps.want_blank = false;
   1052     }
   1053 
   1054     *force_nl = true;		/* following stuff must go onto new line */
   1055     *last_else = true;
   1056     parse(keyword_else);
   1057 }
   1058 
   1059 static void
   1060 process_decl(int *decl_ind, bool *tabs_to_var)
   1061 {
   1062     parse(decl);		/* let parser worry about indentation */
   1063 
   1064     if (ps.last_token == rparen_or_rbracket && ps.tos <= 1) {
   1065 	if (code.s != code.e) {
   1066 	    dump_line();
   1067 	    ps.want_blank = false;
   1068 	}
   1069     }
   1070 
   1071     if (ps.in_parameter_declaration && opt.indent_parameters &&
   1072 	ps.decl_nest == 0) {
   1073 	ps.ind_level = ps.ind_level_follow = 1;
   1074 	ps.ind_stmt = false;
   1075     }
   1076 
   1077     ps.init_or_struct = /* maybe */ true;
   1078     ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
   1079     if (ps.decl_nest <= 0)
   1080 	ps.just_saw_decl = 2;
   1081 
   1082     blank_line_before = false;
   1083 
   1084     int len = (int)buf_len(&token) + 1;
   1085     int ind = ps.ind_level == 0 || ps.decl_nest > 0
   1086 	    ? opt.decl_indent		/* global variable or local member */
   1087 	    : opt.local_decl_indent;	/* local variable */
   1088     *decl_ind = ind > 0 ? ind : len;
   1089     *tabs_to_var = opt.use_tabs && ind > 0;
   1090 }
   1091 
   1092 static void
   1093 process_ident(token_type ttype, int decl_ind, bool tabs_to_var,
   1094     bool *sp_sw, bool *force_nl, token_type hd_type)
   1095 {
   1096     if (ps.in_decl) {
   1097 	if (ttype == funcname) {
   1098 	    ps.in_decl = false;
   1099 	    if (opt.procnames_start_line && code.s != code.e) {
   1100 		*code.e = '\0';
   1101 		dump_line();
   1102 	    } else if (ps.want_blank) {
   1103 		*code.e++ = ' ';
   1104 	    }
   1105 	    ps.want_blank = false;
   1106 
   1107 	} else if (!ps.block_init && !ps.dumped_decl_indent &&
   1108 	    ps.paren_level == 0) {	/* if we are in a declaration, we must
   1109 					 * indent identifier */
   1110 	    indent_declaration(decl_ind, tabs_to_var);
   1111 	    ps.dumped_decl_indent = true;
   1112 	    ps.want_blank = false;
   1113 	}
   1114 
   1115     } else if (*sp_sw && ps.p_l_follow == 0) {
   1116 	*sp_sw = false;
   1117 	*force_nl = true;
   1118 	ps.next_unary = true;
   1119 	ps.in_stmt = false;
   1120 	parse(hd_type);
   1121     }
   1122 }
   1123 
   1124 static void
   1125 copy_token(void)
   1126 {
   1127     if (ps.want_blank)
   1128 	buf_add_char(&code, ' ');
   1129     buf_add_buf(&code, &token);
   1130 }
   1131 
   1132 static void
   1133 process_string_prefix(void)
   1134 {
   1135     copy_token();
   1136     ps.want_blank = false;
   1137 }
   1138 
   1139 static void
   1140 process_period(void)
   1141 {
   1142     if (code.e[-1] == ',')
   1143 	*code.e++ = ' ';
   1144     *code.e++ = '.';
   1145     ps.want_blank = false;
   1146 }
   1147 
   1148 static void
   1149 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
   1150 {
   1151     ps.want_blank = code.s != code.e;	/* only put blank after comma if comma
   1152 					 * does not start the line */
   1153 
   1154     if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
   1155 	!ps.dumped_decl_indent && ps.paren_level == 0) {
   1156 	/* indent leading commas and not the actual identifiers */
   1157 	indent_declaration(decl_ind - 1, tabs_to_var);
   1158 	ps.dumped_decl_indent = true;
   1159     }
   1160 
   1161     *code.e++ = ',';
   1162 
   1163     if (ps.p_l_follow == 0) {
   1164 	if (ps.block_init_level <= 0)
   1165 	    ps.block_init = false;
   1166 	if (break_comma && (opt.break_after_comma ||
   1167 			    indentation_after_range(
   1168 				    compute_code_indent(), code.s, code.e)
   1169 			    >= opt.max_line_length - opt.tabsize))
   1170 	    *force_nl = true;
   1171     }
   1172 }
   1173 
   1174 /* move the whole line to the 'label' buffer */
   1175 static void
   1176 read_preprocessing_line(void)
   1177 {
   1178     enum {
   1179 	PLAIN, STR, CHR, COMM
   1180     } state;
   1181 
   1182     buf_add_char(&lab, '#');
   1183 
   1184     state = PLAIN;
   1185     int com_start = 0, com_end = 0;
   1186 
   1187     while (is_hspace(*inp.s))
   1188 	inbuf_skip();
   1189 
   1190     while (*inp.s != '\n' || (state == COMM && !had_eof)) {
   1191 	buf_reserve(&lab, 2);
   1192 	*lab.e++ = inbuf_next();
   1193 	switch (lab.e[-1]) {
   1194 	case '\\':
   1195 	    if (state != COMM)
   1196 		*lab.e++ = inbuf_next();
   1197 	    break;
   1198 	case '/':
   1199 	    if (*inp.s == '*' && state == PLAIN) {
   1200 		state = COMM;
   1201 		*lab.e++ = *inp.s++;
   1202 		com_start = (int)buf_len(&lab) - 2;
   1203 	    }
   1204 	    break;
   1205 	case '"':
   1206 	    if (state == STR)
   1207 		state = PLAIN;
   1208 	    else if (state == PLAIN)
   1209 		state = STR;
   1210 	    break;
   1211 	case '\'':
   1212 	    if (state == CHR)
   1213 		state = PLAIN;
   1214 	    else if (state == PLAIN)
   1215 		state = CHR;
   1216 	    break;
   1217 	case '*':
   1218 	    if (*inp.s == '/' && state == COMM) {
   1219 		state = PLAIN;
   1220 		*lab.e++ = *inp.s++;
   1221 		com_end = (int)buf_len(&lab);
   1222 	    }
   1223 	    break;
   1224 	}
   1225     }
   1226 
   1227     while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1228 	lab.e--;
   1229     if (lab.e - lab.s == com_end && saved_inp_s == NULL) {
   1230 	/* comment on preprocessor line */
   1231 	if (sc_end == NULL) {	/* if this is the first comment, we must set
   1232 				 * up the buffer */
   1233 	    save_com = sc_buf;
   1234 	    sc_end = save_com;
   1235 	} else {
   1236 	    *sc_end++ = '\n';	/* add newline between comments */
   1237 	    *sc_end++ = ' ';
   1238 	    --line_no;
   1239 	}
   1240 	if (sc_end - save_com + com_end - com_start > sc_size)
   1241 	    errx(1, "input too long");
   1242 	memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
   1243 	sc_end += com_end - com_start;
   1244 	lab.e = lab.s + com_start;
   1245 	while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1246 	    lab.e--;
   1247 	saved_inp_s = inp.s;	/* save current input buffer */
   1248 	saved_inp_e = inp.e;
   1249 	inp.s = save_com;	/* fix so that subsequent calls to lexi will
   1250 				 * take tokens out of save_com */
   1251 	*sc_end++ = ' ';	/* add trailing blank, just in case */
   1252 	inp.e = sc_end;
   1253 	sc_end = NULL;
   1254 	debug_println("switched inp.s to save_com");
   1255     }
   1256     buf_terminate(&lab);
   1257 }
   1258 
   1259 static void
   1260 process_preprocessing(void)
   1261 {
   1262     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
   1263 	dump_line();
   1264 
   1265     read_preprocessing_line();
   1266 
   1267     ps.is_case_label = false;
   1268 
   1269     if (strncmp(lab.s, "#if", 3) == 0) {	/* also ifdef, ifndef */
   1270 	if ((size_t)ifdef_level < nitems(state_stack))
   1271 	    state_stack[ifdef_level++] = ps;
   1272 	else
   1273 	    diag(1, "#if stack overflow");
   1274 
   1275     } else if (strncmp(lab.s, "#el", 3) == 0) {	/* else, elif */
   1276 	if (ifdef_level <= 0)
   1277 	    diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
   1278 	else
   1279 	    ps = state_stack[ifdef_level - 1];
   1280 
   1281     } else if (strncmp(lab.s, "#endif", 6) == 0) {
   1282 	if (ifdef_level <= 0)
   1283 	    diag(1, "Unmatched #endif");
   1284 	else
   1285 	    ifdef_level--;
   1286 
   1287     } else {
   1288 	if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
   1289 	    strncmp(lab.s + 1, "error", 5) != 0 &&
   1290 	    strncmp(lab.s + 1, "line", 4) != 0 &&
   1291 	    strncmp(lab.s + 1, "undef", 5) != 0 &&
   1292 	    strncmp(lab.s + 1, "define", 6) != 0 &&
   1293 	    strncmp(lab.s + 1, "include", 7) != 0) {
   1294 	    diag(1, "Unrecognized cpp directive");
   1295 	    return;
   1296 	}
   1297     }
   1298 
   1299     if (opt.blanklines_around_conditional_compilation) {
   1300 	blank_line_after = true;
   1301 	blank_lines_to_output = 0;
   1302     } else {
   1303 	blank_line_after = false;
   1304 	blank_line_before = false;
   1305     }
   1306 
   1307     /*
   1308      * subsequent processing of the newline character will cause the line to
   1309      * be printed
   1310      */
   1311 }
   1312 
   1313 static void __attribute__((__noreturn__))
   1314 main_loop(void)
   1315 {
   1316     token_type ttype;
   1317     bool force_nl;		/* when true, code must be broken */
   1318     bool last_else = false;	/* true iff last keyword was an else */
   1319     int decl_ind;		/* current indentation for declarations */
   1320     int di_stack[20];		/* a stack of structure indentation levels */
   1321     bool tabs_to_var;		/* true if using tabs to indent to var name */
   1322     bool sp_sw;			/* when true, we are in the expression of
   1323 				 * if(...), while(...), etc. */
   1324     token_type hd_type = end_of_file;	/* the type of statement for if (...),
   1325 				 * for (...), etc */
   1326     int seen_quest;		/* when this is positive, we have seen a '?'
   1327 				 * without the matching ':' in a <c>?<s>:<s>
   1328 				 * construct */
   1329     bool seen_case;		/* set to true when we see a 'case', so we
   1330 				 * know what to do with the following colon */
   1331 
   1332     sp_sw = force_nl = false;
   1333     decl_ind = 0;
   1334     di_stack[ps.decl_nest = 0] = 0;
   1335     seen_case = false;
   1336     seen_quest = 0;
   1337     tabs_to_var = false;
   1338 
   1339     for (;;) {			/* this is the main loop.  it will go until we
   1340 				 * reach eof */
   1341 	bool comment_buffered = false;
   1342 
   1343 	ttype = lexi(&ps);	/* Read the next token.  The actual characters
   1344 				 * read are stored in "token". */
   1345 
   1346 	/*
   1347 	 * Move newlines and comments following an if (), while (), else, etc.
   1348 	 * up to the start of the following stmt to a buffer. This allows
   1349 	 * proper handling of both kinds of brace placement (-br, -bl) and
   1350 	 * cuddling "else" (-ce).
   1351 	 */
   1352 	search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
   1353 
   1354 	if (ttype == end_of_file) {
   1355 	    process_end_of_file();
   1356 	    /* NOTREACHED */
   1357 	}
   1358 
   1359 	if (ttype == newline || ttype == form_feed || ttype == preprocessing)
   1360 	    force_nl = false;
   1361 	else if (ttype != comment)
   1362 	    process_comment_in_code(ttype, &force_nl);
   1363 
   1364 	buf_reserve(&code, 3);	/* space for 2 characters plus '\0' */
   1365 
   1366 	switch (ttype) {
   1367 
   1368 	case form_feed:
   1369 	    process_form_feed();
   1370 	    break;
   1371 
   1372 	case newline:
   1373 	    process_newline();
   1374 	    break;
   1375 
   1376 	case lparen_or_lbracket:
   1377 	    process_lparen_or_lbracket(decl_ind, tabs_to_var, sp_sw);
   1378 	    break;
   1379 
   1380 	case rparen_or_rbracket:
   1381 	    process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
   1382 	    break;
   1383 
   1384 	case unary_op:
   1385 	    process_unary_op(decl_ind, tabs_to_var);
   1386 	    break;
   1387 
   1388 	case binary_op:
   1389 	    process_binary_op();
   1390 	    break;
   1391 
   1392 	case postfix_op:
   1393 	    process_postfix_op();
   1394 	    break;
   1395 
   1396 	case question:
   1397 	    process_question(&seen_quest);
   1398 	    break;
   1399 
   1400 	case case_label:	/* got word 'case' or 'default' */
   1401 	    seen_case = true;
   1402 	    goto copy_token;
   1403 
   1404 	case colon:
   1405 	    process_colon(&seen_quest, &force_nl, &seen_case);
   1406 	    break;
   1407 
   1408 	case semicolon:
   1409 	    process_semicolon(&seen_case, &seen_quest, decl_ind, tabs_to_var,
   1410 		&sp_sw, hd_type, &force_nl);
   1411 	    break;
   1412 
   1413 	case lbrace:
   1414 	    process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
   1415 		(int)nitems(di_stack), &decl_ind);
   1416 	    break;
   1417 
   1418 	case rbrace:
   1419 	    process_rbrace(&sp_sw, &decl_ind, di_stack);
   1420 	    break;
   1421 
   1422 	case switch_expr:	/* got keyword "switch" */
   1423 	    sp_sw = true;
   1424 	    hd_type = switch_expr;	/* keep this for when we have seen the
   1425 					 * expression */
   1426 	    goto copy_token;
   1427 
   1428 	case keyword_for_if_while:
   1429 	    sp_sw = true;	/* the interesting stuff is done after the
   1430 				 * expression is scanned */
   1431 	    hd_type = *token.s == 'i' ? if_expr :
   1432 		*token.s == 'w' ? while_expr : for_exprs;
   1433 
   1434 	    /* remember the type of header for later use by parser */
   1435 	    goto copy_token;
   1436 
   1437 	case keyword_do_else:
   1438 	    if (*token.s == 'd')
   1439 		process_keyword_do(&force_nl, &last_else);
   1440 	    else
   1441 		process_keyword_else(&force_nl, &last_else);
   1442 	    goto copy_token;
   1443 
   1444 	case type_def:
   1445 	case storage_class:
   1446 	    blank_line_before = false;
   1447 	    goto copy_token;
   1448 
   1449 	case keyword_struct_union_enum:
   1450 	    if (ps.p_l_follow > 0)
   1451 		goto copy_token;
   1452 	    /* FALLTHROUGH */
   1453 	case decl:		/* a declaration type (int, etc.) */
   1454 	    process_decl(&decl_ind, &tabs_to_var);
   1455 	    goto copy_token;
   1456 
   1457 	case funcname:
   1458 	case ident:		/* an identifier, constant or string */
   1459 	    process_ident(ttype, decl_ind, tabs_to_var, &sp_sw, &force_nl,
   1460 		hd_type);
   1461     copy_token:
   1462 	    copy_token();
   1463 	    if (ttype != funcname)
   1464 		ps.want_blank = true;
   1465 	    break;
   1466 
   1467 	case string_prefix:
   1468 	    process_string_prefix();
   1469 	    break;
   1470 
   1471 	case period:
   1472 	    process_period();
   1473 	    break;
   1474 
   1475 	case comma:
   1476 	    process_comma(decl_ind, tabs_to_var, &force_nl);
   1477 	    break;
   1478 
   1479 	case preprocessing:	/* the initial '#' */
   1480 	    process_preprocessing();
   1481 	    break;
   1482 
   1483 	case comment:		/* the initial '/' '*' or '//' of a comment */
   1484 	    process_comment();
   1485 	    break;
   1486 
   1487 	default:
   1488 	    break;
   1489 	}
   1490 
   1491 	*code.e = '\0';
   1492 	if (ttype != comment && ttype != newline && ttype != preprocessing)
   1493 	    ps.last_token = ttype;
   1494     }
   1495 }
   1496 
   1497 int
   1498 main(int argc, char **argv)
   1499 {
   1500     main_init_globals();
   1501     main_parse_command_line(argc, argv);
   1502 #if HAVE_CAPSICUM
   1503     init_capsicum();
   1504 #endif
   1505     main_prepare_parsing();
   1506     main_loop();
   1507 }
   1508 
   1509 #ifdef debug
   1510 void
   1511 debug_printf(const char *fmt, ...)
   1512 {
   1513     FILE *f = output == stdout ? stderr : stdout;
   1514     va_list ap;
   1515 
   1516     va_start(ap, fmt);
   1517     vfprintf(f, fmt, ap);
   1518     va_end(ap);
   1519 }
   1520 
   1521 void
   1522 debug_println(const char *fmt, ...)
   1523 {
   1524     FILE *f = output == stdout ? stderr : stdout;
   1525     va_list ap;
   1526 
   1527     va_start(ap, fmt);
   1528     vfprintf(f, fmt, ap);
   1529     va_end(ap);
   1530     fprintf(f, "\n");
   1531 }
   1532 
   1533 void
   1534 debug_vis_range(const char *prefix, const char *s, const char *e,
   1535     const char *suffix)
   1536 {
   1537     debug_printf("%s", prefix);
   1538     for (const char *p = s; p < e; p++) {
   1539 	if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
   1540 	    debug_printf("%c", *p);
   1541 	else if (*p == '\n')
   1542 	    debug_printf("\\n");
   1543 	else if (*p == '\t')
   1544 	    debug_printf("\\t");
   1545 	else
   1546 	    debug_printf("\\x%02x", *p);
   1547     }
   1548     debug_printf("%s", suffix);
   1549 }
   1550 #endif
   1551 
   1552 static void *
   1553 nonnull(void *p)
   1554 {
   1555     if (p == NULL)
   1556 	err(EXIT_FAILURE, NULL);
   1557     return p;
   1558 }
   1559 
   1560 void *
   1561 xmalloc(size_t size)
   1562 {
   1563     return nonnull(malloc(size));
   1564 }
   1565 
   1566 void *
   1567 xrealloc(void *p, size_t new_size)
   1568 {
   1569     return nonnull(realloc(p, new_size));
   1570 }
   1571 
   1572 char *
   1573 xstrdup(const char *s)
   1574 {
   1575     return nonnull(strdup(s));
   1576 }
   1577