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