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