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