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