Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.81
      1 /*	$NetBSD: indent.c,v 1.81 2021/09/25 22:14:21 rillig Exp $	*/
      2 
      3 /*-
      4  * SPDX-License-Identifier: BSD-4-Clause
      5  *
      6  * Copyright (c) 1985 Sun Microsystems, Inc.
      7  * Copyright (c) 1976 Board of Trustees of the University of Illinois.
      8  * Copyright (c) 1980, 1993
      9  *	The Regents of the University of California.  All rights reserved.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the University of
     22  *	California, Berkeley and its contributors.
     23  * 4. Neither the name of the University nor the names of its contributors
     24  *    may be used to endorse or promote products derived from this software
     25  *    without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     37  * SUCH DAMAGE.
     38  */
     39 
     40 #if 0
     41 static char sccsid[] = "@(#)indent.c	5.17 (Berkeley) 6/7/93";
     42 #endif
     43 
     44 #include <sys/cdefs.h>
     45 #if defined(__NetBSD__)
     46 __RCSID("$NetBSD: indent.c,v 1.81 2021/09/25 22:14:21 rillig Exp $");
     47 #elif defined(__FreeBSD__)
     48 __FBSDID("$FreeBSD: head/usr.bin/indent/indent.c 340138 2018-11-04 19:24:49Z oshogbo $");
     49 #endif
     50 
     51 #include <sys/param.h>
     52 #if HAVE_CAPSICUM
     53 #include <sys/capsicum.h>
     54 #include <capsicum_helpers.h>
     55 #endif
     56 #include <err.h>
     57 #include <errno.h>
     58 #include <fcntl.h>
     59 #include <unistd.h>
     60 #include <stdio.h>
     61 #include <stdlib.h>
     62 #include <string.h>
     63 #include <ctype.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 int         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 = 0;
    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);
    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 
    662 	/*
    663 	 * if this is a unary op in a declaration, we should indent
    664 	 * this token
    665 	 */
    666 	int i;
    667 	for (i = 0; token.s[i] != '\0'; ++i)
    668 	    /* find length of token */;
    669 	indent_declaration(dec_ind - i, tabs_to_var);
    670 	ps.dumped_decl_indent = true;
    671     } else if (ps.want_blank)
    672 	*code.e++ = ' ';
    673 
    674     {
    675 	size_t len = token.e - token.s;
    676 
    677 	check_size_code(len);
    678 	memcpy(code.e, token.s, len);
    679 	code.e += len;
    680     }
    681     ps.want_blank = false;
    682 }
    683 
    684 static void
    685 process_binary_op(void)
    686 {
    687     size_t len = token.e - token.s;
    688 
    689     check_size_code(len + 1);
    690     if (ps.want_blank)
    691 	*code.e++ = ' ';
    692     memcpy(code.e, token.s, len);
    693     code.e += len;
    694 
    695     ps.want_blank = true;
    696 }
    697 
    698 static void
    699 process_postfix_op(void)
    700 {
    701     *code.e++ = token.s[0];
    702     *code.e++ = token.s[1];
    703     ps.want_blank = true;
    704 }
    705 
    706 static void
    707 process_question(int *inout_squest)
    708 {
    709     (*inout_squest)++;		/* this will be used when a later colon
    710 				 * appears so we can distinguish the
    711 				 * <c>?<n>:<n> construct */
    712     if (ps.want_blank)
    713 	*code.e++ = ' ';
    714     *code.e++ = '?';
    715     ps.want_blank = true;
    716 }
    717 
    718 static void
    719 process_colon(int *inout_squest, bool *inout_force_nl, bool *inout_scase)
    720 {
    721     if (*inout_squest > 0) {	/* it is part of the <c>?<n>: <n> construct */
    722 	--*inout_squest;
    723 	if (ps.want_blank)
    724 	    *code.e++ = ' ';
    725 	*code.e++ = ':';
    726 	ps.want_blank = true;
    727 	return;
    728     }
    729     if (ps.in_or_st) {
    730 	*code.e++ = ':';
    731 	ps.want_blank = false;
    732 	return;
    733     }
    734     ps.in_stmt = false;		/* seeing a label does not imply we are in a
    735 				 * stmt */
    736     /*
    737      * turn everything so far into a label
    738      */
    739     {
    740 	size_t len = code.e - code.s;
    741 
    742 	check_size_label(len + 3);
    743 	memcpy(lab.e, code.s, len);
    744 	lab.e += len;
    745 	*lab.e++ = ':';
    746 	*lab.e = '\0';
    747 	code.e = code.s;
    748     }
    749     *inout_force_nl = ps.pcase = *inout_scase;	/* ps.pcase will be used by
    750 						 * dump_line to decide how to
    751 						 * indent the label. force_nl
    752 						 * will force a case n: to be
    753 						 * on a line by itself */
    754     *inout_scase = false;
    755     ps.want_blank = false;
    756 }
    757 
    758 static void
    759 process_semicolon(bool *inout_scase, int *inout_squest, int dec_ind,
    760 		  bool tabs_to_var, bool *inout_sp_sw,
    761 		  token_type hd_type,
    762 		  bool *inout_force_nl)
    763 {
    764     if (ps.decl_nest == 0)
    765 	ps.in_or_st = false;	/* we are not in an initialization or
    766 				 * structure declaration */
    767     *inout_scase = false; /* these will only need resetting in an error */
    768     *inout_squest = 0;
    769     if (ps.last_token == rparen)
    770 	ps.in_parameter_declaration = false;
    771     ps.cast_mask = 0;
    772     ps.not_cast_mask = 0;
    773     ps.block_init = false;
    774     ps.block_init_level = 0;
    775     ps.just_saw_decl--;
    776 
    777     if (ps.in_decl && code.s == code.e && !ps.block_init &&
    778 	!ps.dumped_decl_indent && ps.paren_level == 0) {
    779 	/* indent stray semicolons in declarations */
    780 	indent_declaration(dec_ind - 1, tabs_to_var);
    781 	ps.dumped_decl_indent = true;
    782     }
    783 
    784     ps.in_decl = (ps.decl_nest > 0);	/* if we were in a first level
    785 						 * structure declaration, we
    786 						 * arent any more */
    787 
    788     if ((!*inout_sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
    789 
    790 	/*
    791 	 * This should be true iff there were unbalanced parens in the
    792 	 * stmt.  It is a bit complicated, because the semicolon might
    793 	 * be in a for stmt
    794 	 */
    795 	diag(1, "Unbalanced parens");
    796 	ps.p_l_follow = 0;
    797 	if (*inout_sp_sw) {	/* this is a check for an if, while, etc. with
    798 				 * unbalanced parens */
    799 	    *inout_sp_sw = false;
    800 	    parse(hd_type);	/* dont lose the if, or whatever */
    801 	}
    802     }
    803     *code.e++ = ';';
    804     ps.want_blank = true;
    805     ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in the
    806 				 * middle of a stmt */
    807 
    808     if (!*inout_sp_sw) {	/* if not if for (;;) */
    809 	parse(semicolon);	/* let parser know about end of stmt */
    810 	*inout_force_nl = true;/* force newline after an end of stmt */
    811     }
    812 }
    813 
    814 static void
    815 process_lbrace(bool *inout_force_nl, bool *inout_sp_sw, token_type hd_type,
    816 	       int *di_stack, int di_stack_cap, int *inout_dec_ind)
    817 {
    818     ps.in_stmt = false;	/* dont indent the {} */
    819     if (!ps.block_init)
    820 	*inout_force_nl = true;	/* force other stuff on same line as '{' onto
    821 				 * new line */
    822     else if (ps.block_init_level <= 0)
    823 	ps.block_init_level = 1;
    824     else
    825 	ps.block_init_level++;
    826 
    827     if (code.s != code.e && !ps.block_init) {
    828 	if (!opt.btype_2) {
    829 	    dump_line();
    830 	    ps.want_blank = false;
    831 	} else if (ps.in_parameter_declaration && !ps.in_or_st) {
    832 	    ps.ind_level_follow = 0;
    833 	    if (opt.function_brace_split) { /* dump the line prior
    834 				 * to the brace ... */
    835 		dump_line();
    836 		ps.want_blank = false;
    837 	    } else		/* add a space between the decl and brace */
    838 		ps.want_blank = true;
    839 	}
    840     }
    841     if (ps.in_parameter_declaration)
    842 	prefix_blankline_requested = false;
    843 
    844     if (ps.p_l_follow > 0) {	/* check for preceding unbalanced
    845 				 * parens */
    846 	diag(1, "Unbalanced parens");
    847 	ps.p_l_follow = 0;
    848 	if (*inout_sp_sw) {	/* check for unclosed if, for, etc. */
    849 	    *inout_sp_sw = false;
    850 	    parse(hd_type);
    851 	    ps.ind_level = ps.ind_level_follow;
    852 	}
    853     }
    854     if (code.s == code.e)
    855 	ps.ind_stmt = false;	/* dont put extra indentation on line
    856 				 * with '{' */
    857     if (ps.in_decl && ps.in_or_st) {	/* this is either a structure
    858 				 * declaration or an init */
    859 	di_stack[ps.decl_nest] = *inout_dec_ind;
    860 	if (++ps.decl_nest == di_stack_cap) {
    861 	    diag(0, "Reached internal limit of %d struct levels",
    862 		 di_stack_cap);
    863 	    ps.decl_nest--;
    864 	}
    865 	/* ?		dec_ind = 0; */
    866     } else {
    867 	ps.decl_on_line = false;	/* we can't be in the middle of
    868 						 * a declaration, so don't do
    869 						 * special indentation of
    870 						 * comments */
    871 	if (opt.blanklines_after_declarations_at_proctop
    872 	    && ps.in_parameter_declaration)
    873 	    postfix_blankline_requested = true;
    874 	ps.in_parameter_declaration = false;
    875 	ps.in_decl = false;
    876     }
    877     *inout_dec_ind = 0;
    878     parse(lbrace);	/* let parser know about this */
    879     if (ps.want_blank)	/* put a blank before '{' if '{' is not at
    880 				 * start of line */
    881 	*code.e++ = ' ';
    882     ps.want_blank = false;
    883     *code.e++ = '{';
    884     ps.just_saw_decl = 0;
    885 }
    886 
    887 static void
    888 process_rbrace(bool *inout_sp_sw, int *inout_dec_ind, const int *di_stack)
    889 {
    890     if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
    891 				 * omitted in declarations */
    892 	parse(semicolon);
    893     if (ps.p_l_follow != 0) {	/* check for unclosed if, for, else. */
    894 	diag(1, "Unbalanced parens");
    895 	ps.p_l_follow = 0;
    896 	*inout_sp_sw = false;
    897     }
    898     ps.just_saw_decl = 0;
    899     ps.block_init_level--;
    900     if (code.s != code.e && !ps.block_init) {	/* '}' must be first on line */
    901 	if (opt.verbose)
    902 	    diag(0, "Line broken");
    903 	dump_line();
    904     }
    905     *code.e++ = '}';
    906     ps.want_blank = true;
    907     ps.in_stmt = ps.ind_stmt = false;
    908     if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
    909 	*inout_dec_ind = di_stack[--ps.decl_nest];
    910 	if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
    911 	    ps.just_saw_decl = 2;
    912 	ps.in_decl = true;
    913     }
    914     prefix_blankline_requested = false;
    915     parse(rbrace);		/* let parser know about this */
    916     ps.search_brace = opt.cuddle_else
    917 		      && ps.p_stack[ps.tos] == if_expr_stmt
    918 		      && ps.il[ps.tos] >= ps.ind_level;
    919     if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
    920 	postfix_blankline_requested = true;
    921 }
    922 
    923 static void
    924 process_keyword_do_else(bool *inout_force_nl, bool *inout_last_else)
    925 {
    926     ps.in_stmt = false;
    927     if (*token.s == 'e') {
    928 	if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
    929 	    if (opt.verbose)
    930 		diag(0, "Line broken");
    931 	    dump_line();	/* make sure this starts a line */
    932 	    ps.want_blank = false;
    933 	}
    934 	*inout_force_nl = true;/* also, following stuff must go onto new line */
    935 	*inout_last_else = true;
    936 	parse(keyword_else);
    937     } else {
    938 	if (code.e != code.s) {	/* make sure this starts a line */
    939 	    if (opt.verbose)
    940 		diag(0, "Line broken");
    941 	    dump_line();
    942 	    ps.want_blank = false;
    943 	}
    944 	*inout_force_nl = true;/* also, following stuff must go onto new line */
    945 	*inout_last_else = false;
    946 	parse(keyword_do);
    947     }
    948 }
    949 
    950 static void
    951 process_decl(int *out_dec_ind, bool *out_tabs_to_var)
    952 {
    953     parse(decl);		/* let parser worry about indentation */
    954     if (ps.last_token == rparen && ps.tos <= 1) {
    955 	if (code.s != code.e) {
    956 	    dump_line();
    957 	    ps.want_blank = false;
    958 	}
    959     }
    960     if (ps.in_parameter_declaration && opt.indent_parameters &&
    961 	ps.decl_nest == 0) {
    962 	ps.ind_level = ps.ind_level_follow = 1;
    963 	ps.ind_stmt = false;
    964     }
    965     ps.in_or_st = true;		/* this might be a structure or initialization
    966 				 * declaration */
    967     ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
    968     if ( /* !ps.in_or_st && */ ps.decl_nest <= 0)
    969 	ps.just_saw_decl = 2;
    970     prefix_blankline_requested = false;
    971     int i;
    972     for (i = 0; token.s[i++] != '\0';);	/* get length of token */
    973 
    974     if (ps.ind_level == 0 || ps.decl_nest > 0) {
    975 	/* global variable or struct member in local variable */
    976 	*out_dec_ind = opt.decl_indent > 0 ? opt.decl_indent : i;
    977 	*out_tabs_to_var = opt.use_tabs ? opt.decl_indent > 0 : false;
    978     } else {
    979 	/* local variable */
    980 	*out_dec_ind = opt.local_decl_indent > 0 ? opt.local_decl_indent : i;
    981 	*out_tabs_to_var = opt.use_tabs ? opt.local_decl_indent > 0 : false;
    982     }
    983 }
    984 
    985 static void
    986 process_ident(token_type ttype, int dec_ind, bool tabs_to_var,
    987 	      bool *inout_sp_sw, bool *inout_force_nl, token_type hd_type)
    988 {
    989     if (ps.in_decl) {
    990 	if (ttype == funcname) {
    991 	    ps.in_decl = false;
    992 	    if (opt.procnames_start_line && code.s != code.e) {
    993 		*code.e = '\0';
    994 		dump_line();
    995 	    } else if (ps.want_blank) {
    996 		*code.e++ = ' ';
    997 	    }
    998 	    ps.want_blank = false;
    999 	} else if (!ps.block_init && !ps.dumped_decl_indent &&
   1000 		   ps.paren_level == 0) { /* if we are in a declaration, we
   1001 					    * must indent identifier */
   1002 	    indent_declaration(dec_ind, tabs_to_var);
   1003 	    ps.dumped_decl_indent = true;
   1004 	    ps.want_blank = false;
   1005 	}
   1006     } else if (*inout_sp_sw && ps.p_l_follow == 0) {
   1007 	*inout_sp_sw = false;
   1008 	*inout_force_nl = true;
   1009 	ps.last_u_d = true;
   1010 	ps.in_stmt = false;
   1011 	parse(hd_type);
   1012     }
   1013 }
   1014 
   1015 static void
   1016 copy_id(void)
   1017 {
   1018     size_t len = token.e - token.s;
   1019 
   1020     check_size_code(len + 1);
   1021     if (ps.want_blank)
   1022 	*code.e++ = ' ';
   1023     memcpy(code.e, token.s, len);
   1024     code.e += len;
   1025 }
   1026 
   1027 static void
   1028 process_string_prefix(void)
   1029 {
   1030     size_t len = token.e - token.s;
   1031 
   1032     check_size_code(len + 1);
   1033     if (ps.want_blank)
   1034 	*code.e++ = ' ';
   1035     memcpy(code.e, token.s, len);
   1036     code.e += len;
   1037 
   1038     ps.want_blank = false;
   1039 }
   1040 
   1041 static void
   1042 process_period(void)
   1043 {
   1044     *code.e++ = '.';		/* move the period into line */
   1045     ps.want_blank = false;	/* dont put a blank after a period */
   1046 }
   1047 
   1048 static void
   1049 process_comma(int dec_ind, bool tabs_to_var, bool *inout_force_nl)
   1050 {
   1051     ps.want_blank = (code.s != code.e);	/* only put blank after comma
   1052 				 * if comma does not start the line */
   1053     if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
   1054 	!ps.dumped_decl_indent && ps.paren_level == 0) {
   1055 	/* indent leading commas and not the actual identifiers */
   1056 	indent_declaration(dec_ind - 1, tabs_to_var);
   1057 	ps.dumped_decl_indent = true;
   1058     }
   1059     *code.e++ = ',';
   1060     if (ps.p_l_follow == 0) {
   1061 	if (ps.block_init_level <= 0)
   1062 	    ps.block_init = false;
   1063 	if (break_comma && (!opt.leave_comma ||
   1064 			    indentation_after_range(
   1065 				    compute_code_indent(), code.s, code.e)
   1066 			    >= opt.max_line_length - opt.tabsize))
   1067 	    *inout_force_nl = true;
   1068     }
   1069 }
   1070 
   1071 static void
   1072 process_preprocessing(void)
   1073 {
   1074     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
   1075 	dump_line();
   1076     check_size_label(1);
   1077     *lab.e++ = '#';	/* move whole line to 'label' buffer */
   1078 
   1079     {
   1080 	bool in_comment = false;
   1081 	int         com_start = 0;
   1082 	char        quote = '\0';
   1083 	int         com_end = 0;
   1084 
   1085 	while (*buf_ptr == ' ' || *buf_ptr == '\t') {
   1086 	    buf_ptr++;
   1087 	    if (buf_ptr >= buf_end)
   1088 		fill_buffer();
   1089 	}
   1090 	while (*buf_ptr != '\n' || (in_comment && !had_eof)) {
   1091 	    check_size_label(2);
   1092 	    *lab.e = *buf_ptr++;
   1093 	    if (buf_ptr >= buf_end)
   1094 		fill_buffer();
   1095 	    switch (*lab.e++) {
   1096 	    case '\\':
   1097 		if (!in_comment) {
   1098 		    *lab.e++ = *buf_ptr++;
   1099 		    if (buf_ptr >= buf_end)
   1100 			fill_buffer();
   1101 		}
   1102 		break;
   1103 	    case '/':
   1104 		if (*buf_ptr == '*' && !in_comment && quote == '\0') {
   1105 		    in_comment = true;
   1106 		    *lab.e++ = *buf_ptr++;
   1107 		    com_start = (int)(lab.e - lab.s) - 2;
   1108 		}
   1109 		break;
   1110 	    case '"':
   1111 		if (quote == '"')
   1112 		    quote = '\0';
   1113 		else if (quote == '\0')
   1114 		    quote = '"';
   1115 		break;
   1116 	    case '\'':
   1117 		if (quote == '\'')
   1118 		    quote = '\0';
   1119 		else if (quote == '\0')
   1120 		    quote = '\'';
   1121 		break;
   1122 	    case '*':
   1123 		if (*buf_ptr == '/' && in_comment) {
   1124 		    in_comment = false;
   1125 		    *lab.e++ = *buf_ptr++;
   1126 		    com_end = (int)(lab.e - lab.s);
   1127 		}
   1128 		break;
   1129 	    }
   1130 	}
   1131 
   1132 	while (lab.e > lab.s && (lab.e[-1] == ' ' || lab.e[-1] == '\t'))
   1133 	    lab.e--;
   1134 	if (lab.e - lab.s == com_end && bp_save == NULL) {
   1135 	    /* comment on preprocessor line */
   1136 	    if (sc_end == NULL) {	/* if this is the first comment,
   1137 						 * we must set up the buffer */
   1138 		save_com = sc_buf;
   1139 		sc_end = &save_com[0];
   1140 	    } else {
   1141 		*sc_end++ = '\n';	/* add newline between
   1142 						 * comments */
   1143 		*sc_end++ = ' ';
   1144 		--line_no;
   1145 	    }
   1146 	    if (sc_end - save_com + com_end - com_start > sc_size)
   1147 		errx(1, "input too long");
   1148 	    memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
   1149 	    sc_end += com_end - com_start;
   1150 	    lab.e = lab.s + com_start;
   1151 	    while (lab.e > lab.s && (lab.e[-1] == ' ' || lab.e[-1] == '\t'))
   1152 		lab.e--;
   1153 	    bp_save = buf_ptr;	/* save current input buffer */
   1154 	    be_save = buf_end;
   1155 	    buf_ptr = save_com;	/* fix so that subsequent calls to lexi will
   1156 				 * take tokens out of save_com */
   1157 	    *sc_end++ = ' ';	/* add trailing blank, just in case */
   1158 	    buf_end = sc_end;
   1159 	    sc_end = NULL;
   1160 	    debug_println("switched buf_ptr to save_com");
   1161 	}
   1162 	check_size_label(1);
   1163 	*lab.e = '\0';	/* null terminate line */
   1164 	ps.pcase = false;
   1165     }
   1166 
   1167     if (strncmp(lab.s, "#if", 3) == 0) { /* also ifdef, ifndef */
   1168 	if ((size_t)ifdef_level < nitems(state_stack)) {
   1169 	    match_state[ifdef_level].tos = -1;
   1170 	    state_stack[ifdef_level++] = ps;
   1171 	} else
   1172 	    diag(1, "#if stack overflow");
   1173     } else if (strncmp(lab.s, "#el", 3) == 0) { /* else, elif */
   1174 	if (ifdef_level <= 0)
   1175 	    diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
   1176 	else {
   1177 	    match_state[ifdef_level - 1] = ps;
   1178 	    ps = state_stack[ifdef_level - 1];
   1179 	}
   1180     } else if (strncmp(lab.s, "#endif", 6) == 0) {
   1181 	if (ifdef_level <= 0)
   1182 	    diag(1, "Unmatched #endif");
   1183 	else
   1184 	    ifdef_level--;
   1185     } else {
   1186 	if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
   1187 	    strncmp(lab.s + 1, "error", 5) != 0 &&
   1188 	    strncmp(lab.s + 1, "line", 4) != 0 &&
   1189 	    strncmp(lab.s + 1, "undef", 5) != 0 &&
   1190 	    strncmp(lab.s + 1, "define", 6) != 0 &&
   1191 	    strncmp(lab.s + 1, "include", 7) != 0) {
   1192 	    diag(1, "Unrecognized cpp directive");
   1193 	    return;
   1194 	}
   1195     }
   1196     if (opt.blanklines_around_conditional_compilation) {
   1197 	postfix_blankline_requested = true;
   1198 	n_real_blanklines = 0;
   1199     } else {
   1200 	postfix_blankline_requested = false;
   1201 	prefix_blankline_requested = false;
   1202     }
   1203 
   1204     /*
   1205      * subsequent processing of the newline character will cause the line to
   1206      * be printed
   1207      */
   1208 }
   1209 
   1210 static void __attribute__((__noreturn__))
   1211 main_loop(void)
   1212 {
   1213     token_type ttype;
   1214     bool force_nl;		/* when true, code must be broken */
   1215     bool last_else = false;	/* true iff last keyword was an else */
   1216     int         dec_ind;	/* current indentation for declarations */
   1217     int         di_stack[20];	/* a stack of structure indentation levels */
   1218     bool tabs_to_var;		/* true if using tabs to indent to var name */
   1219     bool sp_sw;			/* when true, we are in the expression of
   1220 				 * if(...), while(...), etc. */
   1221     token_type  hd_type = end_of_file; /* used to store type of stmt
   1222 				 * for if (...), for (...), etc */
   1223     int squest;			/* when this is positive, we have seen a '?'
   1224 				 * without the matching ':' in a <c>?<s>:<s>
   1225 				 * construct */
   1226     bool scase;			/* set to true when we see a case, so we will
   1227 				 * know what to do with the following colon */
   1228 
   1229     sp_sw = force_nl = false;
   1230     dec_ind = 0;
   1231     di_stack[ps.decl_nest = 0] = 0;
   1232     scase = false;
   1233     squest = 0;
   1234     tabs_to_var = false;
   1235 
   1236     for (;;) {			/* this is the main loop.  it will go until we
   1237 				 * reach eof */
   1238 	bool comment_buffered = false;
   1239 
   1240 	ttype = lexi(&ps);	/* Read the next token.  The actual characters
   1241 				 * read are stored in "token". */
   1242 
   1243 	/*
   1244 	 * The following code moves newlines and comments following an if (),
   1245 	 * while (), else, etc. up to the start of the following stmt to
   1246 	 * a buffer. This allows proper handling of both kinds of brace
   1247 	 * placement (-br, -bl) and cuddling "else" (-ce).
   1248 	 */
   1249 	search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
   1250 
   1251 	if (ttype == end_of_file) {
   1252 	    process_end_of_file();
   1253 	    /* NOTREACHED */
   1254 	}
   1255 
   1256 	if (
   1257 		ttype != comment &&
   1258 		ttype != newline &&
   1259 		ttype != preprocessing &&
   1260 		ttype != form_feed) {
   1261 	    process_comment_in_code(ttype, &force_nl);
   1262 
   1263 	} else if (ttype != comment) /* preserve force_nl through a comment */
   1264 	    force_nl = false;	/* cancel forced newline after newline, form
   1265 				 * feed, etc */
   1266 
   1267 
   1268 
   1269 	/*-----------------------------------------------------*\
   1270 	|	   do switch on type of token scanned		|
   1271 	\*-----------------------------------------------------*/
   1272 	check_size_code(3);	/* maximum number of increments of code.e
   1273 				 * before the next check_size_code or
   1274 				 * dump_line() is 2. After that there's the
   1275 				 * final increment for the null character. */
   1276 	switch (ttype) {
   1277 
   1278 	case form_feed:
   1279 	    process_form_feed();
   1280 	    break;
   1281 
   1282 	case newline:
   1283 	    process_newline();
   1284 	    break;
   1285 
   1286 	case lparen:		/* got a '(' or '[' */
   1287 	    process_lparen_or_lbracket(dec_ind, tabs_to_var, sp_sw);
   1288 	    break;
   1289 
   1290 	case rparen:		/* got a ')' or ']' */
   1291 	    process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
   1292 	    break;
   1293 
   1294 	case unary_op:		/* this could be any unary operation */
   1295 	    process_unary_op(dec_ind, tabs_to_var);
   1296 	    break;
   1297 
   1298 	case binary_op:		/* any binary operation */
   1299 	    process_binary_op();
   1300 	    break;
   1301 
   1302 	case postfix_op:	/* got a trailing ++ or -- */
   1303 	    process_postfix_op();
   1304 	    break;
   1305 
   1306 	case question:		/* got a ? */
   1307 	    process_question(&squest);
   1308 	    break;
   1309 
   1310 	case case_label:	/* got word 'case' or 'default' */
   1311 	    scase = true;	/* so we can process the later colon properly */
   1312 	    goto copy_id;
   1313 
   1314 	case colon:		/* got a ':' */
   1315 	    process_colon(&squest, &force_nl, &scase);
   1316 	    break;
   1317 
   1318 	case semicolon:		/* got a ';' */
   1319 	    process_semicolon(&scase, &squest, dec_ind, tabs_to_var, &sp_sw,
   1320 		hd_type, &force_nl);
   1321 	    break;
   1322 
   1323 	case lbrace:		/* got a '{' */
   1324 	    process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
   1325 		(int)nitems(di_stack), &dec_ind);
   1326 	    break;
   1327 
   1328 	case rbrace:		/* got a '}' */
   1329 	    process_rbrace(&sp_sw, &dec_ind, di_stack);
   1330 	    break;
   1331 
   1332 	case switch_expr:	/* got keyword "switch" */
   1333 	    sp_sw = true;
   1334 	    hd_type = switch_expr; /* keep this for when we have seen the
   1335 				 * expression */
   1336 	    goto copy_id;	/* go move the token into buffer */
   1337 
   1338 	case keyword_for_if_while:
   1339 	    sp_sw = true;	/* the interesting stuff is done after the
   1340 				 * expression is scanned */
   1341 	    hd_type = (*token.s == 'i' ? if_expr :
   1342 		       (*token.s == 'w' ? while_expr : for_exprs));
   1343 
   1344 	    /* remember the type of header for later use by parser */
   1345 	    goto copy_id;	/* copy the token into line */
   1346 
   1347 	case keyword_do_else:
   1348 	    process_keyword_do_else(&force_nl, &last_else);
   1349 	    goto copy_id;	/* move the token into line */
   1350 
   1351 	case type_def:
   1352 	case storage_class:
   1353 	    prefix_blankline_requested = false;
   1354 	    goto copy_id;
   1355 
   1356 	case keyword_struct_union_enum:
   1357 	    if (ps.p_l_follow > 0)
   1358 		goto copy_id;
   1359 	    /* FALLTHROUGH */
   1360 	case decl:		/* we have a declaration type (int, etc.) */
   1361 	    process_decl(&dec_ind, &tabs_to_var);
   1362 	    goto copy_id;
   1363 
   1364 	case funcname:
   1365 	case ident:		/* got an identifier or constant */
   1366 	    process_ident(ttype, dec_ind, tabs_to_var, &sp_sw, &force_nl,
   1367 			  hd_type);
   1368     copy_id:
   1369 	    copy_id();
   1370 	    if (ttype != funcname)
   1371 		ps.want_blank = true;
   1372 	    break;
   1373 
   1374 	case string_prefix:
   1375 	    process_string_prefix();
   1376 	    break;
   1377 
   1378 	case period:
   1379 	    process_period();
   1380 	    break;
   1381 
   1382 	case comma:
   1383 	    process_comma(dec_ind, tabs_to_var, &force_nl);
   1384 	    break;
   1385 
   1386 	case preprocessing:	/* '#' */
   1387 	    process_preprocessing();
   1388 	    break;
   1389 	case comment:		/* the initial '/' '*' or '//' of a comment */
   1390 	    process_comment();
   1391 	    break;
   1392 
   1393 	default:
   1394 	    break;
   1395 	}
   1396 
   1397 	*code.e = '\0';
   1398 	if (ttype != comment &&
   1399 	    ttype != newline &&
   1400 	    ttype != preprocessing)
   1401 	    ps.last_token = ttype;
   1402     }
   1403 }
   1404 
   1405 int
   1406 main(int argc, char **argv)
   1407 {
   1408     main_init_globals();
   1409     main_parse_command_line(argc, argv);
   1410 #if HAVE_CAPSICUM
   1411     init_capsicum();
   1412 #endif
   1413     main_prepare_parsing();
   1414     main_loop();
   1415 }
   1416 
   1417 /*
   1418  * copy input file to backup file if in_name is /blah/blah/blah/file, then
   1419  * backup file will be ".Bfile" then make the backup file the input and
   1420  * original input file the output
   1421  */
   1422 static void
   1423 bakcopy(void)
   1424 {
   1425     ssize_t n;
   1426     int bakchn;
   1427     char buff[8 * 1024];
   1428     const char *p;
   1429 
   1430     /* construct file name .Bfile */
   1431     for (p = in_name; *p != '\0'; p++);	/* skip to end of string */
   1432     while (p > in_name && *p != '/')	/* find last '/' */
   1433 	p--;
   1434     if (*p == '/')
   1435 	p++;
   1436     sprintf(bakfile, "%s%s", p, simple_backup_suffix);
   1437 
   1438     /* copy in_name to backup file */
   1439     bakchn = creat(bakfile, 0600);
   1440     if (bakchn < 0)
   1441 	err(1, "%s", bakfile);
   1442     while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
   1443 	if (write(bakchn, buff, (size_t)n) != n)
   1444 	    err(1, "%s", bakfile);
   1445     if (n < 0)
   1446 	err(1, "%s", in_name);
   1447     close(bakchn);
   1448     fclose(input);
   1449 
   1450     /* re-open backup file as the input file */
   1451     input = fopen(bakfile, "r");
   1452     if (input == NULL)
   1453 	err(1, "%s", bakfile);
   1454     /* now the original input file will be the output */
   1455     output = fopen(in_name, "w");
   1456     if (output == NULL) {
   1457 	unlink(bakfile);
   1458 	err(1, "%s", in_name);
   1459     }
   1460 }
   1461 
   1462 static void
   1463 indent_declaration(int cur_dec_ind, bool tabs_to_var)
   1464 {
   1465     int pos = (int)(code.e - code.s);
   1466     char *startpos = code.e;
   1467 
   1468     /*
   1469      * get the tab math right for indentations that are not multiples of tabsize
   1470      */
   1471     if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
   1472 	pos += (ps.ind_level * opt.indent_size) % opt.tabsize;
   1473 	cur_dec_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
   1474     }
   1475     if (tabs_to_var) {
   1476 	int tpos;
   1477 
   1478 	check_size_code((size_t)(cur_dec_ind / opt.tabsize));
   1479 	while ((tpos = opt.tabsize * (1 + pos / opt.tabsize)) <= cur_dec_ind) {
   1480 	    *code.e++ = '\t';
   1481 	    pos = tpos;
   1482 	}
   1483     }
   1484     check_size_code((size_t)(cur_dec_ind - pos + 1));
   1485     while (pos < cur_dec_ind) {
   1486 	*code.e++ = ' ';
   1487 	pos++;
   1488     }
   1489     if (code.e == startpos && ps.want_blank) {
   1490 	*code.e++ = ' ';
   1491 	ps.want_blank = false;
   1492     }
   1493 }
   1494 
   1495 #ifdef debug
   1496 void
   1497 debug_printf(const char *fmt, ...)
   1498 {
   1499     FILE *f = output == stdout ? stderr : stdout;
   1500     va_list ap;
   1501 
   1502     va_start(ap, fmt);
   1503     vfprintf(f, fmt, ap);
   1504     va_end(ap);
   1505 }
   1506 
   1507 void
   1508 debug_println(const char *fmt, ...)
   1509 {
   1510     FILE *f = output == stdout ? stderr : stdout;
   1511     va_list ap;
   1512 
   1513     va_start(ap, fmt);
   1514     vfprintf(f, fmt, ap);
   1515     va_end(ap);
   1516     fprintf(f, "\n");
   1517 }
   1518 
   1519 void
   1520 debug_vis_range(const char *prefix, const char *s, const char *e,
   1521 		const char *suffix)
   1522 {
   1523     debug_printf("%s", prefix);
   1524     for (const char *p = s; p < e; p++) {
   1525 	if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
   1526 	    debug_printf("%c", *p);
   1527 	else if (*p == '\n')
   1528 	    debug_printf("\\n");
   1529 	else if (*p == '\t')
   1530 	    debug_printf("\\t");
   1531 	else
   1532 	    debug_printf("\\x%02x", *p);
   1533     }
   1534     debug_printf("%s", suffix);
   1535 }
   1536 #endif
   1537 
   1538 static void *
   1539 nonnull(void *p)
   1540 {
   1541     if (p == NULL)
   1542 	err(EXIT_FAILURE, NULL);
   1543     return p;
   1544 }
   1545 
   1546 void *
   1547 xmalloc(size_t size)
   1548 {
   1549     return nonnull(malloc(size));
   1550 }
   1551 
   1552 void *
   1553 xrealloc(void *p, size_t new_size)
   1554 {
   1555     return nonnull(realloc(p, new_size));
   1556 }
   1557 
   1558 char *
   1559 xstrdup(const char *s)
   1560 {
   1561     return nonnull(strdup(s));
   1562 }
   1563