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