Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.108
      1 /*	$NetBSD: indent.c,v 1.108 2021/10/05 18:50:42 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.108 2021/10/05 18:50:42 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 next_blank_lines;
    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 *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     *force_nl = false;
    182 }
    183 
    184 static void
    185 search_brace_comment(bool *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     *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 *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 	*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 	*force_nl = !remove_newlines;
    267 	while (sc_end > save_com && sc_end[-1] == '\n') {
    268 	    sc_end--;
    269 	}
    270     }
    271     if (*force_nl) {	/* if we should insert a nl here, put it into
    272 				 * the buffer */
    273 	*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 *ttype)
    303 {
    304     /*
    305      * We must make this check, just in case there was an unexpected EOF.
    306      */
    307     if (*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 	*ttype = lexi(&transient_state);	/* read another token */
    340 	if (*ttype != newline && *ttype != form_feed &&
    341 	    *ttype != comment && !transient_state.search_brace) {
    342 	    ps = transient_state;
    343 	}
    344     }
    345 }
    346 
    347 static void
    348 search_brace(token_type *ttype, bool *force_nl,
    349     bool *comment_buffered, bool *last_else)
    350 {
    351     while (ps.search_brace) {
    352 	switch (*ttype) {
    353 	case newline:
    354 	    search_brace_newline(force_nl);
    355 	    break;
    356 	case form_feed:
    357 	    break;
    358 	case comment:
    359 	    search_brace_comment(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(*ttype, force_nl,
    367 		    *comment_buffered, *last_else))
    368 		return;
    369 	sw_buffer:
    370 	    switch_buffer();
    371 	}
    372 	search_brace_lookahead(ttype);
    373     }
    374 
    375     *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 ind = 0;
    505 
    506     for (;;) {
    507 	if (*p == ' ')
    508 	    ind++;
    509 	else if (*p == '\t')
    510 	    ind = opt.tabsize * (1 + ind / opt.tabsize);
    511 	else
    512 	    break;
    513 	p++;
    514     }
    515     if (ind >= opt.indent_size)
    516 	ps.ind_level = ps.ind_level_follow = ind / 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 *force_nl)
    541 {
    542     if (*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 	*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 decl_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(decl_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 *sp_sw, bool *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 (*sp_sw && (ps.p_l_follow == 0)) {	/* check for end of if (...),
    673 						 * or some such */
    674 	*sp_sw = false;
    675 	*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 decl_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(decl_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 *seen_quest)
    733 {
    734     (*seen_quest)++;		/* 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 *seen_quest, bool *force_nl, bool *seen_case)
    745 {
    746     if (*seen_quest > 0) {	/* it is part of the <c>?<n>: <n> construct */
    747 	--*seen_quest;
    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 = *seen_case;	/* will be used by dump_line to decide how to
    775 				 * indent the label. */
    776     *force_nl = *seen_case;	/* will force a 'case n:' to be on a
    777 				 * line by itself */
    778     *seen_case = false;
    779     ps.want_blank = false;
    780 }
    781 
    782 static void
    783 process_semicolon(bool *seen_case, int *seen_quest, int decl_ind,
    784     bool tabs_to_var, bool *sp_sw,
    785     token_type hd_type,
    786     bool *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     *seen_case = false;		/* these will only need resetting in an error */
    792     *seen_quest = 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(decl_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 ((!*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 (*sp_sw) {		/* this is a check for an if, while, etc. with
    822 				 * unbalanced parens */
    823 	    *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 (!*sp_sw) {		/* if not if for (;;) */
    833 	parse(semicolon);	/* let parser know about end of stmt */
    834 	*force_nl = true;	/* force newline after an end of stmt */
    835     }
    836 }
    837 
    838 static void
    839 process_lbrace(bool *force_nl, bool *sp_sw, token_type hd_type,
    840     int *di_stack, int di_stack_cap, int *decl_ind)
    841 {
    842     ps.in_stmt = false;		/* don't indent the {} */
    843     if (!ps.block_init)
    844 	*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 (*sp_sw) {		/* check for unclosed if, for, etc. */
    872 	    *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] = *decl_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     } else {
    889 	ps.decl_on_line = false;	/* we can't be in the middle of a
    890 					 * declaration, so don't do special
    891 					 * indentation of comments */
    892 	if (opt.blanklines_after_declarations_at_proctop
    893 	    && ps.in_parameter_declaration)
    894 	    postfix_blankline_requested = true;
    895 	ps.in_parameter_declaration = false;
    896 	ps.in_decl = false;
    897     }
    898     *decl_ind = 0;
    899     parse(lbrace);		/* let parser know about this */
    900     if (ps.want_blank)		/* put a blank before '{' if '{' is not at
    901 				 * start of line */
    902 	*code.e++ = ' ';
    903     ps.want_blank = false;
    904     *code.e++ = '{';
    905     ps.just_saw_decl = 0;
    906 }
    907 
    908 static void
    909 process_rbrace(bool *sp_sw, int *decl_ind, const int *di_stack)
    910 {
    911     if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
    912 							 * omitted in
    913 							 * declarations */
    914 	parse(semicolon);
    915     if (ps.p_l_follow != 0) {	/* check for unclosed if, for, else. */
    916 	diag(1, "Unbalanced parens");
    917 	ps.p_l_follow = 0;
    918 	*sp_sw = false;
    919     }
    920     ps.just_saw_decl = 0;
    921     ps.block_init_level--;
    922     if (code.s != code.e && !ps.block_init) {	/* '}' must be first on line */
    923 	if (opt.verbose)
    924 	    diag(0, "Line broken");
    925 	dump_line();
    926     }
    927     *code.e++ = '}';
    928     ps.want_blank = true;
    929     ps.in_stmt = ps.ind_stmt = false;
    930     if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
    931 	*decl_ind = di_stack[--ps.decl_nest];
    932 	if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
    933 	    ps.just_saw_decl = 2;
    934 	ps.in_decl = true;
    935     }
    936     prefix_blankline_requested = false;
    937     parse(rbrace);		/* let parser know about this */
    938     ps.search_brace = opt.cuddle_else
    939 	&& ps.p_stack[ps.tos] == if_expr_stmt
    940 	&& ps.il[ps.tos] >= ps.ind_level;
    941     if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
    942 	postfix_blankline_requested = true;
    943 }
    944 
    945 static void
    946 process_keyword_do_else(bool *force_nl, bool *last_else)
    947 {
    948     ps.in_stmt = false;
    949     if (*token.s == 'e') {
    950 	if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
    951 	    if (opt.verbose)
    952 		diag(0, "Line broken");
    953 	    dump_line();	/* make sure this starts a line */
    954 	    ps.want_blank = false;
    955 	}
    956 	*force_nl = true;	/* following stuff must go onto new line */
    957 	*last_else = true;
    958 	parse(keyword_else);
    959     } else {
    960 	if (code.e != code.s) {	/* make sure this starts a line */
    961 	    if (opt.verbose)
    962 		diag(0, "Line broken");
    963 	    dump_line();
    964 	    ps.want_blank = false;
    965 	}
    966 	*force_nl = true;	/* following stuff must go onto new line */
    967 	*last_else = false;
    968 	parse(keyword_do);
    969     }
    970 }
    971 
    972 static void
    973 process_decl(int *out_decl_ind, bool *out_tabs_to_var)
    974 {
    975     parse(decl);		/* let parser worry about indentation */
    976     if (ps.last_token == rparen && ps.tos <= 1) {
    977 	if (code.s != code.e) {
    978 	    dump_line();
    979 	    ps.want_blank = false;
    980 	}
    981     }
    982     if (ps.in_parameter_declaration && opt.indent_parameters &&
    983 	ps.decl_nest == 0) {
    984 	ps.ind_level = ps.ind_level_follow = 1;
    985 	ps.ind_stmt = false;
    986     }
    987     ps.in_or_st = true;		/* this might be a structure or initialization
    988 				 * declaration */
    989     ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
    990     if ( /* !ps.in_or_st && */ ps.decl_nest <= 0)
    991 	ps.just_saw_decl = 2;
    992     prefix_blankline_requested = false;
    993 
    994     int len = (int)strlen(token.s) + 1;
    995     int ind = ps.ind_level == 0 || ps.decl_nest > 0
    996 	    ? opt.decl_indent		/* global variable or local member */
    997 	    : opt.local_decl_indent;	/* local variable */
    998     *out_decl_ind = ind > 0 ? ind : len;
    999     *out_tabs_to_var = opt.use_tabs ? ind > 0 : false;
   1000 }
   1001 
   1002 static void
   1003 process_ident(token_type ttype, int decl_ind, bool tabs_to_var,
   1004     bool *sp_sw, bool *force_nl, token_type hd_type)
   1005 {
   1006     if (ps.in_decl) {
   1007 	if (ttype == funcname) {
   1008 	    ps.in_decl = false;
   1009 	    if (opt.procnames_start_line && code.s != code.e) {
   1010 		*code.e = '\0';
   1011 		dump_line();
   1012 	    } else if (ps.want_blank) {
   1013 		*code.e++ = ' ';
   1014 	    }
   1015 	    ps.want_blank = false;
   1016 	} else if (!ps.block_init && !ps.dumped_decl_indent &&
   1017 	    ps.paren_level == 0) {	/* if we are in a declaration, we must
   1018 					 * indent identifier */
   1019 	    indent_declaration(decl_ind, tabs_to_var);
   1020 	    ps.dumped_decl_indent = true;
   1021 	    ps.want_blank = false;
   1022 	}
   1023     } else if (*sp_sw && ps.p_l_follow == 0) {
   1024 	*sp_sw = false;
   1025 	*force_nl = true;
   1026 	ps.last_u_d = true;
   1027 	ps.in_stmt = false;
   1028 	parse(hd_type);
   1029     }
   1030 }
   1031 
   1032 static void
   1033 copy_id(void)
   1034 {
   1035     size_t len = token.e - token.s;
   1036 
   1037     check_size_code(len + 1);
   1038     if (ps.want_blank)
   1039 	*code.e++ = ' ';
   1040     memcpy(code.e, token.s, len);
   1041     code.e += len;
   1042 }
   1043 
   1044 static void
   1045 process_string_prefix(void)
   1046 {
   1047     size_t len = token.e - token.s;
   1048 
   1049     check_size_code(len + 1);
   1050     if (ps.want_blank)
   1051 	*code.e++ = ' ';
   1052     memcpy(code.e, token.s, len);
   1053     code.e += len;
   1054 
   1055     ps.want_blank = false;
   1056 }
   1057 
   1058 static void
   1059 process_period(void)
   1060 {
   1061     if (code.e[-1] == ',')
   1062 	*code.e++ = ' ';
   1063     *code.e++ = '.';
   1064     ps.want_blank = false;
   1065 }
   1066 
   1067 static void
   1068 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
   1069 {
   1070     ps.want_blank = (code.s != code.e);	/* only put blank after comma if comma
   1071 					 * does not start the line */
   1072     if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
   1073 	!ps.dumped_decl_indent && ps.paren_level == 0) {
   1074 	/* indent leading commas and not the actual identifiers */
   1075 	indent_declaration(decl_ind - 1, tabs_to_var);
   1076 	ps.dumped_decl_indent = true;
   1077     }
   1078     *code.e++ = ',';
   1079     if (ps.p_l_follow == 0) {
   1080 	if (ps.block_init_level <= 0)
   1081 	    ps.block_init = false;
   1082 	if (break_comma && (opt.break_after_comma ||
   1083 			    indentation_after_range(
   1084 				    compute_code_indent(), code.s, code.e)
   1085 			    >= opt.max_line_length - opt.tabsize))
   1086 	    *force_nl = true;
   1087     }
   1088 }
   1089 
   1090 static void
   1091 process_preprocessing(void)
   1092 {
   1093     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
   1094 	dump_line();
   1095     check_size_label(1);
   1096     *lab.e++ = '#';		/* move whole line to 'label' buffer */
   1097 
   1098     {
   1099 	bool in_comment = false;
   1100 	int com_start = 0;
   1101 	char quote = '\0';
   1102 	int com_end = 0;
   1103 
   1104 	while (is_hspace(*buf_ptr))
   1105 	    inbuf_skip();
   1106 
   1107 	while (*buf_ptr != '\n' || (in_comment && !had_eof)) {
   1108 	    check_size_label(2);
   1109 	    *lab.e++ = inbuf_next();
   1110 	    switch (lab.e[-1]) {
   1111 	    case '\\':
   1112 		if (!in_comment)
   1113 		    *lab.e++ = inbuf_next();
   1114 		break;
   1115 	    case '/':
   1116 		if (*buf_ptr == '*' && !in_comment && quote == '\0') {
   1117 		    in_comment = true;
   1118 		    *lab.e++ = *buf_ptr++;
   1119 		    com_start = (int)(lab.e - lab.s) - 2;
   1120 		}
   1121 		break;
   1122 	    case '"':
   1123 		if (quote == '"')
   1124 		    quote = '\0';
   1125 		else if (quote == '\0')
   1126 		    quote = '"';
   1127 		break;
   1128 	    case '\'':
   1129 		if (quote == '\'')
   1130 		    quote = '\0';
   1131 		else if (quote == '\0')
   1132 		    quote = '\'';
   1133 		break;
   1134 	    case '*':
   1135 		if (*buf_ptr == '/' && in_comment) {
   1136 		    in_comment = false;
   1137 		    *lab.e++ = *buf_ptr++;
   1138 		    com_end = (int)(lab.e - lab.s);
   1139 		}
   1140 		break;
   1141 	    }
   1142 	}
   1143 
   1144 	while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1145 	    lab.e--;
   1146 	if (lab.e - lab.s == com_end && bp_save == NULL) {
   1147 	    /* comment on preprocessor line */
   1148 	    if (sc_end == NULL) {	/* if this is the first comment, we
   1149 					 * must set up the buffer */
   1150 		save_com = sc_buf;
   1151 		sc_end = save_com;
   1152 	    } else {
   1153 		*sc_end++ = '\n';	/* add newline between comments */
   1154 		*sc_end++ = ' ';
   1155 		--line_no;
   1156 	    }
   1157 	    if (sc_end - save_com + com_end - com_start > sc_size)
   1158 		errx(1, "input too long");
   1159 	    memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
   1160 	    sc_end += com_end - com_start;
   1161 	    lab.e = lab.s + com_start;
   1162 	    while (lab.e > lab.s && is_hspace(lab.e[-1]))
   1163 		lab.e--;
   1164 	    bp_save = buf_ptr;	/* save current input buffer */
   1165 	    be_save = buf_end;
   1166 	    buf_ptr = save_com;	/* fix so that subsequent calls to lexi will
   1167 				 * take tokens out of save_com */
   1168 	    *sc_end++ = ' ';	/* add trailing blank, just in case */
   1169 	    buf_end = sc_end;
   1170 	    sc_end = NULL;
   1171 	    debug_println("switched buf_ptr to save_com");
   1172 	}
   1173 	check_size_label(1);
   1174 	*lab.e = '\0';		/* null terminate line */
   1175 	ps.pcase = false;
   1176     }
   1177 
   1178     if (strncmp(lab.s, "#if", 3) == 0) {	/* also ifdef, ifndef */
   1179 	if ((size_t)ifdef_level < nitems(state_stack))
   1180 	    state_stack[ifdef_level++] = ps;
   1181 	else
   1182 	    diag(1, "#if stack overflow");
   1183     } else if (strncmp(lab.s, "#el", 3) == 0) {	/* else, elif */
   1184 	if (ifdef_level <= 0)
   1185 	    diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
   1186 	else
   1187 	    ps = state_stack[ifdef_level - 1];
   1188     } else if (strncmp(lab.s, "#endif", 6) == 0) {
   1189 	if (ifdef_level <= 0)
   1190 	    diag(1, "Unmatched #endif");
   1191 	else
   1192 	    ifdef_level--;
   1193     } else {
   1194 	if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
   1195 	    strncmp(lab.s + 1, "error", 5) != 0 &&
   1196 	    strncmp(lab.s + 1, "line", 4) != 0 &&
   1197 	    strncmp(lab.s + 1, "undef", 5) != 0 &&
   1198 	    strncmp(lab.s + 1, "define", 6) != 0 &&
   1199 	    strncmp(lab.s + 1, "include", 7) != 0) {
   1200 	    diag(1, "Unrecognized cpp directive");
   1201 	    return;
   1202 	}
   1203     }
   1204     if (opt.blanklines_around_conditional_compilation) {
   1205 	postfix_blankline_requested = true;
   1206 	next_blank_lines = 0;
   1207     } else {
   1208 	postfix_blankline_requested = false;
   1209 	prefix_blankline_requested = false;
   1210     }
   1211 
   1212     /*
   1213      * subsequent processing of the newline character will cause the line to
   1214      * be printed
   1215      */
   1216 }
   1217 
   1218 static void __attribute__((__noreturn__))
   1219 main_loop(void)
   1220 {
   1221     token_type ttype;
   1222     bool force_nl;		/* when true, code must be broken */
   1223     bool last_else = false;	/* true iff last keyword was an else */
   1224     int decl_ind;		/* current indentation for declarations */
   1225     int di_stack[20];		/* a stack of structure indentation levels */
   1226     bool tabs_to_var;		/* true if using tabs to indent to var name */
   1227     bool sp_sw;			/* when true, we are in the expression of
   1228 				 * if(...), while(...), etc. */
   1229     token_type hd_type = end_of_file;	/* used to store type of stmt for if
   1230 					 * (...), for (...), etc */
   1231     int seen_quest;		/* when this is positive, we have seen a '?'
   1232 				 * without the matching ':' in a <c>?<s>:<s>
   1233 				 * construct */
   1234     bool seen_case;		/* set to true when we see a 'case', so we
   1235 				 * know what to do with the following colon */
   1236 
   1237     sp_sw = force_nl = false;
   1238     decl_ind = 0;
   1239     di_stack[ps.decl_nest = 0] = 0;
   1240     seen_case = false;
   1241     seen_quest = 0;
   1242     tabs_to_var = false;
   1243 
   1244     for (;;) {			/* this is the main loop.  it will go until we
   1245 				 * reach eof */
   1246 	bool comment_buffered = false;
   1247 
   1248 	ttype = lexi(&ps);	/* Read the next token.  The actual characters
   1249 				 * read are stored in "token". */
   1250 
   1251 	/*
   1252 	 * The following code moves newlines and comments following an if (),
   1253 	 * while (), else, etc. up to the start of the following stmt to a
   1254 	 * buffer. This allows proper handling of both kinds of brace
   1255 	 * placement (-br, -bl) and cuddling "else" (-ce).
   1256 	 */
   1257 	search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
   1258 
   1259 	if (ttype == end_of_file) {
   1260 	    process_end_of_file();
   1261 	    /* NOTREACHED */
   1262 	}
   1263 
   1264 	if (
   1265 		ttype != comment &&
   1266 		ttype != newline &&
   1267 		ttype != preprocessing &&
   1268 		ttype != form_feed) {
   1269 	    process_comment_in_code(ttype, &force_nl);
   1270 
   1271 	} else if (ttype != comment)	/* preserve force_nl through a comment */
   1272 	    force_nl = false;	/* cancel forced newline after newline, form
   1273 				 * feed, etc */
   1274 
   1275 
   1276 
   1277 	/*-----------------------------------------------------*\
   1278 	|	   do switch on type of token scanned		|
   1279 	\*-----------------------------------------------------*/
   1280 	check_size_code(3);	/* maximum number of increments of code.e
   1281 				 * before the next check_size_code or
   1282 				 * dump_line() is 2. After that there's the
   1283 				 * final increment for the null character. */
   1284 	switch (ttype) {
   1285 
   1286 	case form_feed:
   1287 	    process_form_feed();
   1288 	    break;
   1289 
   1290 	case newline:
   1291 	    process_newline();
   1292 	    break;
   1293 
   1294 	case lparen:		/* got a '(' or '[' */
   1295 	    process_lparen_or_lbracket(decl_ind, tabs_to_var, sp_sw);
   1296 	    break;
   1297 
   1298 	case rparen:		/* got a ')' or ']' */
   1299 	    process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
   1300 	    break;
   1301 
   1302 	case unary_op:		/* this could be any unary operation */
   1303 	    process_unary_op(decl_ind, tabs_to_var);
   1304 	    break;
   1305 
   1306 	case binary_op:		/* any binary operation */
   1307 	    process_binary_op();
   1308 	    break;
   1309 
   1310 	case postfix_op:	/* got a trailing ++ or -- */
   1311 	    process_postfix_op();
   1312 	    break;
   1313 
   1314 	case question:		/* got a ? */
   1315 	    process_question(&seen_quest);
   1316 	    break;
   1317 
   1318 	case case_label:	/* got word 'case' or 'default' */
   1319 	    seen_case = true;	/* so we can process the later colon properly */
   1320 	    goto copy_id;
   1321 
   1322 	case colon:		/* got a ':' */
   1323 	    process_colon(&seen_quest, &force_nl, &seen_case);
   1324 	    break;
   1325 
   1326 	case semicolon:		/* got a ';' */
   1327 	    process_semicolon(&seen_case, &seen_quest, decl_ind, tabs_to_var,
   1328 		&sp_sw, hd_type, &force_nl);
   1329 	    break;
   1330 
   1331 	case lbrace:		/* got a '{' */
   1332 	    process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
   1333 		(int)nitems(di_stack), &decl_ind);
   1334 	    break;
   1335 
   1336 	case rbrace:		/* got a '}' */
   1337 	    process_rbrace(&sp_sw, &decl_ind, di_stack);
   1338 	    break;
   1339 
   1340 	case switch_expr:	/* got keyword "switch" */
   1341 	    sp_sw = true;
   1342 	    hd_type = switch_expr;	/* keep this for when we have seen the
   1343 					 * expression */
   1344 	    goto copy_id;	/* go move the token into buffer */
   1345 
   1346 	case keyword_for_if_while:
   1347 	    sp_sw = true;	/* the interesting stuff is done after the
   1348 				 * expression is scanned */
   1349 	    hd_type = (*token.s == 'i' ? if_expr :
   1350 		(*token.s == 'w' ? while_expr : for_exprs));
   1351 
   1352 	    /* remember the type of header for later use by parser */
   1353 	    goto copy_id;	/* copy the token into line */
   1354 
   1355 	case keyword_do_else:
   1356 	    process_keyword_do_else(&force_nl, &last_else);
   1357 	    goto copy_id;	/* move the token into line */
   1358 
   1359 	case type_def:
   1360 	case storage_class:
   1361 	    prefix_blankline_requested = false;
   1362 	    goto copy_id;
   1363 
   1364 	case keyword_struct_union_enum:
   1365 	    if (ps.p_l_follow > 0)
   1366 		goto copy_id;
   1367 	    /* FALLTHROUGH */
   1368 	case decl:		/* we have a declaration type (int, etc.) */
   1369 	    process_decl(&decl_ind, &tabs_to_var);
   1370 	    goto copy_id;
   1371 
   1372 	case funcname:
   1373 	case ident:		/* got an identifier or constant */
   1374 	    process_ident(ttype, decl_ind, tabs_to_var, &sp_sw, &force_nl,
   1375 		hd_type);
   1376     copy_id:
   1377 	    copy_id();
   1378 	    if (ttype != funcname)
   1379 		ps.want_blank = true;
   1380 	    break;
   1381 
   1382 	case string_prefix:
   1383 	    process_string_prefix();
   1384 	    break;
   1385 
   1386 	case period:
   1387 	    process_period();
   1388 	    break;
   1389 
   1390 	case comma:
   1391 	    process_comma(decl_ind, tabs_to_var, &force_nl);
   1392 	    break;
   1393 
   1394 	case preprocessing:	/* '#' */
   1395 	    process_preprocessing();
   1396 	    break;
   1397 	case comment:		/* the initial '/' '*' or '//' of a comment */
   1398 	    process_comment();
   1399 	    break;
   1400 
   1401 	default:
   1402 	    break;
   1403 	}
   1404 
   1405 	*code.e = '\0';
   1406 	if (ttype != comment &&
   1407 	    ttype != newline &&
   1408 	    ttype != preprocessing)
   1409 	    ps.last_token = ttype;
   1410     }
   1411 }
   1412 
   1413 int
   1414 main(int argc, char **argv)
   1415 {
   1416     main_init_globals();
   1417     main_parse_command_line(argc, argv);
   1418 #if HAVE_CAPSICUM
   1419     init_capsicum();
   1420 #endif
   1421     main_prepare_parsing();
   1422     main_loop();
   1423 }
   1424 
   1425 /*
   1426  * Copy the input file to the backup file, then make the backup file the input
   1427  * and the original input file the output.
   1428  */
   1429 static void
   1430 bakcopy(void)
   1431 {
   1432     ssize_t n;
   1433     int bak_fd;
   1434     char buff[8 * 1024];
   1435 
   1436     const char *last_slash = strrchr(in_name, '/');
   1437     snprintf(bakfile, sizeof(bakfile), "%s%s",
   1438 	last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
   1439 
   1440     /* copy in_name to backup file */
   1441     bak_fd = creat(bakfile, 0600);
   1442     if (bak_fd < 0)
   1443 	err(1, "%s", bakfile);
   1444     while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
   1445 	if (write(bak_fd, buff, (size_t)n) != n)
   1446 	    err(1, "%s", bakfile);
   1447     if (n < 0)
   1448 	err(1, "%s", in_name);
   1449     close(bak_fd);
   1450     (void)fclose(input);
   1451 
   1452     /* re-open backup file as the input file */
   1453     input = fopen(bakfile, "r");
   1454     if (input == NULL)
   1455 	err(1, "%s", bakfile);
   1456     /* now the original input file will be the output */
   1457     output = fopen(in_name, "w");
   1458     if (output == NULL) {
   1459 	unlink(bakfile);
   1460 	err(1, "%s", in_name);
   1461     }
   1462 }
   1463 
   1464 static void
   1465 indent_declaration(int cur_decl_ind, bool tabs_to_var)
   1466 {
   1467     int pos = (int)(code.e - code.s);
   1468     char *startpos = code.e;
   1469 
   1470     /*
   1471      * get the tab math right for indentations that are not multiples of
   1472      * tabsize
   1473      */
   1474     if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
   1475 	pos += (ps.ind_level * opt.indent_size) % opt.tabsize;
   1476 	cur_decl_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
   1477     }
   1478     if (tabs_to_var) {
   1479 	int tpos;
   1480 
   1481 	check_size_code((size_t)(cur_decl_ind / opt.tabsize));
   1482 	while ((tpos = opt.tabsize * (1 + pos / opt.tabsize)) <= cur_decl_ind) {
   1483 	    *code.e++ = '\t';
   1484 	    pos = tpos;
   1485 	}
   1486     }
   1487     check_size_code((size_t)(cur_decl_ind - pos) + 1);
   1488     while (pos < cur_decl_ind) {
   1489 	*code.e++ = ' ';
   1490 	pos++;
   1491     }
   1492     if (code.e == startpos && ps.want_blank) {
   1493 	*code.e++ = ' ';
   1494 	ps.want_blank = false;
   1495     }
   1496 }
   1497 
   1498 #ifdef debug
   1499 void
   1500 debug_printf(const char *fmt, ...)
   1501 {
   1502     FILE *f = output == stdout ? stderr : stdout;
   1503     va_list ap;
   1504 
   1505     va_start(ap, fmt);
   1506     vfprintf(f, fmt, ap);
   1507     va_end(ap);
   1508 }
   1509 
   1510 void
   1511 debug_println(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     fprintf(f, "\n");
   1520 }
   1521 
   1522 void
   1523 debug_vis_range(const char *prefix, const char *s, const char *e,
   1524     const char *suffix)
   1525 {
   1526     debug_printf("%s", prefix);
   1527     for (const char *p = s; p < e; p++) {
   1528 	if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
   1529 	    debug_printf("%c", *p);
   1530 	else if (*p == '\n')
   1531 	    debug_printf("\\n");
   1532 	else if (*p == '\t')
   1533 	    debug_printf("\\t");
   1534 	else
   1535 	    debug_printf("\\x%02x", *p);
   1536     }
   1537     debug_printf("%s", suffix);
   1538 }
   1539 #endif
   1540 
   1541 static void *
   1542 nonnull(void *p)
   1543 {
   1544     if (p == NULL)
   1545 	err(EXIT_FAILURE, NULL);
   1546     return p;
   1547 }
   1548 
   1549 void *
   1550 xmalloc(size_t size)
   1551 {
   1552     return nonnull(malloc(size));
   1553 }
   1554 
   1555 void *
   1556 xrealloc(void *p, size_t new_size)
   1557 {
   1558     return nonnull(realloc(p, new_size));
   1559 }
   1560 
   1561 char *
   1562 xstrdup(const char *s)
   1563 {
   1564     return nonnull(strdup(s));
   1565 }
   1566