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