Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.86
      1 /*	$NetBSD: indent.c,v 1.86 2021/09/26 19:37:11 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.86 2021/09/26 19:37:11 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 has
    185 	     * been scanned in this loop, force_nl should be false.
    186 	     *
    187 	     * However, the force_nl == true must be preserved if newline is
    188 	     * never scanned in this loop, so this assignment cannot be done
    189 	     * 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 jump
    230 	     * out of this loop in order to avoid copying the token again
    231 	     * 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 line,
    237 		 * but it will be moved into "the else's line", so if there
    238 		 * was a newline resulting from the "{" before, it must be
    239 		 * 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 EOF.
    307 	 */
    308 	if (*inout_ttype != end_of_file) {
    309 	    /*
    310 	     * The only intended purpose of calling lexi() below is to
    311 	     * categorize the next token in order to decide whether to
    312 	     * continue buffering forthcoming tokens. Once the buffering is
    313 	     * over, lexi() will be called again elsewhere on all of the
    314 	     * tokens - this time for normal processing.
    315 	     *
    316 	     * Calling it for this purpose is a bug, because lexi() also
    317 	     * changes the parser state and discards leading whitespace, which
    318 	     * is needed mostly for comment-related considerations.
    319 	     *
    320 	     * Work around the former problem by giving lexi() a copy of the
    321 	     * current parser state and discard it if the call turned out to
    322 	     * be just a look ahead.
    323 	     *
    324 	     * Work around the latter problem by copying all whitespace
    325 	     * characters into the buffer so that the later lexi() call will
    326 	     * read them.
    327 	     */
    328 	    if (sc_end != NULL) {
    329 		while (*buf_ptr == ' ' || *buf_ptr == '\t') {
    330 		    *sc_end++ = *buf_ptr++;
    331 		    if (sc_end >= &save_com[sc_size]) {
    332 			errx(1, "input too long");
    333 		    }
    334 		}
    335 		if (buf_ptr >= buf_end) {
    336 		    fill_buffer();
    337 		}
    338 	    }
    339 
    340 	    struct parser_state transient_state;
    341 	    transient_state = ps;
    342 	    *inout_ttype = lexi(&transient_state);	/* read another token */
    343 	    if (*inout_ttype != newline && *inout_ttype != form_feed &&
    344 		*inout_ttype != comment && !transient_state.search_brace) {
    345 		ps = transient_state;
    346 	    }
    347 	}
    348     }
    349 
    350     *inout_last_else = false;
    351 }
    352 
    353 static void
    354 buf_init(struct buffer *buf)
    355 {
    356     buf->buf = xmalloc(bufsize);
    357     buf->buf[0] = ' ';		/* allow accessing buf->e[-1] */
    358     buf->buf[1] = '\0';
    359     buf->s = buf->buf + 1;
    360     buf->e = buf->s;
    361     buf->l = buf->buf + bufsize - 5;	/* safety margin, though unreliable */
    362 }
    363 
    364 void
    365 buf_expand(struct buffer *buf, size_t desired_size)
    366 {
    367     size_t nsize = buf->l - buf->s + 400 + desired_size;
    368     size_t code_len = buf->e - buf->s;
    369     buf->buf = xrealloc(buf->buf, nsize);
    370     buf->e = buf->buf + code_len + 1;
    371     buf->l = buf->buf + nsize - 5;
    372     buf->s = buf->buf + 1;
    373 }
    374 
    375 static void
    376 main_init_globals(void)
    377 {
    378     found_err = false;
    379 
    380     ps.p_stack[0] = stmt;	/* this is the parser's stack */
    381     ps.last_nl = true;		/* this is true if the last thing scanned was
    382 				 * a newline */
    383     ps.last_token = semicolon;
    384     buf_init(&com);
    385     buf_init(&lab);
    386     buf_init(&code);
    387     buf_init(&token);
    388     alloc_typenames();
    389     opt.else_if = true;		/* XXX: redundant? */
    390 
    391     in_buffer = xmalloc(10);
    392     in_buffer_limit = in_buffer + 8;
    393     buf_ptr = buf_end = in_buffer;
    394     line_no = 1;
    395     had_eof = ps.in_decl = ps.decl_on_line = (break_comma = false);
    396     ps.in_or_st = false;
    397     ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
    398 
    399     ps.pcase = false;
    400     sc_end = NULL;
    401     bp_save = NULL;
    402     be_save = NULL;
    403 
    404     output = NULL;
    405 
    406     const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
    407     if (suffix != NULL)
    408 	simple_backup_suffix = suffix;
    409 }
    410 
    411 static void
    412 main_parse_command_line(int argc, char **argv)
    413 {
    414     int i;
    415     const char *profile_name = NULL;
    416 
    417     for (i = 1; i < argc; ++i)
    418 	if (strcmp(argv[i], "-npro") == 0)
    419 	    break;
    420 	else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0')
    421 	    profile_name = argv[i];	/* non-empty -P (set profile) */
    422     if (i >= argc)
    423 	set_profile(profile_name);
    424 
    425     for (i = 1; i < argc; ++i) {
    426 	if (argv[i][0] == '-') {
    427 	    set_option(argv[i]);
    428 
    429 	} else if (input == NULL) {
    430 	    in_name = argv[i];
    431 	    input = fopen(in_name, "r");
    432 	    if (input == NULL)
    433 		err(1, "%s", in_name);
    434 
    435 	} else if (output == NULL) {
    436 	    out_name = argv[i];
    437 	    if (strcmp(in_name, out_name) == 0)
    438 		errx(1, "input and output files must be different");
    439 	    output = fopen(out_name, "w");
    440 	    if (output == NULL)
    441 		err(1, "%s", out_name);
    442 
    443 	} else
    444 	    errx(1, "unknown parameter: %s", argv[i]);
    445     }
    446 
    447     if (input == NULL)
    448 	input = stdin;
    449     if (output == NULL) {
    450 	if (input == stdin)
    451 	    output = stdout;
    452 	else {
    453 	    out_name = in_name;
    454 	    bakcopy();
    455 	}
    456     }
    457 
    458     if (opt.comment_column <= 1)
    459 	opt.comment_column = 2;	/* don't put normal comments before column 2 */
    460     if (opt.block_comment_max_line_length <= 0)
    461 	opt.block_comment_max_line_length = opt.max_line_length;
    462     if (opt.local_decl_indent < 0) /* if not specified by user, set this */
    463 	opt.local_decl_indent = opt.decl_indent;
    464     if (opt.decl_comment_column <= 0)	/* if not specified by user, set this */
    465 	opt.decl_comment_column = opt.ljust_decl
    466 	    ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
    467 	    : opt.comment_column;
    468     if (opt.continuation_indent == 0)
    469 	opt.continuation_indent = opt.indent_size;
    470 }
    471 
    472 static void
    473 main_prepare_parsing(void)
    474 {
    475     fill_buffer();		/* get first batch of stuff into input buffer */
    476 
    477     parse(semicolon);
    478 
    479     char *p = buf_ptr;
    480     int col = 1;
    481 
    482     for (;;) {
    483 	if (*p == ' ')
    484 	    col++;
    485 	else if (*p == '\t')
    486 	    col = opt.tabsize * (1 + (col - 1) / opt.tabsize) + 1;
    487 	else
    488 	    break;
    489 	p++;
    490     }
    491     if (col > opt.indent_size)
    492 	ps.ind_level = ps.ind_level_follow = col / opt.indent_size;
    493 }
    494 
    495 static void __attribute__((__noreturn__))
    496 process_end_of_file(void)
    497 {
    498     if (lab.s != lab.e || code.s != code.e || com.s != com.e)
    499 	dump_line();
    500 
    501     if (ps.tos > 1)		/* check for balanced braces */
    502 	diag(1, "Stuff missing from end of file");
    503 
    504     if (opt.verbose) {
    505 	printf("There were %d output lines and %d comments\n",
    506 	    ps.stats.lines, ps.stats.comments);
    507 	printf("(Lines with comments)/(Lines with code): %6.3f\n",
    508 	    (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
    509     }
    510 
    511     fflush(output);
    512     exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
    513 }
    514 
    515 static void
    516 process_comment_in_code(token_type ttype, bool *inout_force_nl)
    517 {
    518     if (*inout_force_nl &&
    519 	ttype != semicolon &&
    520 	(ttype != lbrace || !opt.btype_2)) {
    521 
    522 	/* we should force a broken line here */
    523 	if (opt.verbose)
    524 	    diag(0, "Line broken");
    525 	dump_line();
    526 	ps.want_blank = false;	/* dont insert blank at line start */
    527 	*inout_force_nl = false;
    528     }
    529 
    530     ps.in_stmt = true;		/* turn on flag which causes an extra level of
    531 				 * indentation. this is turned off by a ';' or
    532 				 * '}' */
    533     if (com.s != com.e) {	/* the turkey has embedded a comment in a
    534 				 * line. fix it */
    535 	size_t len = com.e - com.s;
    536 
    537 	check_size_code(len + 3);
    538 	*code.e++ = ' ';
    539 	memcpy(code.e, com.s, len);
    540 	code.e += len;
    541 	*code.e++ = ' ';
    542 	*code.e = '\0';
    543 	ps.want_blank = false;
    544 	com.e = com.s;
    545     }
    546 }
    547 
    548 static void
    549 process_form_feed(void)
    550 {
    551     ps.use_ff = true;		/* a form feed is treated much like a newline */
    552     dump_line();
    553     ps.want_blank = false;
    554 }
    555 
    556 static void
    557 process_newline(void)
    558 {
    559     if (ps.last_token != comma || ps.p_l_follow > 0
    560 	|| !opt.leave_comma || ps.block_init || !break_comma || com.s != com.e) {
    561 	dump_line();
    562 	ps.want_blank = false;
    563     }
    564     ++line_no;			/* keep track of input line number */
    565 }
    566 
    567 static void
    568 process_lparen_or_lbracket(int dec_ind, bool tabs_to_var, bool sp_sw)
    569 {
    570     /* count parens to make Healy happy */
    571     if (++ps.p_l_follow == nitems(ps.paren_indents)) {
    572 	diag(0, "Reached internal limit of %zu unclosed parens",
    573 	    nitems(ps.paren_indents));
    574 	ps.p_l_follow--;
    575     }
    576     if (*token.s == '[')
    577 	/* not a function pointer declaration or a function call */;
    578     else if (ps.in_decl && !ps.block_init && !ps.dumped_decl_indent &&
    579 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    580 	/* function pointer declarations */
    581 	indent_declaration(dec_ind, tabs_to_var);
    582 	ps.dumped_decl_indent = true;
    583     } else if (ps.want_blank &&
    584 	    ((ps.last_token != ident && ps.last_token != funcname) ||
    585 	    opt.proc_calls_space ||
    586 	    (ps.keyword == rw_sizeof ? opt.blank_after_sizeof :
    587 	    ps.keyword != rw_0 && ps.keyword != rw_offsetof)))
    588 	*code.e++ = ' ';
    589     ps.want_blank = false;
    590     *code.e++ = token.s[0];
    591 
    592     ps.paren_indents[ps.p_l_follow - 1] =
    593 	indentation_after_range(0, code.s, code.e);
    594     debug_println("paren_indent[%d] is now %d",
    595 	ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
    596 
    597     if (sp_sw && ps.p_l_follow == 1 && opt.extra_expression_indent
    598 	    && ps.paren_indents[0] < 2 * opt.indent_size) {
    599 	ps.paren_indents[0] = 2 * opt.indent_size;
    600 	debug_println("paren_indent[0] is now %d", ps.paren_indents[0]);
    601     }
    602     if (ps.in_or_st && *token.s == '(' && ps.tos <= 2) {
    603 	/*
    604 	 * this is a kluge to make sure that declarations will be aligned
    605 	 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
    606 	 */
    607 	parse(semicolon);	/* I said this was a kluge... */
    608 	ps.in_or_st = false;	/* turn off flag for structure decl or
    609 				 * initialization */
    610     }
    611     /* parenthesized type following sizeof or offsetof is not a cast */
    612     if (ps.keyword == rw_offsetof || ps.keyword == rw_sizeof)
    613 	ps.not_cast_mask |= 1 << ps.p_l_follow;
    614 }
    615 
    616 static void
    617 process_rparen_or_rbracket(bool *inout_sp_sw, bool *inout_force_nl,
    618     token_type hd_type)
    619 {
    620     if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
    621 	ps.last_u_d = true;
    622 	ps.cast_mask &= (1 << ps.p_l_follow) - 1;
    623 	ps.want_blank = opt.space_after_cast;
    624     } else
    625 	ps.want_blank = true;
    626     ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
    627 
    628     if (--ps.p_l_follow < 0) {
    629 	ps.p_l_follow = 0;
    630 	diag(0, "Extra %c", *token.s);
    631     }
    632 
    633     if (code.e == code.s)	/* if the paren starts the line */
    634 	ps.paren_level = ps.p_l_follow;	/* then indent it */
    635 
    636     *code.e++ = token.s[0];
    637 
    638     if (*inout_sp_sw && (ps.p_l_follow == 0)) {	/* check for end of if (...),
    639 						 * or some such */
    640 	*inout_sp_sw = false;
    641 	*inout_force_nl = true;	/* must force newline after if */
    642 	ps.last_u_d = true;	/* inform lexi that a following operator is
    643 				 * unary */
    644 	ps.in_stmt = false;	/* dont use stmt continuation indentation */
    645 
    646 	parse(hd_type);		/* let parser worry about if, or whatever */
    647     }
    648     ps.search_brace = opt.btype_2;	/* this should ensure that constructs
    649 					 * such as main(){...} and int[]{...}
    650 					 * have their braces put in the right
    651 					 * place */
    652 }
    653 
    654 static void
    655 process_unary_op(int dec_ind, bool tabs_to_var)
    656 {
    657     if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
    658 	ps.procname[0] == '\0' && ps.paren_level == 0) {
    659 	/* pointer declarations */
    660 	indent_declaration(dec_ind - (int)strlen(token.s), tabs_to_var);
    661 	ps.dumped_decl_indent = true;
    662     } else if (ps.want_blank)
    663 	*code.e++ = ' ';
    664 
    665     {
    666 	size_t len = token.e - token.s;
    667 
    668 	check_size_code(len);
    669 	memcpy(code.e, token.s, len);
    670 	code.e += len;
    671     }
    672     ps.want_blank = false;
    673 }
    674 
    675 static void
    676 process_binary_op(void)
    677 {
    678     size_t len = token.e - token.s;
    679 
    680     check_size_code(len + 1);
    681     if (ps.want_blank)
    682 	*code.e++ = ' ';
    683     memcpy(code.e, token.s, len);
    684     code.e += len;
    685 
    686     ps.want_blank = true;
    687 }
    688 
    689 static void
    690 process_postfix_op(void)
    691 {
    692     *code.e++ = token.s[0];
    693     *code.e++ = token.s[1];
    694     ps.want_blank = true;
    695 }
    696 
    697 static void
    698 process_question(int *inout_squest)
    699 {
    700     (*inout_squest)++;		/* this will be used when a later colon
    701 				 * appears so we can distinguish the
    702 				 * <c>?<n>:<n> construct */
    703     if (ps.want_blank)
    704 	*code.e++ = ' ';
    705     *code.e++ = '?';
    706     ps.want_blank = true;
    707 }
    708 
    709 static void
    710 process_colon(int *inout_squest, bool *inout_force_nl, bool *inout_scase)
    711 {
    712     if (*inout_squest > 0) {	/* it is part of the <c>?<n>: <n> construct */
    713 	--*inout_squest;
    714 	if (ps.want_blank)
    715 	    *code.e++ = ' ';
    716 	*code.e++ = ':';
    717 	ps.want_blank = true;
    718 	return;
    719     }
    720     if (ps.in_or_st) {
    721 	*code.e++ = ':';
    722 	ps.want_blank = false;
    723 	return;
    724     }
    725     ps.in_stmt = false;		/* seeing a label does not imply we are in a
    726 				 * stmt */
    727     /*
    728      * turn everything so far into a label
    729      */
    730     {
    731 	size_t len = code.e - code.s;
    732 
    733 	check_size_label(len + 3);
    734 	memcpy(lab.e, code.s, len);
    735 	lab.e += len;
    736 	*lab.e++ = ':';
    737 	*lab.e = '\0';
    738 	code.e = code.s;
    739     }
    740     *inout_force_nl = ps.pcase = *inout_scase;	/* ps.pcase will be used by
    741 						 * dump_line to decide how to
    742 						 * indent the label. force_nl
    743 						 * will force a case n: to be
    744 						 * on a line by itself */
    745     *inout_scase = false;
    746     ps.want_blank = false;
    747 }
    748 
    749 static void
    750 process_semicolon(bool *inout_scase, int *inout_squest, int dec_ind,
    751     bool tabs_to_var, bool *inout_sp_sw,
    752     token_type hd_type,
    753     bool *inout_force_nl)
    754 {
    755     if (ps.decl_nest == 0)
    756 	ps.in_or_st = false;	/* we are not in an initialization or
    757 				 * structure declaration */
    758     *inout_scase = false;	/* these will only need resetting in an error */
    759     *inout_squest = 0;
    760     if (ps.last_token == rparen)
    761 	ps.in_parameter_declaration = false;
    762     ps.cast_mask = 0;
    763     ps.not_cast_mask = 0;
    764     ps.block_init = false;
    765     ps.block_init_level = 0;
    766     ps.just_saw_decl--;
    767 
    768     if (ps.in_decl && code.s == code.e && !ps.block_init &&
    769 	!ps.dumped_decl_indent && ps.paren_level == 0) {
    770 	/* indent stray semicolons in declarations */
    771 	indent_declaration(dec_ind - 1, tabs_to_var);
    772 	ps.dumped_decl_indent = true;
    773     }
    774 
    775     ps.in_decl = (ps.decl_nest > 0);	/* if we were in a first level
    776 					 * structure declaration, we arent any
    777 					 * more */
    778 
    779     if ((!*inout_sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
    780 
    781 	/*
    782 	 * This should be true iff there were unbalanced parens in the stmt.
    783 	 * It is a bit complicated, because the semicolon might be in a for
    784 	 * stmt
    785 	 */
    786 	diag(1, "Unbalanced parens");
    787 	ps.p_l_follow = 0;
    788 	if (*inout_sp_sw) {	/* this is a check for an if, while, etc. with
    789 				 * unbalanced parens */
    790 	    *inout_sp_sw = false;
    791 	    parse(hd_type);	/* dont lose the if, or whatever */
    792 	}
    793     }
    794     *code.e++ = ';';
    795     ps.want_blank = true;
    796     ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in the middle of a
    797 					 * stmt */
    798 
    799     if (!*inout_sp_sw) {	/* if not if for (;;) */
    800 	parse(semicolon);	/* let parser know about end of stmt */
    801 	*inout_force_nl = true;	/* force newline after an end of stmt */
    802     }
    803 }
    804 
    805 static void
    806 process_lbrace(bool *inout_force_nl, bool *inout_sp_sw, token_type hd_type,
    807     int *di_stack, int di_stack_cap, int *inout_dec_ind)
    808 {
    809     ps.in_stmt = false;		/* dont indent the {} */
    810     if (!ps.block_init)
    811 	*inout_force_nl = true;	/* force other stuff on same line as '{' onto
    812 				 * new line */
    813     else if (ps.block_init_level <= 0)
    814 	ps.block_init_level = 1;
    815     else
    816 	ps.block_init_level++;
    817 
    818     if (code.s != code.e && !ps.block_init) {
    819 	if (!opt.btype_2) {
    820 	    dump_line();
    821 	    ps.want_blank = false;
    822 	} else if (ps.in_parameter_declaration && !ps.in_or_st) {
    823 	    ps.ind_level_follow = 0;
    824 	    if (opt.function_brace_split) {	/* dump the line prior to the
    825 						 * brace ... */
    826 		dump_line();
    827 		ps.want_blank = false;
    828 	    } else		/* add a space between the decl and brace */
    829 		ps.want_blank = true;
    830 	}
    831     }
    832     if (ps.in_parameter_declaration)
    833 	prefix_blankline_requested = false;
    834 
    835     if (ps.p_l_follow > 0) {	/* check for preceding unbalanced parens */
    836 	diag(1, "Unbalanced parens");
    837 	ps.p_l_follow = 0;
    838 	if (*inout_sp_sw) {	/* check for unclosed if, for, etc. */
    839 	    *inout_sp_sw = false;
    840 	    parse(hd_type);
    841 	    ps.ind_level = ps.ind_level_follow;
    842 	}
    843     }
    844     if (code.s == code.e)
    845 	ps.ind_stmt = false;	/* dont put extra indentation on line
    846 				 * with '{' */
    847     if (ps.in_decl && ps.in_or_st) {	/* this is either a structure
    848 					 * declaration or an init */
    849 	di_stack[ps.decl_nest] = *inout_dec_ind;
    850 	if (++ps.decl_nest == di_stack_cap) {
    851 	    diag(0, "Reached internal limit of %d struct levels",
    852 		di_stack_cap);
    853 	    ps.decl_nest--;
    854 	}
    855 	/* ?		dec_ind = 0; */
    856     } else {
    857 	ps.decl_on_line = false;	/* we can't be in the middle of a
    858 					 * declaration, so don't do special
    859 					 * indentation of comments */
    860 	if (opt.blanklines_after_declarations_at_proctop
    861 	    && ps.in_parameter_declaration)
    862 	    postfix_blankline_requested = true;
    863 	ps.in_parameter_declaration = false;
    864 	ps.in_decl = false;
    865     }
    866     *inout_dec_ind = 0;
    867     parse(lbrace);		/* let parser know about this */
    868     if (ps.want_blank)		/* put a blank before '{' if '{' is not at
    869 				 * start of line */
    870 	*code.e++ = ' ';
    871     ps.want_blank = false;
    872     *code.e++ = '{';
    873     ps.just_saw_decl = 0;
    874 }
    875 
    876 static void
    877 process_rbrace(bool *inout_sp_sw, int *inout_dec_ind, const int *di_stack)
    878 {
    879     if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
    880 							 * omitted in
    881 							 * declarations */
    882 	parse(semicolon);
    883     if (ps.p_l_follow != 0) {	/* check for unclosed if, for, else. */
    884 	diag(1, "Unbalanced parens");
    885 	ps.p_l_follow = 0;
    886 	*inout_sp_sw = false;
    887     }
    888     ps.just_saw_decl = 0;
    889     ps.block_init_level--;
    890     if (code.s != code.e && !ps.block_init) {	/* '}' must be first on line */
    891 	if (opt.verbose)
    892 	    diag(0, "Line broken");
    893 	dump_line();
    894     }
    895     *code.e++ = '}';
    896     ps.want_blank = true;
    897     ps.in_stmt = ps.ind_stmt = false;
    898     if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
    899 	*inout_dec_ind = di_stack[--ps.decl_nest];
    900 	if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
    901 	    ps.just_saw_decl = 2;
    902 	ps.in_decl = true;
    903     }
    904     prefix_blankline_requested = false;
    905     parse(rbrace);		/* let parser know about this */
    906     ps.search_brace = opt.cuddle_else
    907 	&& ps.p_stack[ps.tos] == if_expr_stmt
    908 	&& ps.il[ps.tos] >= ps.ind_level;
    909     if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
    910 	postfix_blankline_requested = true;
    911 }
    912 
    913 static void
    914 process_keyword_do_else(bool *inout_force_nl, bool *inout_last_else)
    915 {
    916     ps.in_stmt = false;
    917     if (*token.s == 'e') {
    918 	if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
    919 	    if (opt.verbose)
    920 		diag(0, "Line broken");
    921 	    dump_line();	/* make sure this starts a line */
    922 	    ps.want_blank = false;
    923 	}
    924 	*inout_force_nl = true;/* also, following stuff must go onto new line */
    925 	*inout_last_else = true;
    926 	parse(keyword_else);
    927     } else {
    928 	if (code.e != code.s) {	/* make sure this starts a line */
    929 	    if (opt.verbose)
    930 		diag(0, "Line broken");
    931 	    dump_line();
    932 	    ps.want_blank = false;
    933 	}
    934 	*inout_force_nl = true;/* also, following stuff must go onto new line */
    935 	*inout_last_else = false;
    936 	parse(keyword_do);
    937     }
    938 }
    939 
    940 static void
    941 process_decl(int *out_dec_ind, bool *out_tabs_to_var)
    942 {
    943     parse(decl);		/* let parser worry about indentation */
    944     if (ps.last_token == rparen && ps.tos <= 1) {
    945 	if (code.s != code.e) {
    946 	    dump_line();
    947 	    ps.want_blank = false;
    948 	}
    949     }
    950     if (ps.in_parameter_declaration && opt.indent_parameters &&
    951 	ps.decl_nest == 0) {
    952 	ps.ind_level = ps.ind_level_follow = 1;
    953 	ps.ind_stmt = false;
    954     }
    955     ps.in_or_st = true;		/* this might be a structure or initialization
    956 				 * declaration */
    957     ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
    958     if ( /* !ps.in_or_st && */ ps.decl_nest <= 0)
    959 	ps.just_saw_decl = 2;
    960     prefix_blankline_requested = false;
    961 
    962     int len = (int)strlen(token.s) + 1;
    963     int ind = ps.ind_level == 0 || ps.decl_nest > 0
    964 	    ? opt.decl_indent		/* global variable or local member */
    965 	    : opt.local_decl_indent;	/* local variable */
    966     *out_dec_ind = ind > 0 ? ind : len;
    967     *out_tabs_to_var = opt.use_tabs ? ind > 0 : false;
    968 }
    969 
    970 static void
    971 process_ident(token_type ttype, int dec_ind, bool tabs_to_var,
    972     bool *inout_sp_sw, bool *inout_force_nl, token_type hd_type)
    973 {
    974     if (ps.in_decl) {
    975 	if (ttype == funcname) {
    976 	    ps.in_decl = false;
    977 	    if (opt.procnames_start_line && code.s != code.e) {
    978 		*code.e = '\0';
    979 		dump_line();
    980 	    } else if (ps.want_blank) {
    981 		*code.e++ = ' ';
    982 	    }
    983 	    ps.want_blank = false;
    984 	} else if (!ps.block_init && !ps.dumped_decl_indent &&
    985 	    ps.paren_level == 0) {	/* if we are in a declaration, we must
    986 					 * indent identifier */
    987 	    indent_declaration(dec_ind, tabs_to_var);
    988 	    ps.dumped_decl_indent = true;
    989 	    ps.want_blank = false;
    990 	}
    991     } else if (*inout_sp_sw && ps.p_l_follow == 0) {
    992 	*inout_sp_sw = false;
    993 	*inout_force_nl = true;
    994 	ps.last_u_d = true;
    995 	ps.in_stmt = false;
    996 	parse(hd_type);
    997     }
    998 }
    999 
   1000 static void
   1001 copy_id(void)
   1002 {
   1003     size_t len = token.e - token.s;
   1004 
   1005     check_size_code(len + 1);
   1006     if (ps.want_blank)
   1007 	*code.e++ = ' ';
   1008     memcpy(code.e, token.s, len);
   1009     code.e += len;
   1010 }
   1011 
   1012 static void
   1013 process_string_prefix(void)
   1014 {
   1015     size_t len = token.e - token.s;
   1016 
   1017     check_size_code(len + 1);
   1018     if (ps.want_blank)
   1019 	*code.e++ = ' ';
   1020     memcpy(code.e, token.s, len);
   1021     code.e += len;
   1022 
   1023     ps.want_blank = false;
   1024 }
   1025 
   1026 static void
   1027 process_period(void)
   1028 {
   1029     if (code.e[-1] == ',')
   1030 	*code.e++ = ' ';
   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 if comma
   1039 					 * 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, we
   1124 					 * 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 comments */
   1129 		*sc_end++ = ' ';
   1130 		--line_no;
   1131 	    }
   1132 	    if (sc_end - save_com + com_end - com_start > sc_size)
   1133 		errx(1, "input too long");
   1134 	    memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
   1135 	    sc_end += com_end - com_start;
   1136 	    lab.e = lab.s + com_start;
   1137 	    while (lab.e > lab.s && (lab.e[-1] == ' ' || lab.e[-1] == '\t'))
   1138 		lab.e--;
   1139 	    bp_save = buf_ptr;	/* save current input buffer */
   1140 	    be_save = buf_end;
   1141 	    buf_ptr = save_com;	/* fix so that subsequent calls to lexi will
   1142 				 * take tokens out of save_com */
   1143 	    *sc_end++ = ' ';	/* add trailing blank, just in case */
   1144 	    buf_end = sc_end;
   1145 	    sc_end = NULL;
   1146 	    debug_println("switched buf_ptr to save_com");
   1147 	}
   1148 	check_size_label(1);
   1149 	*lab.e = '\0';		/* null terminate line */
   1150 	ps.pcase = false;
   1151     }
   1152 
   1153     if (strncmp(lab.s, "#if", 3) == 0) {	/* also ifdef, ifndef */
   1154 	if ((size_t)ifdef_level < nitems(state_stack)) {
   1155 	    match_state[ifdef_level].tos = -1;
   1156 	    state_stack[ifdef_level++] = ps;
   1157 	} else
   1158 	    diag(1, "#if stack overflow");
   1159     } else if (strncmp(lab.s, "#el", 3) == 0) {	/* else, elif */
   1160 	if (ifdef_level <= 0)
   1161 	    diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
   1162 	else {
   1163 	    match_state[ifdef_level - 1] = ps;
   1164 	    ps = state_stack[ifdef_level - 1];
   1165 	}
   1166     } else if (strncmp(lab.s, "#endif", 6) == 0) {
   1167 	if (ifdef_level <= 0)
   1168 	    diag(1, "Unmatched #endif");
   1169 	else
   1170 	    ifdef_level--;
   1171     } else {
   1172 	if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
   1173 	    strncmp(lab.s + 1, "error", 5) != 0 &&
   1174 	    strncmp(lab.s + 1, "line", 4) != 0 &&
   1175 	    strncmp(lab.s + 1, "undef", 5) != 0 &&
   1176 	    strncmp(lab.s + 1, "define", 6) != 0 &&
   1177 	    strncmp(lab.s + 1, "include", 7) != 0) {
   1178 	    diag(1, "Unrecognized cpp directive");
   1179 	    return;
   1180 	}
   1181     }
   1182     if (opt.blanklines_around_conditional_compilation) {
   1183 	postfix_blankline_requested = true;
   1184 	n_real_blanklines = 0;
   1185     } else {
   1186 	postfix_blankline_requested = false;
   1187 	prefix_blankline_requested = false;
   1188     }
   1189 
   1190     /*
   1191      * subsequent processing of the newline character will cause the line to
   1192      * be printed
   1193      */
   1194 }
   1195 
   1196 static void __attribute__((__noreturn__))
   1197 main_loop(void)
   1198 {
   1199     token_type ttype;
   1200     bool force_nl;		/* when true, code must be broken */
   1201     bool last_else = false;	/* true iff last keyword was an else */
   1202     int dec_ind;		/* current indentation for declarations */
   1203     int di_stack[20];		/* a stack of structure indentation levels */
   1204     bool tabs_to_var;		/* true if using tabs to indent to var name */
   1205     bool sp_sw;			/* when true, we are in the expression of
   1206 				 * if(...), while(...), etc. */
   1207     token_type hd_type = end_of_file;	/* used to store type of stmt for if
   1208 					 * (...), for (...), etc */
   1209     int squest;			/* when this is positive, we have seen a '?'
   1210 				 * without the matching ':' in a <c>?<s>:<s>
   1211 				 * construct */
   1212     bool scase;			/* set to true when we see a 'case', so we
   1213 				 * know what to do with the following colon */
   1214 
   1215     sp_sw = force_nl = false;
   1216     dec_ind = 0;
   1217     di_stack[ps.decl_nest = 0] = 0;
   1218     scase = false;
   1219     squest = 0;
   1220     tabs_to_var = false;
   1221 
   1222     for (;;) {			/* this is the main loop.  it will go until we
   1223 				 * reach eof */
   1224 	bool comment_buffered = false;
   1225 
   1226 	ttype = lexi(&ps);	/* Read the next token.  The actual characters
   1227 				 * read are stored in "token". */
   1228 
   1229 	/*
   1230 	 * The following code moves newlines and comments following an if (),
   1231 	 * while (), else, etc. up to the start of the following stmt to a
   1232 	 * buffer. This allows proper handling of both kinds of brace
   1233 	 * placement (-br, -bl) and cuddling "else" (-ce).
   1234 	 */
   1235 	search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
   1236 
   1237 	if (ttype == end_of_file) {
   1238 	    process_end_of_file();
   1239 	    /* NOTREACHED */
   1240 	}
   1241 
   1242 	if (
   1243 		ttype != comment &&
   1244 		ttype != newline &&
   1245 		ttype != preprocessing &&
   1246 		ttype != form_feed) {
   1247 	    process_comment_in_code(ttype, &force_nl);
   1248 
   1249 	} else if (ttype != comment)	/* preserve force_nl through a comment */
   1250 	    force_nl = false;	/* cancel forced newline after newline, form
   1251 				 * feed, etc */
   1252 
   1253 
   1254 
   1255 	/*-----------------------------------------------------*\
   1256 	|	   do switch on type of token scanned		|
   1257 	\*-----------------------------------------------------*/
   1258 	check_size_code(3);	/* maximum number of increments of code.e
   1259 				 * before the next check_size_code or
   1260 				 * dump_line() is 2. After that there's the
   1261 				 * final increment for the null character. */
   1262 	switch (ttype) {
   1263 
   1264 	case form_feed:
   1265 	    process_form_feed();
   1266 	    break;
   1267 
   1268 	case newline:
   1269 	    process_newline();
   1270 	    break;
   1271 
   1272 	case lparen:		/* got a '(' or '[' */
   1273 	    process_lparen_or_lbracket(dec_ind, tabs_to_var, sp_sw);
   1274 	    break;
   1275 
   1276 	case rparen:		/* got a ')' or ']' */
   1277 	    process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
   1278 	    break;
   1279 
   1280 	case unary_op:		/* this could be any unary operation */
   1281 	    process_unary_op(dec_ind, tabs_to_var);
   1282 	    break;
   1283 
   1284 	case binary_op:		/* any binary operation */
   1285 	    process_binary_op();
   1286 	    break;
   1287 
   1288 	case postfix_op:	/* got a trailing ++ or -- */
   1289 	    process_postfix_op();
   1290 	    break;
   1291 
   1292 	case question:		/* got a ? */
   1293 	    process_question(&squest);
   1294 	    break;
   1295 
   1296 	case case_label:	/* got word 'case' or 'default' */
   1297 	    scase = true;	/* so we can process the later colon properly */
   1298 	    goto copy_id;
   1299 
   1300 	case colon:		/* got a ':' */
   1301 	    process_colon(&squest, &force_nl, &scase);
   1302 	    break;
   1303 
   1304 	case semicolon:		/* got a ';' */
   1305 	    process_semicolon(&scase, &squest, dec_ind, tabs_to_var, &sp_sw,
   1306 		hd_type, &force_nl);
   1307 	    break;
   1308 
   1309 	case lbrace:		/* got a '{' */
   1310 	    process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
   1311 		(int)nitems(di_stack), &dec_ind);
   1312 	    break;
   1313 
   1314 	case rbrace:		/* got a '}' */
   1315 	    process_rbrace(&sp_sw, &dec_ind, di_stack);
   1316 	    break;
   1317 
   1318 	case switch_expr:	/* got keyword "switch" */
   1319 	    sp_sw = true;
   1320 	    hd_type = switch_expr;	/* keep this for when we have seen the
   1321 					 * expression */
   1322 	    goto copy_id;	/* go move the token into buffer */
   1323 
   1324 	case keyword_for_if_while:
   1325 	    sp_sw = true;	/* the interesting stuff is done after the
   1326 				 * expression is scanned */
   1327 	    hd_type = (*token.s == 'i' ? if_expr :
   1328 		(*token.s == 'w' ? while_expr : for_exprs));
   1329 
   1330 	    /* remember the type of header for later use by parser */
   1331 	    goto copy_id;	/* copy the token into line */
   1332 
   1333 	case keyword_do_else:
   1334 	    process_keyword_do_else(&force_nl, &last_else);
   1335 	    goto copy_id;	/* move the token into line */
   1336 
   1337 	case type_def:
   1338 	case storage_class:
   1339 	    prefix_blankline_requested = false;
   1340 	    goto copy_id;
   1341 
   1342 	case keyword_struct_union_enum:
   1343 	    if (ps.p_l_follow > 0)
   1344 		goto copy_id;
   1345 	    /* FALLTHROUGH */
   1346 	case decl:		/* we have a declaration type (int, etc.) */
   1347 	    process_decl(&dec_ind, &tabs_to_var);
   1348 	    goto copy_id;
   1349 
   1350 	case funcname:
   1351 	case ident:		/* got an identifier or constant */
   1352 	    process_ident(ttype, dec_ind, tabs_to_var, &sp_sw, &force_nl,
   1353 		hd_type);
   1354     copy_id:
   1355 	    copy_id();
   1356 	    if (ttype != funcname)
   1357 		ps.want_blank = true;
   1358 	    break;
   1359 
   1360 	case string_prefix:
   1361 	    process_string_prefix();
   1362 	    break;
   1363 
   1364 	case period:
   1365 	    process_period();
   1366 	    break;
   1367 
   1368 	case comma:
   1369 	    process_comma(dec_ind, tabs_to_var, &force_nl);
   1370 	    break;
   1371 
   1372 	case preprocessing:	/* '#' */
   1373 	    process_preprocessing();
   1374 	    break;
   1375 	case comment:		/* the initial '/' '*' or '//' of a comment */
   1376 	    process_comment();
   1377 	    break;
   1378 
   1379 	default:
   1380 	    break;
   1381 	}
   1382 
   1383 	*code.e = '\0';
   1384 	if (ttype != comment &&
   1385 	    ttype != newline &&
   1386 	    ttype != preprocessing)
   1387 	    ps.last_token = ttype;
   1388     }
   1389 }
   1390 
   1391 int
   1392 main(int argc, char **argv)
   1393 {
   1394     main_init_globals();
   1395     main_parse_command_line(argc, argv);
   1396 #if HAVE_CAPSICUM
   1397     init_capsicum();
   1398 #endif
   1399     main_prepare_parsing();
   1400     main_loop();
   1401 }
   1402 
   1403 /*
   1404  * copy input file to backup file if in_name is /blah/blah/blah/file, then
   1405  * backup file will be ".Bfile" then make the backup file the input and
   1406  * original input file the output
   1407  */
   1408 static void
   1409 bakcopy(void)
   1410 {
   1411     ssize_t n;
   1412     int bakchn;
   1413     char buff[8 * 1024];
   1414     const char *p;
   1415 
   1416     /* construct file name .Bfile */
   1417     for (p = in_name; *p != '\0'; p++);	/* skip to end of string */
   1418     while (p > in_name && *p != '/')	/* find last '/' */
   1419 	p--;
   1420     if (*p == '/')
   1421 	p++;
   1422     sprintf(bakfile, "%s%s", p, simple_backup_suffix);
   1423 
   1424     /* copy in_name to backup file */
   1425     bakchn = creat(bakfile, 0600);
   1426     if (bakchn < 0)
   1427 	err(1, "%s", bakfile);
   1428     while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
   1429 	if (write(bakchn, buff, (size_t)n) != n)
   1430 	    err(1, "%s", bakfile);
   1431     if (n < 0)
   1432 	err(1, "%s", in_name);
   1433     close(bakchn);
   1434     fclose(input);
   1435 
   1436     /* re-open backup file as the input file */
   1437     input = fopen(bakfile, "r");
   1438     if (input == NULL)
   1439 	err(1, "%s", bakfile);
   1440     /* now the original input file will be the output */
   1441     output = fopen(in_name, "w");
   1442     if (output == NULL) {
   1443 	unlink(bakfile);
   1444 	err(1, "%s", in_name);
   1445     }
   1446 }
   1447 
   1448 static void
   1449 indent_declaration(int cur_dec_ind, bool tabs_to_var)
   1450 {
   1451     int pos = (int)(code.e - code.s);
   1452     char *startpos = code.e;
   1453 
   1454     /*
   1455      * get the tab math right for indentations that are not multiples of
   1456      * 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