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