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