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