Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.331
      1 /*	$NetBSD: indent.c,v 1.331 2023/06/05 09:10:31 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.331 2023/06/05 09:10:31 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 	if (opt.verbose)
    397 		diag(0, "Line broken");
    398 	output_line();
    399 	ps.force_nl = false;
    400 }
    401 
    402 static void
    403 move_com_to_code(lexer_symbol lsym)
    404 {
    405 	if (ps.want_blank)
    406 		buf_add_char(&code, ' ');
    407 	buf_add_buf(&code, &com);
    408 	com.len = 0;
    409 	ps.want_blank = lsym != lsym_rparen && lsym != lsym_rbracket;
    410 }
    411 
    412 static void
    413 process_newline(void)
    414 {
    415 	if (ps.prev_lsym == lsym_comma
    416 	    && ps.nparen == 0 && !ps.block_init
    417 	    && !opt.break_after_comma && ps.break_after_comma
    418 	    && lab.len == 0 /* for preprocessing lines */
    419 	    && com.len == 0)
    420 		goto stay_in_line;
    421 	if (ps.s_sym[ps.tos] == psym_switch_expr && opt.brace_same_line) {
    422 		ps.force_nl = true;
    423 		goto stay_in_line;
    424 	}
    425 
    426 	output_line();
    427 
    428 stay_in_line:
    429 	++line_no;
    430 }
    431 
    432 static bool
    433 is_function_pointer_declaration(void)
    434 {
    435 	return ps.in_decl
    436 	    && !ps.block_init
    437 	    && !ps.decl_indent_done
    438 	    && !ps.is_function_definition
    439 	    && ps.line_start_nparen == 0;
    440 }
    441 
    442 static bool
    443 want_blank_before_lparen(void)
    444 {
    445 	if (!ps.want_blank)
    446 		return false;
    447 	if (opt.proc_calls_space)
    448 		return true;
    449 	if (ps.prev_lsym == lsym_rparen || ps.prev_lsym == lsym_rbracket)
    450 		return false;
    451 	if (ps.prev_lsym == lsym_offsetof)
    452 		return false;
    453 	if (ps.prev_lsym == lsym_sizeof)
    454 		return opt.blank_after_sizeof;
    455 	if (ps.prev_lsym == lsym_word || ps.prev_lsym == lsym_funcname)
    456 		return false;
    457 	return true;
    458 }
    459 
    460 static void
    461 process_lparen(void)
    462 {
    463 	if (++ps.nparen == array_length(ps.paren)) {
    464 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    465 		    array_length(ps.paren));
    466 		ps.nparen--;
    467 	}
    468 
    469 	if (is_function_pointer_declaration()) {
    470 		code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    471 		ps.decl_indent_done = true;
    472 	} else if (want_blank_before_lparen())
    473 		buf_add_char(&code, ' ');
    474 	ps.want_blank = false;
    475 	buf_add_char(&code, token.s[0]);
    476 
    477 	if (opt.extra_expr_indent && !opt.lineup_to_parens
    478 	    && ps.spaced_expr_psym != psym_0 && ps.nparen == 1
    479 	    && opt.continuation_indent == opt.indent_size)
    480 		ps.extra_expr_indent = eei_yes;
    481 
    482 	if (ps.init_or_struct && ps.tos <= 2) {
    483 		/* A kludge to correctly align function definitions. */
    484 		parse(psym_stmt);
    485 		ps.init_or_struct = false;
    486 	}
    487 
    488 	int indent = ind_add(0, code.s, code.len);
    489 	if (opt.extra_expr_indent && ps.spaced_expr_psym != psym_0
    490 	    && ps.nparen == 1 && indent < 2 * opt.indent_size)
    491 		indent = 2 * opt.indent_size;
    492 
    493 	enum paren_level_cast cast = cast_unknown;
    494 	if (ps.prev_lsym == lsym_offsetof || ps.prev_lsym == lsym_sizeof
    495 	    || ps.is_function_definition)
    496 		cast = cast_no;
    497 
    498 	ps.paren[ps.nparen - 1].indent = indent;
    499 	ps.paren[ps.nparen - 1].cast = cast;
    500 	debug_println("paren_indents[%d] is now %s%d",
    501 	    ps.nparen - 1, paren_level_cast_name[cast], indent);
    502 }
    503 
    504 static bool
    505 want_blank_before_lbracket(void)
    506 {
    507 	if (code.len == 0)
    508 		return false;
    509 	if (ps.prev_lsym == lsym_comma)
    510 		return true;
    511 	if (ps.prev_lsym == lsym_binary_op)
    512 		return true;
    513 	return false;
    514 }
    515 
    516 static void
    517 process_lbracket(void)
    518 {
    519 	if (++ps.nparen == array_length(ps.paren)) {
    520 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    521 		    array_length(ps.paren));
    522 		ps.nparen--;
    523 	}
    524 
    525 	if (want_blank_before_lbracket())
    526 		buf_add_char(&code, ' ');
    527 	ps.want_blank = false;
    528 	buf_add_char(&code, token.s[0]);
    529 
    530 	int indent = ind_add(0, code.s, code.len);
    531 
    532 	ps.paren[ps.nparen - 1].indent = indent;
    533 	ps.paren[ps.nparen - 1].cast = cast_no;
    534 	debug_println("paren_indents[%d] is now %d", ps.nparen - 1, indent);
    535 }
    536 
    537 static void
    538 process_rparen(void)
    539 {
    540 	if (ps.nparen == 0) {
    541 		diag(0, "Extra '%c'", *token.s);
    542 		goto unbalanced;
    543 	}
    544 
    545 	enum paren_level_cast cast = ps.paren[--ps.nparen].cast;
    546 	if (ps.decl_on_line && !ps.block_init)
    547 		cast = cast_no;
    548 
    549 	if (cast == cast_maybe) {
    550 		ps.next_unary = true;
    551 		ps.want_blank = opt.space_after_cast;
    552 	} else
    553 		ps.want_blank = true;
    554 
    555 	if (code.len == 0)
    556 		ps.line_start_nparen = ps.nparen;
    557 
    558 unbalanced:
    559 	buf_add_char(&code, token.s[0]);
    560 
    561 	if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    562 		if (ps.extra_expr_indent == eei_yes)
    563 			ps.extra_expr_indent = eei_last;
    564 		ps.force_nl = true;
    565 		ps.next_unary = true;
    566 		ps.in_stmt_or_decl = false;
    567 		parse(ps.spaced_expr_psym);
    568 		ps.spaced_expr_psym = psym_0;
    569 		ps.want_blank = true;
    570 		out.line_kind = lk_stmt_head;
    571 	}
    572 }
    573 
    574 static void
    575 process_rbracket(void)
    576 {
    577 	if (ps.nparen == 0) {
    578 		diag(0, "Extra '%c'", *token.s);
    579 		goto unbalanced;
    580 	}
    581 	--ps.nparen;
    582 
    583 	ps.want_blank = true;
    584 	if (code.len == 0)
    585 		ps.line_start_nparen = ps.nparen;
    586 
    587 unbalanced:
    588 	buf_add_char(&code, token.s[0]);
    589 }
    590 
    591 static bool
    592 want_blank_before_unary_op(void)
    593 {
    594 	if (ps.want_blank)
    595 		return true;
    596 	if (token.s[0] == '+' || token.s[0] == '-')
    597 		return code.len > 0 && code.s[code.len - 1] == token.s[0];
    598 	return false;
    599 }
    600 
    601 static void
    602 process_unary_op(void)
    603 {
    604 	if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
    605 	    !ps.is_function_definition && ps.line_start_nparen == 0) {
    606 		/* pointer declarations */
    607 		code_add_decl_indent(ps.decl_ind - (int)token.len,
    608 		    ps.tabs_to_var);
    609 		ps.decl_indent_done = true;
    610 	} else if (want_blank_before_unary_op())
    611 		buf_add_char(&code, ' ');
    612 
    613 	buf_add_buf(&code, &token);
    614 	ps.want_blank = false;
    615 }
    616 
    617 static void
    618 process_binary_op(void)
    619 {
    620 	if (code.len > 0 && ps.want_blank)
    621 		buf_add_char(&code, ' ');
    622 	buf_add_buf(&code, &token);
    623 	ps.want_blank = true;
    624 }
    625 
    626 static void
    627 process_postfix_op(void)
    628 {
    629 	buf_add_buf(&code, &token);
    630 	ps.want_blank = true;
    631 }
    632 
    633 static void
    634 process_question(void)
    635 {
    636 	ps.quest_level++;
    637 	if (code.len == 0) {
    638 		ps.in_stmt_cont = true;
    639 		ps.in_stmt_or_decl = true;
    640 		ps.in_decl = false;
    641 	}
    642 	if (ps.want_blank)
    643 		buf_add_char(&code, ' ');
    644 	buf_add_char(&code, '?');
    645 	ps.want_blank = true;
    646 }
    647 
    648 static void
    649 process_colon_question(void)
    650 {
    651 	if (code.len == 0) {
    652 		ps.in_stmt_cont = true;
    653 		ps.in_stmt_or_decl = true;
    654 		ps.in_decl = false;
    655 	}
    656 	if (ps.want_blank)
    657 		buf_add_char(&code, ' ');
    658 	buf_add_char(&code, ':');
    659 	ps.want_blank = true;
    660 }
    661 
    662 static void
    663 process_colon_label(void)
    664 {
    665 	buf_add_buf(&lab, &code);
    666 	buf_add_char(&lab, ':');
    667 	code.len = 0;
    668 
    669 	if (ps.seen_case)
    670 		out.line_kind = lk_case_or_default;
    671 	ps.in_stmt_or_decl = false;
    672 	ps.force_nl = ps.seen_case;
    673 	ps.seen_case = false;
    674 	ps.want_blank = false;
    675 }
    676 
    677 static void
    678 process_colon_other(void)
    679 {
    680 	buf_add_char(&code, ':');
    681 	ps.want_blank = false;
    682 }
    683 
    684 static void
    685 process_semicolon(void)
    686 {
    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 	ps.in_stmt_or_decl = false;	/* don't indent the {} */
    743 
    744 	if (!ps.block_init)
    745 		ps.force_nl = true;
    746 	else
    747 		ps.block_init_level++;
    748 
    749 	if (code.len > 0 && !ps.block_init) {
    750 		if (!opt.brace_same_line ||
    751 		    (code.len > 0 && code.s[code.len - 1] == '}'))
    752 			output_line();
    753 		else if (ps.in_func_def_params && !ps.init_or_struct) {
    754 			ps.ind_level_follow = 0;
    755 			if (opt.function_brace_split)
    756 				output_line();
    757 			else
    758 				ps.want_blank = true;
    759 		}
    760 	}
    761 
    762 	if (ps.nparen > 0) {
    763 		diag(1, "Unbalanced parentheses");
    764 		ps.nparen = 0;
    765 		if (ps.spaced_expr_psym != psym_0) {
    766 			parse(ps.spaced_expr_psym);
    767 			ps.spaced_expr_psym = psym_0;
    768 			ps.ind_level = ps.ind_level_follow;
    769 		}
    770 	}
    771 
    772 	if (code.len == 0)
    773 		ps.in_stmt_cont = false;	/* don't indent the '{' itself
    774 						 */
    775 	if (ps.in_decl && ps.init_or_struct) {
    776 		ps.di_stack[ps.decl_level] = ps.decl_ind;
    777 		if (++ps.decl_level == (int)array_length(ps.di_stack)) {
    778 			diag(0, "Reached internal limit of %d struct levels",
    779 			    (int)array_length(ps.di_stack));
    780 			ps.decl_level--;
    781 		}
    782 	} else {
    783 		ps.decl_on_line = false;	/* we can't be in the middle of
    784 						 * a declaration, so don't do
    785 						 * special indentation of
    786 						 * comments */
    787 		ps.in_func_def_params = false;
    788 		ps.in_decl = false;
    789 	}
    790 
    791 	ps.decl_ind = 0;
    792 	parse(ps.lbrace_kind);
    793 	if (ps.want_blank)
    794 		buf_add_char(&code, ' ');
    795 	ps.want_blank = false;
    796 	buf_add_char(&code, '{');
    797 	ps.declaration = decl_no;
    798 }
    799 
    800 static void
    801 process_rbrace(void)
    802 {
    803 	if (ps.nparen > 0) {	/* check for unclosed if, for, else. */
    804 		diag(1, "Unbalanced parentheses");
    805 		ps.nparen = 0;
    806 		ps.spaced_expr_psym = psym_0;
    807 	}
    808 
    809 	ps.declaration = decl_no;
    810 	if (ps.block_init_level > 0)
    811 		ps.block_init_level--;
    812 
    813 	if (code.len > 0 && !ps.block_init) {
    814 		if (opt.verbose)
    815 			diag(0, "Line broken");
    816 		output_line();
    817 	}
    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 
    850 	if (code.len > 0) {	/* make sure this starts a line */
    851 		if (opt.verbose)
    852 			diag(0, "Line broken");
    853 		output_line();
    854 	}
    855 
    856 	ps.force_nl = true;
    857 	parse(psym_do);
    858 }
    859 
    860 static void
    861 process_else(void)
    862 {
    863 	ps.in_stmt_or_decl = false;
    864 
    865 	if (code.len > 0
    866 	    && !(opt.cuddle_else && code.s[code.len - 1] == '}')) {
    867 		if (opt.verbose)
    868 			diag(0, "Line broken");
    869 		output_line();
    870 	}
    871 
    872 	ps.force_nl = true;
    873 	parse(psym_else);
    874 }
    875 
    876 static void
    877 process_type(void)
    878 {
    879 	parse(psym_decl);	/* let the parser worry about indentation */
    880 
    881 	if (ps.prev_lsym == lsym_rparen && ps.tos <= 1) {
    882 		if (code.len > 0)
    883 			output_line();
    884 	}
    885 
    886 	if (ps.in_func_def_params && opt.indent_parameters &&
    887 	    ps.decl_level == 0) {
    888 		ps.ind_level = ps.ind_level_follow = 1;
    889 		ps.in_stmt_cont = false;
    890 	}
    891 
    892 	ps.init_or_struct = /* maybe */ true;
    893 	ps.in_decl = ps.decl_on_line = ps.prev_lsym != lsym_typedef;
    894 	if (ps.decl_level <= 0)
    895 		ps.declaration = decl_begin;
    896 
    897 	int len = (int)token.len + 1;
    898 	int ind = ps.ind_level == 0 || ps.decl_level > 0
    899 	    ? opt.decl_indent	/* global variable or local member */
    900 	    : opt.local_decl_indent;	/* local variable */
    901 	ps.decl_ind = ind > 0 ? ind : len;
    902 	ps.tabs_to_var = opt.use_tabs && ind > 0;
    903 }
    904 
    905 static void
    906 process_ident(lexer_symbol lsym)
    907 {
    908 	if (ps.in_decl) {
    909 		if (lsym == lsym_funcname) {
    910 			ps.in_decl = false;
    911 			if (opt.procnames_start_line && code.len > 0)
    912 				output_line();
    913 			else if (ps.want_blank)
    914 				buf_add_char(&code, ' ');
    915 			ps.want_blank = false;
    916 
    917 		} else if (!ps.block_init && !ps.decl_indent_done &&
    918 		    ps.line_start_nparen == 0) {
    919 			if (opt.decl_indent == 0
    920 			    && code.len > 0 && code.s[code.len - 1] == '}')
    921 				ps.decl_ind =
    922 				    ind_add(0, code.s, code.len) + 1;
    923 			code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    924 			ps.decl_indent_done = true;
    925 			ps.want_blank = false;
    926 		}
    927 
    928 	} else if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    929 		ps.force_nl = true;
    930 		ps.next_unary = true;
    931 		ps.in_stmt_or_decl = false;
    932 		parse(ps.spaced_expr_psym);
    933 		ps.spaced_expr_psym = psym_0;
    934 	}
    935 }
    936 
    937 static void
    938 process_period(void)
    939 {
    940 	if (code.len > 0 && code.s[code.len - 1] == ',')
    941 		buf_add_char(&code, ' ');
    942 	buf_add_char(&code, '.');
    943 	ps.want_blank = false;
    944 }
    945 
    946 static void
    947 process_comma(void)
    948 {
    949 	ps.want_blank = code.len > 0;	/* only put blank after comma if comma
    950 					 * does not start the line */
    951 
    952 	if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
    953 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    954 		/* indent leading commas and not the actual identifiers */
    955 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    956 		ps.decl_indent_done = true;
    957 	}
    958 
    959 	buf_add_char(&code, ',');
    960 
    961 	if (ps.nparen == 0) {
    962 		if (ps.block_init_level == 0)
    963 			ps.block_init = false;
    964 		int typical_varname_length = 8;
    965 		if (ps.break_after_comma && (opt.break_after_comma ||
    966 		    ind_add(compute_code_indent(), code.s, code.len)
    967 		    >= opt.max_line_length - typical_varname_length))
    968 			ps.force_nl = true;
    969 	}
    970 }
    971 
    972 /* move the whole line to the 'label' buffer */
    973 static void
    974 read_preprocessing_line(void)
    975 {
    976 	enum {
    977 		PLAIN, STR, CHR, COMM
    978 	} state = PLAIN;
    979 
    980 	buf_add_char(&lab, '#');
    981 
    982 	while (inp_p[0] != '\n' || (state == COMM && !had_eof)) {
    983 		buf_add_char(&lab, inp_next());
    984 		switch (lab.s[lab.len - 1]) {
    985 		case '\\':
    986 			if (state != COMM)
    987 				buf_add_char(&lab, inp_next());
    988 			break;
    989 		case '/':
    990 			if (inp_p[0] == '*' && state == PLAIN) {
    991 				state = COMM;
    992 				buf_add_char(&lab, *inp_p++);
    993 			}
    994 			break;
    995 		case '"':
    996 			if (state == STR)
    997 				state = PLAIN;
    998 			else if (state == PLAIN)
    999 				state = STR;
   1000 			break;
   1001 		case '\'':
   1002 			if (state == CHR)
   1003 				state = PLAIN;
   1004 			else if (state == PLAIN)
   1005 				state = CHR;
   1006 			break;
   1007 		case '*':
   1008 			if (inp_p[0] == '/' && state == COMM) {
   1009 				state = PLAIN;
   1010 				buf_add_char(&lab, *inp_p++);
   1011 			}
   1012 			break;
   1013 		}
   1014 	}
   1015 
   1016 	while (lab.len > 0 && ch_isblank(lab.s[lab.len - 1]))
   1017 		lab.len--;
   1018 }
   1019 
   1020 static void
   1021 process_preprocessing(void)
   1022 {
   1023 	if (lab.len > 0 || code.len > 0 || com.len > 0)
   1024 		output_line();
   1025 
   1026 	read_preprocessing_line();
   1027 
   1028 	const char *end = lab.s + lab.len;
   1029 	const char *dir = lab.s + 1;
   1030 	while (dir < end && ch_isblank(*dir))
   1031 		dir++;
   1032 	size_t dir_len = 0;
   1033 	while (dir + dir_len < end && ch_isalpha(dir[dir_len]))
   1034 		dir_len++;
   1035 
   1036 	if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
   1037 		if ((size_t)ifdef_level < array_length(state_stack))
   1038 			state_stack[ifdef_level++] = ps;
   1039 		else
   1040 			diag(1, "#if stack overflow");
   1041 		out.line_kind = lk_if;
   1042 
   1043 	} else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
   1044 		if (ifdef_level <= 0)
   1045 			diag(1, dir[2] == 'i'
   1046 			    ? "Unmatched #elif" : "Unmatched #else");
   1047 		else
   1048 			ps = state_stack[ifdef_level - 1];
   1049 
   1050 	} else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
   1051 		if (ifdef_level <= 0)
   1052 			diag(1, "Unmatched #endif");
   1053 		else
   1054 			ifdef_level--;
   1055 		out.line_kind = lk_endif;
   1056 	}
   1057 
   1058 	/* subsequent processing of the newline character will cause the line
   1059 	 * to be printed */
   1060 }
   1061 
   1062 static void
   1063 process_lsym(lexer_symbol lsym)
   1064 {
   1065 	switch (lsym) {
   1066 
   1067 	case lsym_newline:
   1068 		process_newline();
   1069 		break;
   1070 
   1071 	case lsym_lparen:
   1072 		process_lparen();
   1073 		break;
   1074 
   1075 	case lsym_lbracket:
   1076 		process_lbracket();
   1077 		break;
   1078 
   1079 	case lsym_rparen:
   1080 		process_rparen();
   1081 		break;
   1082 
   1083 	case lsym_rbracket:
   1084 		process_rbracket();
   1085 		break;
   1086 
   1087 	case lsym_unary_op:
   1088 		process_unary_op();
   1089 		break;
   1090 
   1091 	case lsym_binary_op:
   1092 		process_binary_op();
   1093 		break;
   1094 
   1095 	case lsym_postfix_op:
   1096 		process_postfix_op();
   1097 		break;
   1098 
   1099 	case lsym_question:
   1100 		process_question();
   1101 		break;
   1102 
   1103 	case lsym_case:
   1104 	case lsym_default:
   1105 		ps.seen_case = true;
   1106 		goto copy_token;
   1107 
   1108 	case lsym_colon_question:
   1109 		process_colon_question();
   1110 		break;
   1111 
   1112 	case lsym_colon_label:
   1113 		process_colon_label();
   1114 		break;
   1115 
   1116 	case lsym_colon_other:
   1117 		process_colon_other();
   1118 		break;
   1119 
   1120 	case lsym_semicolon:
   1121 		process_semicolon();
   1122 		break;
   1123 
   1124 	case lsym_lbrace:
   1125 		process_lbrace();
   1126 		break;
   1127 
   1128 	case lsym_rbrace:
   1129 		process_rbrace();
   1130 		break;
   1131 
   1132 	case lsym_switch:
   1133 		ps.spaced_expr_psym = psym_switch_expr;
   1134 		goto copy_token;
   1135 
   1136 	case lsym_for:
   1137 		ps.spaced_expr_psym = psym_for_exprs;
   1138 		goto copy_token;
   1139 
   1140 	case lsym_if:
   1141 		ps.spaced_expr_psym = psym_if_expr;
   1142 		goto copy_token;
   1143 
   1144 	case lsym_while:
   1145 		ps.spaced_expr_psym = psym_while_expr;
   1146 		goto copy_token;
   1147 
   1148 	case lsym_do:
   1149 		process_do();
   1150 		goto copy_token;
   1151 
   1152 	case lsym_else:
   1153 		process_else();
   1154 		goto copy_token;
   1155 
   1156 	case lsym_typedef:
   1157 	case lsym_modifier:
   1158 		goto copy_token;
   1159 
   1160 	case lsym_tag:
   1161 		if (ps.nparen > 0)
   1162 			goto copy_token;
   1163 		/* FALLTHROUGH */
   1164 	case lsym_type_outside_parentheses:
   1165 		process_type();
   1166 		goto copy_token;
   1167 
   1168 	case lsym_type_in_parentheses:
   1169 	case lsym_offsetof:
   1170 	case lsym_sizeof:
   1171 	case lsym_word:
   1172 	case lsym_funcname:
   1173 	case lsym_return:
   1174 		process_ident(lsym);
   1175 	copy_token:
   1176 		if (ps.want_blank)
   1177 			buf_add_char(&code, ' ');
   1178 		buf_add_buf(&code, &token);
   1179 		if (lsym != lsym_funcname)
   1180 			ps.want_blank = true;
   1181 		break;
   1182 
   1183 	case lsym_period:
   1184 		process_period();
   1185 		break;
   1186 
   1187 	case lsym_comma:
   1188 		process_comma();
   1189 		break;
   1190 
   1191 	case lsym_preprocessing:
   1192 		process_preprocessing();
   1193 		break;
   1194 
   1195 	case lsym_comment:
   1196 		process_comment();
   1197 		break;
   1198 
   1199 	default:
   1200 		break;
   1201 	}
   1202 }
   1203 
   1204 static int
   1205 indent(void)
   1206 {
   1207 	debug_parser_state();
   1208 
   1209 	for (;;) {		/* loop until we reach eof */
   1210 		lexer_symbol lsym = lexi();
   1211 
   1212 		debug_blank_line();
   1213 		debug_printf("line %d: %s", line_no, lsym_name[lsym]);
   1214 		debug_print_buf("token", &token);
   1215 		debug_buffers();
   1216 		debug_blank_line();
   1217 
   1218 		if (lsym == lsym_eof)
   1219 			return process_eof();
   1220 
   1221 		if (lsym == lsym_if && ps.prev_lsym == lsym_else
   1222 		    && opt.else_if_in_same_line)
   1223 			ps.force_nl = false;
   1224 
   1225 		if (lsym == lsym_newline || lsym == lsym_preprocessing)
   1226 			ps.force_nl = false;
   1227 		else if (lsym == lsym_comment) {
   1228 			/* no special processing */
   1229 		} else {
   1230 			maybe_break_line(lsym);
   1231 			/*
   1232 			 * Add an extra level of indentation; turned off again
   1233 			 * by a ';' or '}'.
   1234 			 */
   1235 			ps.in_stmt_or_decl = true;
   1236 			if (com.len > 0)
   1237 				move_com_to_code(lsym);
   1238 			update_ps_decl_ptr(lsym);
   1239 			update_ps_prev_tag(lsym);
   1240 		}
   1241 
   1242 		process_lsym(lsym);
   1243 
   1244 		debug_parser_state();
   1245 
   1246 		if (lsym != lsym_comment && lsym != lsym_newline &&
   1247 		    lsym != lsym_preprocessing)
   1248 			ps.prev_lsym = lsym;
   1249 	}
   1250 }
   1251 
   1252 int
   1253 main(int argc, char **argv)
   1254 {
   1255 	init_globals();
   1256 	load_profiles(argc, argv);
   1257 	parse_command_line(argc, argv);
   1258 	set_initial_indentation();
   1259 	return indent();
   1260 }
   1261