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