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