Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.335
      1 /*	$NetBSD: indent.c,v 1.335 2023/06/05 12:05:01 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 #include <sys/cdefs.h>
     41 __RCSID("$NetBSD: indent.c,v 1.335 2023/06/05 12:05:01 rillig Exp $");
     42 
     43 #include <sys/param.h>
     44 #include <err.h>
     45 #include <fcntl.h>
     46 #include <stdarg.h>
     47 #include <stdio.h>
     48 #include <stdlib.h>
     49 #include <string.h>
     50 #include <unistd.h>
     51 
     52 #include "indent.h"
     53 
     54 struct options opt = {
     55 	.brace_same_line = true,
     56 	.comment_delimiter_on_blankline = true,
     57 	.cuddle_else = true,
     58 	.comment_column = 33,
     59 	.decl_indent = 16,
     60 	.else_if_in_same_line = true,
     61 	.function_brace_split = true,
     62 	.format_col1_comments = true,
     63 	.format_block_comments = true,
     64 	.indent_parameters = true,
     65 	.indent_size = 8,
     66 	.local_decl_indent = -1,
     67 	.lineup_to_parens = true,
     68 	.procnames_start_line = true,
     69 	.star_comment_cont = true,
     70 	.tabsize = 8,
     71 	.max_line_length = 78,
     72 	.use_tabs = true,
     73 };
     74 
     75 struct parser_state ps;
     76 
     77 struct buffer token;
     78 
     79 struct buffer lab;
     80 struct buffer code;
     81 struct buffer com;
     82 
     83 bool found_err;
     84 float case_ind;
     85 bool had_eof;
     86 int line_no = 1;
     87 enum indent_enabled indent_enabled;
     88 
     89 static int ifdef_level;
     90 static struct parser_state state_stack[5];
     91 
     92 FILE *input;
     93 FILE *output;
     94 
     95 static const char *in_name = "Standard Input";
     96 static const char *out_name = "Standard Output";
     97 static const char *backup_suffix = ".BAK";
     98 static char bakfile[MAXPATHLEN] = "";
     99 
    100 
    101 void *
    102 nonnull(void *p)
    103 {
    104 	if (p == NULL)
    105 		err(EXIT_FAILURE, NULL);
    106 	return p;
    107 }
    108 
    109 static void
    110 buf_expand(struct buffer *buf, size_t add_size)
    111 {
    112 	buf->cap = buf->cap + add_size + 400;
    113 	buf->s = nonnull(realloc(buf->s, buf->cap));
    114 }
    115 
    116 void
    117 buf_add_char(struct buffer *buf, char ch)
    118 {
    119 	if (buf->len == buf->cap)
    120 		buf_expand(buf, 1);
    121 	buf->s[buf->len++] = ch;
    122 }
    123 
    124 void
    125 buf_add_chars(struct buffer *buf, const char *s, size_t len)
    126 {
    127 	if (len == 0)
    128 		return;
    129 	if (len > buf->cap - buf->len)
    130 		buf_expand(buf, len);
    131 	memcpy(buf->s + buf->len, s, len);
    132 	buf->len += len;
    133 }
    134 
    135 static void
    136 buf_add_buf(struct buffer *buf, const struct buffer *add)
    137 {
    138 	buf_add_chars(buf, add->s, add->len);
    139 }
    140 
    141 void
    142 diag(int level, const char *msg, ...)
    143 {
    144 	va_list ap;
    145 
    146 	if (level != 0)
    147 		found_err = true;
    148 
    149 	va_start(ap, msg);
    150 	fprintf(stderr, "%s: %s:%d: ",
    151 	    level == 0 ? "warning" : "error", in_name, line_no);
    152 	vfprintf(stderr, msg, ap);
    153 	fprintf(stderr, "\n");
    154 	va_end(ap);
    155 }
    156 
    157 /*
    158  * Compute the indentation from starting at 'ind' and adding the text starting
    159  * at 's'.
    160  */
    161 int
    162 ind_add(int ind, const char *s, size_t len)
    163 {
    164 	for (const char *p = s; len > 0; p++, len--) {
    165 		if (*p == '\n')
    166 			ind = 0;
    167 		else if (*p == '\t')
    168 			ind = next_tab(ind);
    169 		else if (*p == '\b')
    170 			--ind;
    171 		else
    172 			++ind;
    173 	}
    174 	return ind;
    175 }
    176 
    177 static void
    178 init_globals(void)
    179 {
    180 	ps.s_sym[0] = psym_stmt_list;
    181 	ps.prev_lsym = lsym_semicolon;
    182 	ps.next_col_1 = true;
    183 	ps.lbrace_kind = psym_lbrace_block;
    184 
    185 	const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
    186 	if (suffix != NULL)
    187 		backup_suffix = suffix;
    188 }
    189 
    190 /*
    191  * Copy the input file to the backup file, then make the backup file the input
    192  * and the original input file the output.
    193  */
    194 static void
    195 bakcopy(void)
    196 {
    197 	ssize_t n;
    198 	int bak_fd;
    199 	char buff[8 * 1024];
    200 
    201 	const char *last_slash = strrchr(in_name, '/');
    202 	snprintf(bakfile, sizeof(bakfile), "%s%s",
    203 	    last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
    204 
    205 	/* copy in_name to backup file */
    206 	bak_fd = creat(bakfile, 0600);
    207 	if (bak_fd < 0)
    208 		err(1, "%s", bakfile);
    209 
    210 	while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
    211 		if (write(bak_fd, buff, (size_t)n) != n)
    212 			err(1, "%s", bakfile);
    213 	if (n < 0)
    214 		err(1, "%s", in_name);
    215 
    216 	close(bak_fd);
    217 	(void)fclose(input);
    218 
    219 	/* re-open backup file as the input file */
    220 	input = fopen(bakfile, "r");
    221 	if (input == NULL)
    222 		err(1, "%s", bakfile);
    223 	/* now the original input file will be the output */
    224 	output = fopen(in_name, "w");
    225 	if (output == NULL) {
    226 		unlink(bakfile);
    227 		err(1, "%s", in_name);
    228 	}
    229 }
    230 
    231 static void
    232 load_profiles(int argc, char **argv)
    233 {
    234 	const char *profile_name = NULL;
    235 
    236 	for (int i = 1; i < argc; ++i) {
    237 		const char *arg = argv[i];
    238 
    239 		if (strcmp(arg, "-npro") == 0)
    240 			return;
    241 		if (arg[0] == '-' && arg[1] == 'P' && arg[2] != '\0')
    242 			profile_name = arg + 2;
    243 	}
    244 
    245 	load_profile_files(profile_name);
    246 }
    247 
    248 static void
    249 parse_command_line(int argc, char **argv)
    250 {
    251 	for (int i = 1; i < argc; ++i) {
    252 		const char *arg = argv[i];
    253 
    254 		if (arg[0] == '-') {
    255 			set_option(arg, "Command line");
    256 
    257 		} else if (input == NULL) {
    258 			in_name = arg;
    259 			if ((input = fopen(in_name, "r")) == NULL)
    260 				err(1, "%s", in_name);
    261 
    262 		} else if (output == NULL) {
    263 			out_name = arg;
    264 			if (strcmp(in_name, out_name) == 0)
    265 				errx(1, "input and output files "
    266 				    "must be different");
    267 			if ((output = fopen(out_name, "w")) == NULL)
    268 				err(1, "%s", out_name);
    269 
    270 		} else
    271 			errx(1, "too many arguments: %s", arg);
    272 	}
    273 
    274 	if (input == NULL) {
    275 		input = stdin;
    276 		output = stdout;
    277 	} else if (output == NULL) {
    278 		out_name = in_name;
    279 		bakcopy();
    280 	}
    281 
    282 	if (opt.comment_column <= 1)
    283 		opt.comment_column = 2;	/* don't put normal comments in column
    284 					 * 1, see opt.format_col1_comments */
    285 	if (opt.block_comment_max_line_length <= 0)
    286 		opt.block_comment_max_line_length = opt.max_line_length;
    287 	if (opt.local_decl_indent < 0)
    288 		opt.local_decl_indent = opt.decl_indent;
    289 	if (opt.decl_comment_column <= 0)
    290 		opt.decl_comment_column = opt.left_justify_decl
    291 		    ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
    292 		    : opt.comment_column;
    293 	if (opt.continuation_indent == 0)
    294 		opt.continuation_indent = opt.indent_size;
    295 }
    296 
    297 static void
    298 set_initial_indentation(void)
    299 {
    300 	inp_read_line();
    301 
    302 	int ind = 0;
    303 	for (const char *p = inp_p;; p++) {
    304 		if (*p == ' ')
    305 			ind++;
    306 		else if (*p == '\t')
    307 			ind = next_tab(ind);
    308 		else
    309 			break;
    310 	}
    311 
    312 	ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
    313 }
    314 
    315 static void
    316 code_add_decl_indent(int decl_ind, bool tabs_to_var)
    317 {
    318 	int base = ps.ind_level * opt.indent_size;
    319 	int ind = base + (int)code.len;
    320 	int target = base + decl_ind;
    321 	size_t orig_code_len = code.len;
    322 
    323 	if (tabs_to_var)
    324 		for (int next; (next = next_tab(ind)) <= target; ind = next)
    325 			buf_add_char(&code, '\t');
    326 
    327 	for (; ind < target; ind++)
    328 		buf_add_char(&code, ' ');
    329 
    330 	if (code.len == orig_code_len && ps.want_blank) {
    331 		buf_add_char(&code, ' ');
    332 		ps.want_blank = false;
    333 	}
    334 }
    335 
    336 static void
    337 update_ps_decl_ptr(lexer_symbol lsym)
    338 {
    339 	if (lsym == lsym_semicolon
    340 	    || lsym == lsym_lbrace
    341 	    || lsym == lsym_rbrace
    342 	    || (lsym == lsym_lparen && ps.prev_lsym != lsym_sizeof)
    343 	    || (lsym == lsym_comma && ps.in_decl)
    344 	    || lsym == lsym_modifier)
    345 		ps.decl_ptr = dp_start;
    346 	else if (ps.decl_ptr == dp_start && lsym == lsym_word)
    347 		ps.decl_ptr = dp_word;
    348 	else if ((ps.decl_ptr == dp_word || ps.decl_ptr == dp_word_asterisk)
    349 	    && (lsym == lsym_unary_op && token.s[0] == '*'))
    350 		ps.decl_ptr = dp_word_asterisk;
    351 	else
    352 		ps.decl_ptr = dp_other;
    353 }
    354 
    355 static void
    356 update_ps_prev_tag(lexer_symbol lsym)
    357 {
    358 	if (lsym == lsym_tag) {
    359 		ps.lbrace_kind = token.s[0] == 's' ? psym_lbrace_struct :
    360 		    token.s[0] == 'u' ? psym_lbrace_union :
    361 		    psym_lbrace_enum;
    362 	} else if (lsym != lsym_type_outside_parentheses
    363 	    && lsym != lsym_word
    364 	    && lsym != lsym_lbrace)
    365 		ps.lbrace_kind = psym_lbrace_block;
    366 }
    367 
    368 static int
    369 process_eof(void)
    370 {
    371 	if (lab.len > 0 || code.len > 0 || com.len > 0)
    372 		output_line();
    373 	if (indent_enabled != indent_on) {
    374 		indent_enabled = indent_last_off_line;
    375 		output_line();
    376 	}
    377 
    378 	if (ps.tos > 1)		/* check for balanced braces */
    379 		diag(1, "Stuff missing from end of file");
    380 
    381 	fflush(output);
    382 	return found_err ? EXIT_FAILURE : EXIT_SUCCESS;
    383 }
    384 
    385 static void
    386 maybe_break_line(lexer_symbol lsym)
    387 {
    388 	if (!ps.force_nl)
    389 		return;
    390 	if (lsym == lsym_semicolon)
    391 		return;
    392 	if (lsym == lsym_lbrace && opt.brace_same_line
    393 	    && ps.prev_lsym != lsym_lbrace)
    394 		return;
    395 
    396 	output_line();
    397 	ps.force_nl = false;
    398 }
    399 
    400 static void
    401 move_com_to_code(lexer_symbol lsym)
    402 {
    403 	if (ps.want_blank)
    404 		buf_add_char(&code, ' ');
    405 	buf_add_buf(&code, &com);
    406 	com.len = 0;
    407 	ps.want_blank = lsym != lsym_rparen && lsym != lsym_rbracket;
    408 }
    409 
    410 static void
    411 process_newline(void)
    412 {
    413 	if (ps.prev_lsym == lsym_comma
    414 	    && ps.nparen == 0 && !ps.block_init
    415 	    && !opt.break_after_comma && ps.break_after_comma
    416 	    && lab.len == 0	/* for preprocessing lines */
    417 	    && com.len == 0)
    418 		goto stay_in_line;
    419 	if (ps.s_sym[ps.tos] == psym_switch_expr && opt.brace_same_line) {
    420 		ps.force_nl = true;
    421 		goto stay_in_line;
    422 	}
    423 
    424 	output_line();
    425 
    426 stay_in_line:
    427 	++line_no;
    428 }
    429 
    430 static bool
    431 is_function_pointer_declaration(void)
    432 {
    433 	return ps.in_decl
    434 	    && !ps.block_init
    435 	    && !ps.decl_indent_done
    436 	    && !ps.is_function_definition
    437 	    && ps.line_start_nparen == 0;
    438 }
    439 
    440 static bool
    441 want_blank_before_lparen(void)
    442 {
    443 	if (!ps.want_blank)
    444 		return false;
    445 	if (opt.proc_calls_space)
    446 		return true;
    447 	if (ps.prev_lsym == lsym_rparen || ps.prev_lsym == lsym_rbracket)
    448 		return false;
    449 	if (ps.prev_lsym == lsym_offsetof)
    450 		return false;
    451 	if (ps.prev_lsym == lsym_sizeof)
    452 		return opt.blank_after_sizeof;
    453 	if (ps.prev_lsym == lsym_word || ps.prev_lsym == lsym_funcname)
    454 		return false;
    455 	return true;
    456 }
    457 
    458 static void
    459 process_lparen(void)
    460 {
    461 	if (++ps.nparen == array_length(ps.paren)) {
    462 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    463 		    array_length(ps.paren));
    464 		ps.nparen--;
    465 	}
    466 
    467 	if (is_function_pointer_declaration()) {
    468 		code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    469 		ps.decl_indent_done = true;
    470 	} else if (want_blank_before_lparen())
    471 		buf_add_char(&code, ' ');
    472 	ps.want_blank = false;
    473 	buf_add_char(&code, token.s[0]);
    474 
    475 	if (opt.extra_expr_indent && !opt.lineup_to_parens
    476 	    && ps.spaced_expr_psym != psym_0 && ps.nparen == 1
    477 	    && opt.continuation_indent == opt.indent_size)
    478 		ps.extra_expr_indent = eei_yes;
    479 
    480 	if (ps.init_or_struct && ps.tos <= 2) {
    481 		/* A kludge to correctly align function definitions. */
    482 		parse(psym_stmt);
    483 		ps.init_or_struct = false;
    484 	}
    485 
    486 	int indent = ind_add(0, code.s, code.len);
    487 	if (opt.extra_expr_indent && ps.spaced_expr_psym != psym_0
    488 	    && ps.nparen == 1 && indent < 2 * opt.indent_size)
    489 		indent = 2 * opt.indent_size;
    490 
    491 	enum paren_level_cast cast = cast_unknown;
    492 	if (ps.prev_lsym == lsym_offsetof || ps.prev_lsym == lsym_sizeof
    493 	    || ps.is_function_definition)
    494 		cast = cast_no;
    495 
    496 	ps.paren[ps.nparen - 1].indent = indent;
    497 	ps.paren[ps.nparen - 1].cast = cast;
    498 	debug_println("paren_indents[%d] is now %s%d",
    499 	    ps.nparen - 1, paren_level_cast_name[cast], indent);
    500 }
    501 
    502 static bool
    503 want_blank_before_lbracket(void)
    504 {
    505 	if (code.len == 0)
    506 		return false;
    507 	if (ps.prev_lsym == lsym_comma)
    508 		return true;
    509 	if (ps.prev_lsym == lsym_binary_op)
    510 		return true;
    511 	return false;
    512 }
    513 
    514 static void
    515 process_lbracket(void)
    516 {
    517 	if (++ps.nparen == array_length(ps.paren)) {
    518 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    519 		    array_length(ps.paren));
    520 		ps.nparen--;
    521 	}
    522 
    523 	if (want_blank_before_lbracket())
    524 		buf_add_char(&code, ' ');
    525 	ps.want_blank = false;
    526 	buf_add_char(&code, token.s[0]);
    527 
    528 	int indent = ind_add(0, code.s, code.len);
    529 
    530 	ps.paren[ps.nparen - 1].indent = indent;
    531 	ps.paren[ps.nparen - 1].cast = cast_no;
    532 	debug_println("paren_indents[%d] is now %d", ps.nparen - 1, indent);
    533 }
    534 
    535 static void
    536 process_rparen(void)
    537 {
    538 	if (ps.nparen == 0) {
    539 		diag(0, "Extra '%c'", *token.s);
    540 		goto unbalanced;
    541 	}
    542 
    543 	enum paren_level_cast cast = ps.paren[--ps.nparen].cast;
    544 	if (ps.decl_on_line && !ps.block_init)
    545 		cast = cast_no;
    546 
    547 	if (cast == cast_maybe) {
    548 		ps.next_unary = true;
    549 		ps.want_blank = opt.space_after_cast;
    550 	} else
    551 		ps.want_blank = true;
    552 
    553 	if (code.len == 0)
    554 		ps.line_start_nparen = ps.nparen;
    555 
    556 unbalanced:
    557 	buf_add_char(&code, token.s[0]);
    558 
    559 	if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    560 		if (ps.extra_expr_indent == eei_yes)
    561 			ps.extra_expr_indent = eei_last;
    562 		ps.force_nl = true;
    563 		ps.next_unary = true;
    564 		ps.in_stmt_or_decl = false;
    565 		parse(ps.spaced_expr_psym);
    566 		ps.spaced_expr_psym = psym_0;
    567 		ps.want_blank = true;
    568 		out.line_kind = lk_stmt_head;
    569 	}
    570 }
    571 
    572 static void
    573 process_rbracket(void)
    574 {
    575 	if (ps.nparen == 0) {
    576 		diag(0, "Extra '%c'", *token.s);
    577 		goto unbalanced;
    578 	}
    579 	--ps.nparen;
    580 
    581 	ps.want_blank = true;
    582 	if (code.len == 0)
    583 		ps.line_start_nparen = ps.nparen;
    584 
    585 unbalanced:
    586 	buf_add_char(&code, token.s[0]);
    587 }
    588 
    589 static bool
    590 want_blank_before_unary_op(void)
    591 {
    592 	if (ps.want_blank)
    593 		return true;
    594 	if (token.s[0] == '+' || token.s[0] == '-')
    595 		return code.len > 0 && code.s[code.len - 1] == token.s[0];
    596 	return false;
    597 }
    598 
    599 static void
    600 process_unary_op(void)
    601 {
    602 	if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
    603 	    !ps.is_function_definition && ps.line_start_nparen == 0) {
    604 		/* pointer declarations */
    605 		code_add_decl_indent(ps.decl_ind - (int)token.len,
    606 		    ps.tabs_to_var);
    607 		ps.decl_indent_done = true;
    608 	} else if (want_blank_before_unary_op())
    609 		buf_add_char(&code, ' ');
    610 
    611 	buf_add_buf(&code, &token);
    612 	ps.want_blank = false;
    613 }
    614 
    615 static void
    616 process_binary_op(void)
    617 {
    618 	if (code.len > 0 && ps.want_blank)
    619 		buf_add_char(&code, ' ');
    620 	buf_add_buf(&code, &token);
    621 	ps.want_blank = true;
    622 }
    623 
    624 static void
    625 process_postfix_op(void)
    626 {
    627 	buf_add_buf(&code, &token);
    628 	ps.want_blank = true;
    629 }
    630 
    631 static void
    632 process_question(void)
    633 {
    634 	ps.quest_level++;
    635 	if (code.len == 0) {
    636 		ps.in_stmt_cont = true;
    637 		ps.in_stmt_or_decl = true;
    638 		ps.in_decl = false;
    639 	}
    640 	if (ps.want_blank)
    641 		buf_add_char(&code, ' ');
    642 	buf_add_char(&code, '?');
    643 	ps.want_blank = true;
    644 }
    645 
    646 static void
    647 process_colon_question(void)
    648 {
    649 	if (code.len == 0) {
    650 		ps.in_stmt_cont = true;
    651 		ps.in_stmt_or_decl = true;
    652 		ps.in_decl = false;
    653 	}
    654 	if (ps.want_blank)
    655 		buf_add_char(&code, ' ');
    656 	buf_add_char(&code, ':');
    657 	ps.want_blank = true;
    658 }
    659 
    660 static void
    661 process_colon_label(void)
    662 {
    663 	buf_add_buf(&lab, &code);
    664 	buf_add_char(&lab, ':');
    665 	code.len = 0;
    666 
    667 	if (ps.seen_case)
    668 		out.line_kind = lk_case_or_default;
    669 	ps.in_stmt_or_decl = false;
    670 	ps.force_nl = ps.seen_case;
    671 	ps.seen_case = false;
    672 	ps.want_blank = false;
    673 }
    674 
    675 static void
    676 process_colon_other(void)
    677 {
    678 	buf_add_char(&code, ':');
    679 	ps.want_blank = false;
    680 }
    681 
    682 static void
    683 process_semicolon(void)
    684 {
    685 	if (out.line_kind == lk_stmt_head)
    686 		out.line_kind = lk_other;
    687 	if (ps.decl_level == 0)
    688 		ps.init_or_struct = false;
    689 	ps.seen_case = false;	/* only needs to be reset on error */
    690 	ps.quest_level = 0;	/* only needs to be reset on error */
    691 	if (ps.prev_lsym == lsym_rparen)
    692 		ps.in_func_def_params = false;
    693 	ps.block_init = false;
    694 	ps.block_init_level = 0;
    695 	ps.declaration = ps.declaration == decl_begin ? decl_end : decl_no;
    696 
    697 	if (ps.in_decl && code.len == 0 && !ps.block_init &&
    698 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    699 		/* indent stray semicolons in declarations */
    700 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    701 		ps.decl_indent_done = true;
    702 	}
    703 
    704 	ps.in_decl = ps.decl_level > 0;	/* if we were in a first level
    705 					 * structure declaration before, we
    706 					 * aren't anymore */
    707 
    708 	if (ps.nparen > 0 && ps.spaced_expr_psym != psym_for_exprs) {
    709 		/* There were unbalanced parentheses in the statement. It is a
    710 		 * bit complicated, because the semicolon might be in a for
    711 		 * statement. */
    712 		diag(1, "Unbalanced parentheses");
    713 		ps.nparen = 0;
    714 		if (ps.spaced_expr_psym != psym_0) {
    715 			parse(ps.spaced_expr_psym);
    716 			ps.spaced_expr_psym = psym_0;
    717 		}
    718 	}
    719 	buf_add_char(&code, ';');
    720 	ps.want_blank = true;
    721 	ps.in_stmt_or_decl = ps.nparen > 0;
    722 	ps.decl_ind = 0;
    723 
    724 	if (ps.spaced_expr_psym == psym_0) {
    725 		parse(psym_stmt);
    726 		ps.force_nl = true;
    727 	}
    728 }
    729 
    730 static void
    731 process_lbrace(void)
    732 {
    733 	parser_symbol psym = ps.s_sym[ps.tos];
    734 	if (ps.prev_lsym == lsym_rparen
    735 	    && ps.tos >= 2
    736 	    && !(psym == psym_for_exprs || psym == psym_if_expr
    737 		    || psym == psym_switch_expr || psym == psym_while_expr)) {
    738 		ps.block_init = true;
    739 		ps.init_or_struct = true;
    740 	}
    741 
    742 	if (out.line_kind == lk_stmt_head)
    743 		out.line_kind = lk_other;
    744 
    745 	ps.in_stmt_or_decl = false;	/* don't indent the {} */
    746 
    747 	if (!ps.block_init)
    748 		ps.force_nl = true;
    749 	else
    750 		ps.block_init_level++;
    751 
    752 	if (code.len > 0 && !ps.block_init) {
    753 		if (!opt.brace_same_line ||
    754 		    (code.len > 0 && code.s[code.len - 1] == '}'))
    755 			output_line();
    756 		else if (ps.in_func_def_params && !ps.init_or_struct) {
    757 			ps.ind_level_follow = 0;
    758 			if (opt.function_brace_split)
    759 				output_line();
    760 			else
    761 				ps.want_blank = true;
    762 		}
    763 	}
    764 
    765 	if (ps.nparen > 0) {
    766 		diag(1, "Unbalanced parentheses");
    767 		ps.nparen = 0;
    768 		if (ps.spaced_expr_psym != psym_0) {
    769 			parse(ps.spaced_expr_psym);
    770 			ps.spaced_expr_psym = psym_0;
    771 			ps.ind_level = ps.ind_level_follow;
    772 		}
    773 	}
    774 
    775 	if (code.len == 0)
    776 		ps.in_stmt_cont = false;	/* don't indent the '{' itself
    777 						 */
    778 	if (ps.in_decl && ps.init_or_struct) {
    779 		ps.di_stack[ps.decl_level] = ps.decl_ind;
    780 		if (++ps.decl_level == (int)array_length(ps.di_stack)) {
    781 			diag(0, "Reached internal limit of %d struct levels",
    782 			    (int)array_length(ps.di_stack));
    783 			ps.decl_level--;
    784 		}
    785 	} else {
    786 		ps.decl_on_line = false;	/* we can't be in the middle of
    787 						 * a declaration, so don't do
    788 						 * special indentation of
    789 						 * comments */
    790 		ps.in_func_def_params = false;
    791 		ps.in_decl = false;
    792 	}
    793 
    794 	ps.decl_ind = 0;
    795 	parse(ps.lbrace_kind);
    796 	if (ps.want_blank)
    797 		buf_add_char(&code, ' ');
    798 	ps.want_blank = false;
    799 	buf_add_char(&code, '{');
    800 	ps.declaration = decl_no;
    801 }
    802 
    803 static void
    804 process_rbrace(void)
    805 {
    806 	if (ps.nparen > 0) {	/* check for unclosed if, for, else. */
    807 		diag(1, "Unbalanced parentheses");
    808 		ps.nparen = 0;
    809 		ps.spaced_expr_psym = psym_0;
    810 	}
    811 
    812 	ps.declaration = decl_no;
    813 	if (ps.block_init_level > 0)
    814 		ps.block_init_level--;
    815 
    816 	if (code.len > 0 && !ps.block_init)
    817 		output_line();
    818 
    819 	buf_add_char(&code, '}');
    820 	ps.want_blank = true;
    821 	ps.in_stmt_or_decl = false;
    822 	ps.in_stmt_cont = false;
    823 
    824 	if (ps.decl_level > 0) {	/* multi-level structure declaration */
    825 		ps.decl_ind = ps.di_stack[--ps.decl_level];
    826 		if (ps.decl_level == 0 && !ps.in_func_def_params) {
    827 			ps.declaration = decl_begin;
    828 			ps.decl_ind = ps.ind_level == 0
    829 			    ? opt.decl_indent : opt.local_decl_indent;
    830 		}
    831 		ps.in_decl = true;
    832 	}
    833 
    834 	if (ps.tos == 2)
    835 		out.line_kind = lk_func_end;
    836 
    837 	parse(psym_rbrace);
    838 
    839 	if (!ps.init_or_struct
    840 	    && ps.s_sym[ps.tos] != psym_do_stmt
    841 	    && ps.s_sym[ps.tos] != psym_if_expr_stmt)
    842 		ps.force_nl = true;
    843 }
    844 
    845 static void
    846 process_do(void)
    847 {
    848 	ps.in_stmt_or_decl = false;
    849 	ps.in_decl = false;
    850 
    851 	if (code.len > 0)
    852 		output_line();
    853 
    854 	ps.force_nl = true;
    855 	parse(psym_do);
    856 }
    857 
    858 static void
    859 process_else(void)
    860 {
    861 	ps.in_stmt_or_decl = false;
    862 
    863 	if (code.len > 0
    864 	    && !(opt.cuddle_else && code.s[code.len - 1] == '}'))
    865 		output_line();
    866 
    867 	ps.force_nl = true;
    868 	parse(psym_else);
    869 }
    870 
    871 static void
    872 process_type(void)
    873 {
    874 	parse(psym_decl);	/* let the parser worry about indentation */
    875 
    876 	if (ps.prev_lsym == lsym_rparen && ps.tos <= 1) {
    877 		if (code.len > 0)
    878 			output_line();
    879 	}
    880 
    881 	if (ps.in_func_def_params && opt.indent_parameters &&
    882 	    ps.decl_level == 0) {
    883 		ps.ind_level = ps.ind_level_follow = 1;
    884 		ps.in_stmt_cont = false;
    885 	}
    886 
    887 	ps.init_or_struct = /* maybe */ true;
    888 	ps.in_decl = ps.decl_on_line = ps.prev_lsym != lsym_typedef;
    889 	if (ps.decl_level <= 0)
    890 		ps.declaration = decl_begin;
    891 
    892 	int len = (int)token.len + 1;
    893 	int ind = ps.ind_level == 0 || ps.decl_level > 0
    894 	    ? opt.decl_indent	/* global variable or local member */
    895 	    : opt.local_decl_indent;	/* local variable */
    896 	ps.decl_ind = ind > 0 ? ind : len;
    897 	ps.tabs_to_var = opt.use_tabs && ind > 0;
    898 }
    899 
    900 static void
    901 process_ident(lexer_symbol lsym)
    902 {
    903 	if (ps.in_decl) {
    904 		if (lsym == lsym_funcname) {
    905 			ps.in_decl = false;
    906 			if (opt.procnames_start_line && code.len > 0)
    907 				output_line();
    908 			else if (ps.want_blank)
    909 				buf_add_char(&code, ' ');
    910 			ps.want_blank = false;
    911 
    912 		} else if (!ps.block_init && !ps.decl_indent_done &&
    913 		    ps.line_start_nparen == 0) {
    914 			if (opt.decl_indent == 0
    915 			    && code.len > 0 && code.s[code.len - 1] == '}')
    916 				ps.decl_ind =
    917 				    ind_add(0, code.s, code.len) + 1;
    918 			code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    919 			ps.decl_indent_done = true;
    920 			ps.want_blank = false;
    921 		}
    922 
    923 	} else if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    924 		ps.force_nl = true;
    925 		ps.next_unary = true;
    926 		ps.in_stmt_or_decl = false;
    927 		parse(ps.spaced_expr_psym);
    928 		ps.spaced_expr_psym = psym_0;
    929 	}
    930 }
    931 
    932 static void
    933 process_period(void)
    934 {
    935 	if (code.len > 0 && code.s[code.len - 1] == ',')
    936 		buf_add_char(&code, ' ');
    937 	buf_add_char(&code, '.');
    938 	ps.want_blank = false;
    939 }
    940 
    941 static void
    942 process_comma(void)
    943 {
    944 	ps.want_blank = code.len > 0;	/* only put blank after comma if comma
    945 					 * does not start the line */
    946 
    947 	if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
    948 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    949 		/* indent leading commas and not the actual identifiers */
    950 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    951 		ps.decl_indent_done = true;
    952 	}
    953 
    954 	buf_add_char(&code, ',');
    955 
    956 	if (ps.nparen == 0) {
    957 		if (ps.block_init_level == 0)
    958 			ps.block_init = false;
    959 		int typical_varname_length = 8;
    960 		if (ps.break_after_comma && (opt.break_after_comma ||
    961 		    ind_add(compute_code_indent(), code.s, code.len)
    962 		    >= opt.max_line_length - typical_varname_length))
    963 			ps.force_nl = true;
    964 	}
    965 }
    966 
    967 /* move the whole line to the 'label' buffer */
    968 static void
    969 read_preprocessing_line(void)
    970 {
    971 	enum {
    972 		PLAIN, STR, CHR, COMM
    973 	} state = PLAIN;
    974 
    975 	buf_add_char(&lab, '#');
    976 
    977 	while (inp_p[0] != '\n' || (state == COMM && !had_eof)) {
    978 		buf_add_char(&lab, inp_next());
    979 		switch (lab.s[lab.len - 1]) {
    980 		case '\\':
    981 			if (state != COMM)
    982 				buf_add_char(&lab, inp_next());
    983 			break;
    984 		case '/':
    985 			if (inp_p[0] == '*' && state == PLAIN) {
    986 				state = COMM;
    987 				buf_add_char(&lab, *inp_p++);
    988 			}
    989 			break;
    990 		case '"':
    991 			if (state == STR)
    992 				state = PLAIN;
    993 			else if (state == PLAIN)
    994 				state = STR;
    995 			break;
    996 		case '\'':
    997 			if (state == CHR)
    998 				state = PLAIN;
    999 			else if (state == PLAIN)
   1000 				state = CHR;
   1001 			break;
   1002 		case '*':
   1003 			if (inp_p[0] == '/' && state == COMM) {
   1004 				state = PLAIN;
   1005 				buf_add_char(&lab, *inp_p++);
   1006 			}
   1007 			break;
   1008 		}
   1009 	}
   1010 
   1011 	while (lab.len > 0 && ch_isblank(lab.s[lab.len - 1]))
   1012 		lab.len--;
   1013 }
   1014 
   1015 static void
   1016 process_preprocessing(void)
   1017 {
   1018 	if (lab.len > 0 || code.len > 0 || com.len > 0)
   1019 		output_line();
   1020 
   1021 	read_preprocessing_line();
   1022 
   1023 	const char *end = lab.s + lab.len;
   1024 	const char *dir = lab.s + 1;
   1025 	while (dir < end && ch_isblank(*dir))
   1026 		dir++;
   1027 	size_t dir_len = 0;
   1028 	while (dir + dir_len < end && ch_isalpha(dir[dir_len]))
   1029 		dir_len++;
   1030 
   1031 	if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
   1032 		if ((size_t)ifdef_level < array_length(state_stack))
   1033 			state_stack[ifdef_level++] = ps;
   1034 		else
   1035 			diag(1, "#if stack overflow");
   1036 		out.line_kind = lk_if;
   1037 
   1038 	} else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
   1039 		if (ifdef_level <= 0)
   1040 			diag(1, dir[2] == 'i'
   1041 			    ? "Unmatched #elif" : "Unmatched #else");
   1042 		else
   1043 			ps = state_stack[ifdef_level - 1];
   1044 
   1045 	} else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
   1046 		if (ifdef_level <= 0)
   1047 			diag(1, "Unmatched #endif");
   1048 		else
   1049 			ifdef_level--;
   1050 		out.line_kind = lk_endif;
   1051 	}
   1052 
   1053 	/* subsequent processing of the newline character will cause the line
   1054 	 * to be printed */
   1055 }
   1056 
   1057 static void
   1058 process_lsym(lexer_symbol lsym)
   1059 {
   1060 	switch (lsym) {
   1061 
   1062 	case lsym_newline:
   1063 		process_newline();
   1064 		break;
   1065 
   1066 	case lsym_lparen:
   1067 		process_lparen();
   1068 		break;
   1069 
   1070 	case lsym_lbracket:
   1071 		process_lbracket();
   1072 		break;
   1073 
   1074 	case lsym_rparen:
   1075 		process_rparen();
   1076 		break;
   1077 
   1078 	case lsym_rbracket:
   1079 		process_rbracket();
   1080 		break;
   1081 
   1082 	case lsym_unary_op:
   1083 		process_unary_op();
   1084 		break;
   1085 
   1086 	case lsym_binary_op:
   1087 		process_binary_op();
   1088 		break;
   1089 
   1090 	case lsym_postfix_op:
   1091 		process_postfix_op();
   1092 		break;
   1093 
   1094 	case lsym_question:
   1095 		process_question();
   1096 		break;
   1097 
   1098 	case lsym_case:
   1099 	case lsym_default:
   1100 		ps.seen_case = true;
   1101 		goto copy_token;
   1102 
   1103 	case lsym_colon_question:
   1104 		process_colon_question();
   1105 		break;
   1106 
   1107 	case lsym_colon_label:
   1108 		process_colon_label();
   1109 		break;
   1110 
   1111 	case lsym_colon_other:
   1112 		process_colon_other();
   1113 		break;
   1114 
   1115 	case lsym_semicolon:
   1116 		process_semicolon();
   1117 		break;
   1118 
   1119 	case lsym_lbrace:
   1120 		process_lbrace();
   1121 		break;
   1122 
   1123 	case lsym_rbrace:
   1124 		process_rbrace();
   1125 		break;
   1126 
   1127 	case lsym_switch:
   1128 		ps.spaced_expr_psym = psym_switch_expr;
   1129 		goto copy_token;
   1130 
   1131 	case lsym_for:
   1132 		ps.spaced_expr_psym = psym_for_exprs;
   1133 		goto copy_token;
   1134 
   1135 	case lsym_if:
   1136 		ps.spaced_expr_psym = psym_if_expr;
   1137 		goto copy_token;
   1138 
   1139 	case lsym_while:
   1140 		ps.spaced_expr_psym = psym_while_expr;
   1141 		goto copy_token;
   1142 
   1143 	case lsym_do:
   1144 		process_do();
   1145 		goto copy_token;
   1146 
   1147 	case lsym_else:
   1148 		process_else();
   1149 		goto copy_token;
   1150 
   1151 	case lsym_typedef:
   1152 	case lsym_modifier:
   1153 		goto copy_token;
   1154 
   1155 	case lsym_tag:
   1156 		if (ps.nparen > 0)
   1157 			goto copy_token;
   1158 		/* FALLTHROUGH */
   1159 	case lsym_type_outside_parentheses:
   1160 		process_type();
   1161 		goto copy_token;
   1162 
   1163 	case lsym_type_in_parentheses:
   1164 	case lsym_offsetof:
   1165 	case lsym_sizeof:
   1166 	case lsym_word:
   1167 	case lsym_funcname:
   1168 	case lsym_return:
   1169 		process_ident(lsym);
   1170 copy_token:
   1171 		if (ps.want_blank)
   1172 			buf_add_char(&code, ' ');
   1173 		buf_add_buf(&code, &token);
   1174 		if (lsym != lsym_funcname)
   1175 			ps.want_blank = true;
   1176 		break;
   1177 
   1178 	case lsym_period:
   1179 		process_period();
   1180 		break;
   1181 
   1182 	case lsym_comma:
   1183 		process_comma();
   1184 		break;
   1185 
   1186 	case lsym_preprocessing:
   1187 		process_preprocessing();
   1188 		break;
   1189 
   1190 	case lsym_comment:
   1191 		process_comment();
   1192 		break;
   1193 
   1194 	default:
   1195 		break;
   1196 	}
   1197 }
   1198 
   1199 static int
   1200 indent(void)
   1201 {
   1202 	debug_parser_state();
   1203 
   1204 	for (;;) {		/* loop until we reach eof */
   1205 		lexer_symbol lsym = lexi();
   1206 
   1207 		debug_blank_line();
   1208 		debug_printf("line %d: %s", line_no, lsym_name[lsym]);
   1209 		debug_print_buf("token", &token);
   1210 		debug_buffers();
   1211 		debug_blank_line();
   1212 
   1213 		if (lsym == lsym_eof)
   1214 			return process_eof();
   1215 
   1216 		if (lsym == lsym_if && ps.prev_lsym == lsym_else
   1217 		    && opt.else_if_in_same_line)
   1218 			ps.force_nl = false;
   1219 
   1220 		if (lsym == lsym_newline || lsym == lsym_preprocessing)
   1221 			ps.force_nl = false;
   1222 		else if (lsym == lsym_comment) {
   1223 			/* no special processing */
   1224 		} else {
   1225 			maybe_break_line(lsym);
   1226 			/*
   1227 			 * Add an extra level of indentation; turned off again
   1228 			 * by a ';' or '}'.
   1229 			 */
   1230 			ps.in_stmt_or_decl = true;
   1231 			if (com.len > 0)
   1232 				move_com_to_code(lsym);
   1233 			update_ps_decl_ptr(lsym);
   1234 			update_ps_prev_tag(lsym);
   1235 		}
   1236 
   1237 		process_lsym(lsym);
   1238 
   1239 		debug_parser_state();
   1240 
   1241 		if (lsym != lsym_comment && lsym != lsym_newline &&
   1242 		    lsym != lsym_preprocessing)
   1243 			ps.prev_lsym = lsym;
   1244 	}
   1245 }
   1246 
   1247 int
   1248 main(int argc, char **argv)
   1249 {
   1250 	init_globals();
   1251 	load_profiles(argc, argv);
   1252 	parse_command_line(argc, argv);
   1253 	set_initial_indentation();
   1254 	return indent();
   1255 }
   1256