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