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