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