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