Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.318
      1 /*	$NetBSD: indent.c,v 1.318 2023/06/04 10:23:36 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.318 2023/06/04 10:23:36 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 = 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->mem = nonnull(realloc(buf->mem, buf->cap));
    114 	buf->st = buf->mem;
    115 }
    116 
    117 void
    118 buf_add_char(struct buffer *buf, char ch)
    119 {
    120 	if (buf->len == buf->cap)
    121 		buf_expand(buf, 1);
    122 	buf->mem[buf->len++] = ch;
    123 }
    124 
    125 void
    126 buf_add_chars(struct buffer *buf, const char *s, size_t len)
    127 {
    128 	if (len == 0)
    129 		return;
    130 	if (len > buf->cap - buf->len)
    131 		buf_expand(buf, len);
    132 	memcpy(buf->mem + buf->len, s, len);
    133 	buf->len += len;
    134 }
    135 
    136 static void
    137 buf_add_buf(struct buffer *buf, const struct buffer *add)
    138 {
    139 	buf_add_chars(buf, add->st, add->len);
    140 }
    141 
    142 void
    143 diag(int level, const char *msg, ...)
    144 {
    145 	va_list ap;
    146 
    147 	if (level != 0)
    148 		found_err = true;
    149 
    150 	va_start(ap, msg);
    151 	fprintf(stderr, "%s: %s:%d: ",
    152 	    level == 0 ? "warning" : "error", in_name, line_no);
    153 	vfprintf(stderr, msg, ap);
    154 	fprintf(stderr, "\n");
    155 	va_end(ap);
    156 }
    157 
    158 /*
    159  * Compute the indentation from starting at 'ind' and adding the text starting
    160  * at 's'.
    161  */
    162 int
    163 ind_add(int ind, const char *s, size_t len)
    164 {
    165 	for (const char *p = s; len > 0; p++, len--) {
    166 		if (*p == '\n')
    167 			ind = 0;
    168 		else if (*p == '\t')
    169 			ind = next_tab(ind);
    170 		else if (*p == '\b')
    171 			--ind;
    172 		else
    173 			++ind;
    174 	}
    175 	return ind;
    176 }
    177 
    178 static void
    179 init_globals(void)
    180 {
    181 	ps.s_sym[0] = psym_stmt_list;
    182 	ps.prev_token = lsym_semicolon;
    183 	ps.next_col_1 = true;
    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.ljust_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.st;; 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 	switch (ps.decl_ptr) {
    340 	case dp_start:
    341 		if (lsym == lsym_storage_class)
    342 			ps.decl_ptr = dp_start;
    343 		else if (lsym == lsym_type_outside_parentheses)
    344 			ps.decl_ptr = dp_word;
    345 		else if (lsym == lsym_word)
    346 			ps.decl_ptr = dp_word;
    347 		else
    348 			ps.decl_ptr = dp_other;
    349 		break;
    350 	case dp_word:
    351 		if (lsym == lsym_unary_op && token.st[0] == '*')
    352 			ps.decl_ptr = dp_word_asterisk;
    353 		else
    354 			ps.decl_ptr = dp_other;
    355 		break;
    356 	case dp_word_asterisk:
    357 		if (lsym == lsym_unary_op && token.st[0] == '*')
    358 			ps.decl_ptr = dp_word_asterisk;
    359 		else
    360 			ps.decl_ptr = dp_other;
    361 		break;
    362 	case dp_other:
    363 		if (lsym == lsym_semicolon || lsym == lsym_rbrace)
    364 			ps.decl_ptr = dp_start;
    365 		if (lsym == lsym_lparen && ps.prev_token != lsym_sizeof)
    366 			ps.decl_ptr = dp_start;
    367 		if (lsym == lsym_comma && ps.in_decl)
    368 			ps.decl_ptr = dp_start;
    369 		break;
    370 	}
    371 }
    372 
    373 static void
    374 update_ps_in_enum(lexer_symbol lsym)
    375 {
    376 	switch (ps.in_enum) {
    377 	case in_enum_no:
    378 		if (lsym == lsym_tag && token.st[0] == 'e')
    379 			ps.in_enum = in_enum_enum;
    380 		break;
    381 	case in_enum_enum:
    382 		if (lsym == lsym_type_outside_parentheses
    383 		    || lsym == lsym_type_in_parentheses)
    384 			ps.in_enum = in_enum_type;
    385 		else if (lsym == lsym_lbrace)
    386 			ps.in_enum = in_enum_brace;
    387 		else
    388 			ps.in_enum = in_enum_no;
    389 		break;
    390 	case in_enum_type:
    391 		if (lsym == lsym_lbrace)
    392 			ps.in_enum = in_enum_brace;
    393 		else
    394 			ps.in_enum = in_enum_no;
    395 		break;
    396 	case in_enum_brace:
    397 		if (lsym == lsym_rbrace)
    398 			ps.in_enum = in_enum_no;
    399 		break;
    400 	}
    401 }
    402 
    403 static int
    404 process_eof(void)
    405 {
    406 	if (lab.len > 0 || code.len > 0 || com.len > 0)
    407 		output_line();
    408 	if (indent_enabled != indent_on) {
    409 		indent_enabled = indent_last_off_line;
    410 		output_line();
    411 	}
    412 
    413 	if (ps.tos > 1)		/* check for balanced braces */
    414 		diag(1, "Stuff missing from end of file");
    415 
    416 	fflush(output);
    417 	return found_err ? EXIT_FAILURE : EXIT_SUCCESS;
    418 }
    419 
    420 static void
    421 maybe_break_line(lexer_symbol lsym)
    422 {
    423 	if (!ps.force_nl)
    424 		return;
    425 	if (lsym == lsym_semicolon)
    426 		return;
    427 	if (lsym == lsym_lbrace && opt.brace_same_line
    428 	    && ps.prev_token != lsym_lbrace)
    429 		return;
    430 
    431 	if (opt.verbose)
    432 		diag(0, "Line broken");
    433 	output_line();
    434 	ps.force_nl = false;
    435 }
    436 
    437 static void
    438 move_com_to_code(lexer_symbol lsym)
    439 {
    440 	if (ps.want_blank)
    441 		buf_add_char(&code, ' ');
    442 	buf_add_buf(&code, &com);
    443 	if (lsym != lsym_rparen && lsym != lsym_rbracket)
    444 		buf_add_char(&code, ' ');
    445 	com.len = 0;
    446 	ps.want_blank = false;
    447 }
    448 
    449 static void
    450 process_newline(void)
    451 {
    452 	if (ps.prev_token == lsym_comma
    453 	    && ps.nparen == 0 && !ps.block_init
    454 	    && !opt.break_after_comma && ps.break_after_comma
    455 	    && lab.len == 0 /* for preprocessing lines */
    456 	    && com.len == 0)
    457 		goto stay_in_line;
    458 	if (ps.s_sym[ps.tos] == psym_switch_expr && opt.brace_same_line) {
    459 		ps.force_nl = true;
    460 		goto stay_in_line;
    461 	}
    462 
    463 	output_line();
    464 
    465 stay_in_line:
    466 	++line_no;
    467 }
    468 
    469 static bool
    470 is_function_pointer_declaration(void)
    471 {
    472 	return ps.in_decl
    473 	    && !ps.block_init
    474 	    && !ps.decl_indent_done
    475 	    && !ps.is_function_definition
    476 	    && ps.line_start_nparen == 0;
    477 }
    478 
    479 static bool
    480 want_blank_before_lparen(void)
    481 {
    482 	if (!ps.want_blank)
    483 		return false;
    484 	if (opt.proc_calls_space)
    485 		return true;
    486 	if (ps.prev_token == lsym_rparen || ps.prev_token == lsym_rbracket)
    487 		return false;
    488 	if (ps.prev_token == lsym_offsetof)
    489 		return false;
    490 	if (ps.prev_token == lsym_sizeof)
    491 		return opt.blank_after_sizeof;
    492 	if (ps.prev_token == lsym_word || ps.prev_token == lsym_funcname)
    493 		return false;
    494 	return true;
    495 }
    496 
    497 static void
    498 process_lparen(void)
    499 {
    500 	if (++ps.nparen == array_length(ps.paren)) {
    501 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    502 		    array_length(ps.paren));
    503 		ps.nparen--;
    504 	}
    505 
    506 	if (is_function_pointer_declaration()) {
    507 		code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    508 		ps.decl_indent_done = true;
    509 	} else if (want_blank_before_lparen())
    510 		buf_add_char(&code, ' ');
    511 	ps.want_blank = false;
    512 	buf_add_char(&code, token.st[0]);
    513 
    514 	if (opt.extra_expr_indent && !opt.lineup_to_parens
    515 	    && ps.spaced_expr_psym != psym_0 && ps.nparen == 1
    516 	    && opt.continuation_indent == opt.indent_size)
    517 		ps.extra_expr_indent = eei_yes;
    518 
    519 	if (ps.init_or_struct && ps.tos <= 2) {
    520 		/* this is a kluge to make sure that declarations will be
    521 		 * aligned right if proc decl has an explicit type on it, i.e.
    522 		 * "int a(x) {..." */
    523 		parse(psym_stmt);
    524 		ps.init_or_struct = false;
    525 	}
    526 
    527 	int indent = ind_add(0, code.st, code.len);
    528 	if (opt.extra_expr_indent && ps.spaced_expr_psym != psym_0
    529 	    && ps.nparen == 1 && indent < 2 * opt.indent_size)
    530 		indent = 2 * opt.indent_size;
    531 
    532 	enum paren_level_cast cast = cast_unknown;
    533 	if (ps.prev_token == lsym_offsetof || ps.prev_token == lsym_sizeof
    534 	    || ps.is_function_definition)
    535 		cast = cast_no;
    536 
    537 	ps.paren[ps.nparen - 1].indent = indent;
    538 	ps.paren[ps.nparen - 1].cast = cast;
    539 	debug_println("paren_indents[%d] is now %s%d",
    540 	    ps.nparen - 1, paren_level_cast_name[cast], indent);
    541 }
    542 
    543 static bool
    544 want_blank_before_lbracket(void)
    545 {
    546 	if (code.len == 0)
    547 		return false;
    548 	if (ps.prev_token == lsym_comma)
    549 		return true;
    550 	if (ps.prev_token == lsym_binary_op)
    551 		return true;
    552 	return false;
    553 }
    554 
    555 static void
    556 process_lbracket(void)
    557 {
    558 	if (++ps.nparen == array_length(ps.paren)) {
    559 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    560 		    array_length(ps.paren));
    561 		ps.nparen--;
    562 	}
    563 
    564 	if (want_blank_before_lbracket())
    565 		buf_add_char(&code, ' ');
    566 	ps.want_blank = false;
    567 	buf_add_char(&code, token.st[0]);
    568 
    569 	int indent = ind_add(0, code.st, code.len);
    570 
    571 	ps.paren[ps.nparen - 1].indent = indent;
    572 	ps.paren[ps.nparen - 1].cast = cast_no;
    573 	debug_println("paren_indents[%d] is now %d", ps.nparen - 1, indent);
    574 }
    575 
    576 static void
    577 process_rparen(void)
    578 {
    579 	if (ps.nparen == 0) {
    580 		diag(0, "Extra '%c'", *token.st);
    581 		goto unbalanced;
    582 	}
    583 
    584 	enum paren_level_cast cast = ps.paren[--ps.nparen].cast;
    585 	if (ps.decl_on_line && !ps.block_init)
    586 		cast = cast_no;
    587 
    588 	if (cast == cast_maybe) {
    589 		ps.next_unary = true;
    590 		ps.want_blank = opt.space_after_cast;
    591 	} else
    592 		ps.want_blank = true;
    593 
    594 	if (code.len == 0)
    595 		ps.line_start_nparen = ps.nparen;
    596 
    597 unbalanced:
    598 	buf_add_char(&code, token.st[0]);
    599 
    600 	if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    601 		if (ps.extra_expr_indent == eei_yes)
    602 			ps.extra_expr_indent = eei_last;
    603 		ps.force_nl = true;
    604 		ps.next_unary = true;
    605 		ps.in_stmt_or_decl = false;
    606 		parse(ps.spaced_expr_psym);
    607 		ps.spaced_expr_psym = psym_0;
    608 		ps.want_blank = true;
    609 		out.line_kind = lk_stmt_head;
    610 	}
    611 }
    612 
    613 static void
    614 process_rbracket(void)
    615 {
    616 	if (ps.nparen == 0) {
    617 		diag(0, "Extra '%c'", *token.st);
    618 		goto unbalanced;
    619 	}
    620 	--ps.nparen;
    621 
    622 	ps.want_blank = true;
    623 	if (code.len == 0)
    624 		ps.line_start_nparen = ps.nparen;
    625 
    626 unbalanced:
    627 	buf_add_char(&code, token.st[0]);
    628 }
    629 
    630 static bool
    631 want_blank_before_unary_op(void)
    632 {
    633 	if (ps.want_blank)
    634 		return true;
    635 	if (token.st[0] == '+' || token.st[0] == '-')
    636 		return code.len > 0 && code.mem[code.len - 1] == token.st[0];
    637 	return false;
    638 }
    639 
    640 static void
    641 process_unary_op(void)
    642 {
    643 	if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
    644 	    !ps.is_function_definition && ps.line_start_nparen == 0) {
    645 		/* pointer declarations */
    646 		code_add_decl_indent(ps.decl_ind - (int)token.len,
    647 		    ps.tabs_to_var);
    648 		ps.decl_indent_done = true;
    649 	} else if (want_blank_before_unary_op())
    650 		buf_add_char(&code, ' ');
    651 
    652 	buf_add_buf(&code, &token);
    653 	ps.want_blank = false;
    654 }
    655 
    656 static void
    657 process_binary_op(void)
    658 {
    659 	if (code.len > 0 && ps.want_blank)
    660 		buf_add_char(&code, ' ');
    661 	buf_add_buf(&code, &token);
    662 	ps.want_blank = true;
    663 }
    664 
    665 static void
    666 process_postfix_op(void)
    667 {
    668 	buf_add_buf(&code, &token);
    669 	ps.want_blank = true;
    670 }
    671 
    672 static void
    673 process_question(void)
    674 {
    675 	ps.quest_level++;
    676 	if (code.len == 0) {
    677 		ps.in_stmt_cont = true;
    678 		ps.in_stmt_or_decl = true;
    679 		ps.in_decl = false;
    680 	}
    681 	if (ps.want_blank)
    682 		buf_add_char(&code, ' ');
    683 	buf_add_char(&code, '?');
    684 	ps.want_blank = true;
    685 }
    686 
    687 static void
    688 process_colon(void)
    689 {
    690 	if (ps.quest_level > 0) {	/* part of a '?:' operator */
    691 		ps.quest_level--;
    692 		if (code.len == 0) {
    693 			ps.in_stmt_cont = true;
    694 			ps.in_stmt_or_decl = true;
    695 			ps.in_decl = false;
    696 		}
    697 		if (ps.want_blank)
    698 			buf_add_char(&code, ' ');
    699 		buf_add_char(&code, ':');
    700 		ps.want_blank = true;
    701 		return;
    702 	}
    703 
    704 	if (ps.init_or_struct) {	/* bit-field */
    705 		buf_add_char(&code, ':');
    706 		ps.want_blank = false;
    707 		return;
    708 	}
    709 
    710 	buf_add_buf(&lab, &code);	/* 'case' or 'default' or named label
    711 					 */
    712 	buf_add_char(&lab, ':');
    713 	code.len = 0;
    714 
    715 	ps.in_stmt_or_decl = false;
    716 	ps.is_case_label = ps.seen_case;
    717 	ps.force_nl = ps.seen_case;
    718 	ps.seen_case = false;
    719 	ps.want_blank = false;
    720 }
    721 
    722 static void
    723 process_semicolon(void)
    724 {
    725 	if (ps.decl_level == 0)
    726 		ps.init_or_struct = false;
    727 	ps.seen_case = false;	/* only needs to be reset on error */
    728 	ps.quest_level = 0;	/* only needs to be reset on error */
    729 	if (ps.prev_token == lsym_rparen)
    730 		ps.in_func_def_params = false;
    731 	ps.block_init = false;
    732 	ps.block_init_level = 0;
    733 	ps.declaration = ps.declaration == decl_begin ? decl_end : decl_no;
    734 
    735 	if (ps.in_decl && code.len == 0 && !ps.block_init &&
    736 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    737 		/* indent stray semicolons in declarations */
    738 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    739 		ps.decl_indent_done = true;
    740 	}
    741 
    742 	ps.in_decl = ps.decl_level > 0;	/* if we were in a first level
    743 					 * structure declaration before, we
    744 					 * aren't anymore */
    745 
    746 	if (ps.nparen > 0 && ps.spaced_expr_psym != psym_for_exprs) {
    747 		/* There were unbalanced parentheses in the statement. It is a
    748 		 * bit complicated, because the semicolon might be in a for
    749 		 * statement. */
    750 		diag(1, "Unbalanced parentheses");
    751 		ps.nparen = 0;
    752 		if (ps.spaced_expr_psym != psym_0) {
    753 			parse(ps.spaced_expr_psym);
    754 			ps.spaced_expr_psym = psym_0;
    755 		}
    756 	}
    757 	buf_add_char(&code, ';');
    758 	ps.want_blank = true;
    759 	ps.in_stmt_or_decl = ps.nparen > 0;
    760 	ps.decl_ind = 0;
    761 
    762 	if (ps.spaced_expr_psym == psym_0) {
    763 		parse(psym_stmt);
    764 		ps.force_nl = true;
    765 	}
    766 }
    767 
    768 static void
    769 process_lbrace(void)
    770 {
    771 	ps.in_stmt_or_decl = false;	/* don't indent the {} */
    772 
    773 	if (!ps.block_init)
    774 		ps.force_nl = true;
    775 	else if (ps.block_init_level <= 0)
    776 		ps.block_init_level = 1;
    777 	else
    778 		ps.block_init_level++;
    779 
    780 	if (code.len > 0 && !ps.block_init) {
    781 		if (!opt.brace_same_line ||
    782 		    (code.len > 0 && code.mem[code.len - 1] == '}'))
    783 			output_line();
    784 		else if (ps.in_func_def_params && !ps.init_or_struct) {
    785 			ps.ind_level_follow = 0;
    786 			if (opt.function_brace_split)
    787 				output_line();
    788 			else
    789 				ps.want_blank = true;
    790 		}
    791 	}
    792 
    793 	if (ps.nparen > 0) {
    794 		diag(1, "Unbalanced parentheses");
    795 		ps.nparen = 0;
    796 		if (ps.spaced_expr_psym != psym_0) {
    797 			parse(ps.spaced_expr_psym);
    798 			ps.spaced_expr_psym = psym_0;
    799 			ps.ind_level = ps.ind_level_follow;
    800 		}
    801 	}
    802 
    803 	if (code.len == 0)
    804 		ps.in_stmt_cont = false;	/* don't indent the '{' itself
    805 						 */
    806 	if (ps.in_decl && ps.init_or_struct) {
    807 		ps.di_stack[ps.decl_level] = ps.decl_ind;
    808 		if (++ps.decl_level == (int)array_length(ps.di_stack)) {
    809 			diag(0, "Reached internal limit of %d struct levels",
    810 			    (int)array_length(ps.di_stack));
    811 			ps.decl_level--;
    812 		}
    813 	} else {
    814 		ps.decl_on_line = false;	/* we can't be in the middle of
    815 						 * a declaration, so don't do
    816 						 * special indentation of
    817 						 * comments */
    818 		ps.in_func_def_params = false;
    819 		ps.in_decl = false;
    820 	}
    821 
    822 	ps.decl_ind = 0;
    823 	parse(psym_lbrace);
    824 	if (ps.want_blank)
    825 		buf_add_char(&code, ' ');
    826 	ps.want_blank = false;
    827 	buf_add_char(&code, '{');
    828 	ps.declaration = decl_no;
    829 }
    830 
    831 static void
    832 process_rbrace(void)
    833 {
    834 	if (ps.nparen > 0) {	/* check for unclosed if, for, else. */
    835 		diag(1, "Unbalanced parentheses");
    836 		ps.nparen = 0;
    837 		ps.spaced_expr_psym = psym_0;
    838 	}
    839 
    840 	ps.declaration = decl_no;
    841 	ps.block_init_level--;
    842 
    843 	if (code.len > 0 && !ps.block_init) {
    844 		if (opt.verbose)
    845 			diag(0, "Line broken");
    846 		output_line();
    847 	}
    848 
    849 	buf_add_char(&code, '}');
    850 	ps.want_blank = true;
    851 	ps.in_stmt_or_decl = false;
    852 	ps.in_stmt_cont = false;
    853 
    854 	if (ps.decl_level > 0) {	/* multi-level structure declaration */
    855 		ps.decl_ind = ps.di_stack[--ps.decl_level];
    856 		if (ps.decl_level == 0 && !ps.in_func_def_params) {
    857 			ps.declaration = decl_begin;
    858 			ps.decl_ind = ps.ind_level == 0
    859 			    ? opt.decl_indent : opt.local_decl_indent;
    860 		}
    861 		ps.in_decl = true;
    862 	}
    863 
    864 	if (ps.tos == 2)
    865 		out.line_kind = lk_func_end;
    866 
    867 	parse(psym_rbrace);
    868 
    869 	if (!ps.init_or_struct
    870 	    && ps.s_sym[ps.tos] != psym_do_stmt
    871 	    && ps.s_sym[ps.tos] != psym_if_expr_stmt)
    872 		ps.force_nl = true;
    873 }
    874 
    875 static void
    876 process_do(void)
    877 {
    878 	ps.in_stmt_or_decl = false;
    879 
    880 	if (code.len > 0) {	/* make sure this starts a line */
    881 		if (opt.verbose)
    882 			diag(0, "Line broken");
    883 		output_line();
    884 	}
    885 
    886 	ps.force_nl = true;
    887 	parse(psym_do);
    888 }
    889 
    890 static void
    891 process_else(void)
    892 {
    893 	ps.in_stmt_or_decl = false;
    894 
    895 	if (code.len > 0
    896 	    && !(opt.cuddle_else && code.mem[code.len - 1] == '}')) {
    897 		if (opt.verbose)
    898 			diag(0, "Line broken");
    899 		output_line();
    900 	}
    901 
    902 	ps.force_nl = true;
    903 	parse(psym_else);
    904 }
    905 
    906 static void
    907 process_type(void)
    908 {
    909 	parse(psym_decl);	/* let the parser worry about indentation */
    910 
    911 	if (ps.prev_token == lsym_rparen && ps.tos <= 1) {
    912 		if (code.len > 0)
    913 			output_line();
    914 	}
    915 
    916 	if (ps.in_func_def_params && opt.indent_parameters &&
    917 	    ps.decl_level == 0) {
    918 		ps.ind_level = ps.ind_level_follow = 1;
    919 		ps.in_stmt_cont = false;
    920 	}
    921 
    922 	ps.init_or_struct = /* maybe */ true;
    923 	ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
    924 	if (ps.decl_level <= 0)
    925 		ps.declaration = decl_begin;
    926 
    927 	int len = (int)token.len + 1;
    928 	int ind = ps.ind_level == 0 || ps.decl_level > 0
    929 	    ? opt.decl_indent	/* global variable or local member */
    930 	    : opt.local_decl_indent;	/* local variable */
    931 	ps.decl_ind = ind > 0 ? ind : len;
    932 	ps.tabs_to_var = opt.use_tabs && ind > 0;
    933 }
    934 
    935 static void
    936 process_ident(lexer_symbol lsym)
    937 {
    938 	if (ps.in_decl) {
    939 		if (lsym == lsym_funcname) {
    940 			ps.in_decl = false;
    941 			if (opt.procnames_start_line && code.len > 0)
    942 				output_line();
    943 			else if (ps.want_blank)
    944 				buf_add_char(&code, ' ');
    945 			ps.want_blank = false;
    946 
    947 		} else if (!ps.block_init && !ps.decl_indent_done &&
    948 		    ps.line_start_nparen == 0) {
    949 			if (opt.decl_indent == 0
    950 			    && code.len > 0 && code.mem[code.len - 1] == '}')
    951 				ps.decl_ind =
    952 				    ind_add(0, code.st, code.len) + 1;
    953 			code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    954 			ps.decl_indent_done = true;
    955 			ps.want_blank = false;
    956 		}
    957 
    958 	} else if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    959 		ps.force_nl = true;
    960 		ps.next_unary = true;
    961 		ps.in_stmt_or_decl = false;
    962 		parse(ps.spaced_expr_psym);
    963 		ps.spaced_expr_psym = psym_0;
    964 	}
    965 }
    966 
    967 static void
    968 process_period(void)
    969 {
    970 	if (code.len > 0 && code.mem[code.len - 1] == ',')
    971 		buf_add_char(&code, ' ');
    972 	buf_add_char(&code, '.');
    973 	ps.want_blank = false;
    974 }
    975 
    976 static void
    977 process_comma(void)
    978 {
    979 	ps.want_blank = code.len > 0;	/* only put blank after comma if comma
    980 					 * does not start the line */
    981 
    982 	if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
    983 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    984 		/* indent leading commas and not the actual identifiers */
    985 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    986 		ps.decl_indent_done = true;
    987 	}
    988 
    989 	buf_add_char(&code, ',');
    990 
    991 	if (ps.nparen == 0) {
    992 		if (ps.block_init_level <= 0)
    993 			ps.block_init = false;
    994 		int typical_varname_length = 8;
    995 		if (ps.break_after_comma && (opt.break_after_comma ||
    996 		    ind_add(compute_code_indent(), code.st, code.len)
    997 		    >= opt.max_line_length - typical_varname_length))
    998 			ps.force_nl = true;
    999 	}
   1000 }
   1001 
   1002 /* move the whole line to the 'label' buffer */
   1003 static void
   1004 read_preprocessing_line(void)
   1005 {
   1006 	enum {
   1007 		PLAIN, STR, CHR, COMM
   1008 	} state = PLAIN;
   1009 
   1010 	buf_add_char(&lab, '#');
   1011 
   1012 	while (ch_isblank(inp.st[0]))
   1013 		buf_add_char(&lab, *inp.st++);
   1014 
   1015 	while (inp.st[0] != '\n' || (state == COMM && !had_eof)) {
   1016 		buf_add_char(&lab, inp_next());
   1017 		switch (lab.mem[lab.len - 1]) {
   1018 		case '\\':
   1019 			if (state != COMM)
   1020 				buf_add_char(&lab, inp_next());
   1021 			break;
   1022 		case '/':
   1023 			if (inp.st[0] == '*' && state == PLAIN) {
   1024 				state = COMM;
   1025 				buf_add_char(&lab, *inp.st++);
   1026 			}
   1027 			break;
   1028 		case '"':
   1029 			if (state == STR)
   1030 				state = PLAIN;
   1031 			else if (state == PLAIN)
   1032 				state = STR;
   1033 			break;
   1034 		case '\'':
   1035 			if (state == CHR)
   1036 				state = PLAIN;
   1037 			else if (state == PLAIN)
   1038 				state = CHR;
   1039 			break;
   1040 		case '*':
   1041 			if (inp.st[0] == '/' && state == COMM) {
   1042 				state = PLAIN;
   1043 				buf_add_char(&lab, *inp.st++);
   1044 			}
   1045 			break;
   1046 		}
   1047 	}
   1048 
   1049 	while (lab.len > 0 && ch_isblank(lab.mem[lab.len - 1]))
   1050 		lab.len--;
   1051 }
   1052 
   1053 static void
   1054 process_preprocessing(void)
   1055 {
   1056 	if (lab.len > 0 || code.len > 0 || com.len > 0)
   1057 		output_line();
   1058 
   1059 	read_preprocessing_line();
   1060 
   1061 	ps.is_case_label = false;
   1062 
   1063 	const char *end = lab.mem + lab.len;
   1064 	const char *dir = lab.st + 1;
   1065 	while (dir < end && ch_isblank(*dir))
   1066 		dir++;
   1067 	size_t dir_len = 0;
   1068 	while (dir + dir_len < end && ch_isalpha(dir[dir_len]))
   1069 		dir_len++;
   1070 
   1071 	if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
   1072 		if ((size_t)ifdef_level < array_length(state_stack))
   1073 			state_stack[ifdef_level++] = ps;
   1074 		else
   1075 			diag(1, "#if stack overflow");
   1076 		out.line_kind = lk_if;
   1077 
   1078 	} else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
   1079 		if (ifdef_level <= 0)
   1080 			diag(1, dir[2] == 'i'
   1081 			    ? "Unmatched #elif" : "Unmatched #else");
   1082 		else
   1083 			ps = state_stack[ifdef_level - 1];
   1084 
   1085 	} else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
   1086 		if (ifdef_level <= 0)
   1087 			diag(1, "Unmatched #endif");
   1088 		else
   1089 			ifdef_level--;
   1090 		out.line_kind = lk_endif;
   1091 	}
   1092 
   1093 	/* subsequent processing of the newline character will cause the line
   1094 	 * to be printed */
   1095 }
   1096 
   1097 static void
   1098 process_lsym(lexer_symbol lsym)
   1099 {
   1100 	switch (lsym) {
   1101 
   1102 	case lsym_newline:
   1103 		process_newline();
   1104 		break;
   1105 
   1106 	case lsym_lparen:
   1107 		process_lparen();
   1108 		break;
   1109 
   1110 	case lsym_lbracket:
   1111 		process_lbracket();
   1112 		break;
   1113 
   1114 	case lsym_rparen:
   1115 		process_rparen();
   1116 		break;
   1117 
   1118 	case lsym_rbracket:
   1119 		process_rbracket();
   1120 		break;
   1121 
   1122 	case lsym_unary_op:
   1123 		process_unary_op();
   1124 		break;
   1125 
   1126 	case lsym_binary_op:
   1127 		process_binary_op();
   1128 		break;
   1129 
   1130 	case lsym_postfix_op:
   1131 		process_postfix_op();
   1132 		break;
   1133 
   1134 	case lsym_question:
   1135 		process_question();
   1136 		break;
   1137 
   1138 	case lsym_case_label:
   1139 		ps.seen_case = true;
   1140 		goto copy_token;
   1141 
   1142 	case lsym_colon:
   1143 		process_colon();
   1144 		break;
   1145 
   1146 	case lsym_semicolon:
   1147 		process_semicolon();
   1148 		break;
   1149 
   1150 	case lsym_lbrace:
   1151 		process_lbrace();
   1152 		break;
   1153 
   1154 	case lsym_rbrace:
   1155 		process_rbrace();
   1156 		break;
   1157 
   1158 	case lsym_switch:
   1159 		ps.spaced_expr_psym = psym_switch_expr;
   1160 		goto copy_token;
   1161 
   1162 	case lsym_for:
   1163 		ps.spaced_expr_psym = psym_for_exprs;
   1164 		goto copy_token;
   1165 
   1166 	case lsym_if:
   1167 		ps.spaced_expr_psym = psym_if_expr;
   1168 		goto copy_token;
   1169 
   1170 	case lsym_while:
   1171 		ps.spaced_expr_psym = psym_while_expr;
   1172 		goto copy_token;
   1173 
   1174 	case lsym_do:
   1175 		process_do();
   1176 		goto copy_token;
   1177 
   1178 	case lsym_else:
   1179 		process_else();
   1180 		goto copy_token;
   1181 
   1182 	case lsym_typedef:
   1183 	case lsym_storage_class:
   1184 		goto copy_token;
   1185 
   1186 	case lsym_tag:
   1187 		if (ps.nparen > 0)
   1188 			goto copy_token;
   1189 		/* FALLTHROUGH */
   1190 	case lsym_type_outside_parentheses:
   1191 		process_type();
   1192 		goto copy_token;
   1193 
   1194 	case lsym_type_in_parentheses:
   1195 	case lsym_offsetof:
   1196 	case lsym_sizeof:
   1197 	case lsym_word:
   1198 	case lsym_funcname:
   1199 	case lsym_return:
   1200 		process_ident(lsym);
   1201 	copy_token:
   1202 		if (ps.want_blank)
   1203 			buf_add_char(&code, ' ');
   1204 		buf_add_buf(&code, &token);
   1205 		if (lsym != lsym_funcname)
   1206 			ps.want_blank = true;
   1207 		break;
   1208 
   1209 	case lsym_period:
   1210 		process_period();
   1211 		break;
   1212 
   1213 	case lsym_comma:
   1214 		process_comma();
   1215 		break;
   1216 
   1217 	case lsym_preprocessing:
   1218 		process_preprocessing();
   1219 		break;
   1220 
   1221 	case lsym_comment:
   1222 		process_comment();
   1223 		break;
   1224 
   1225 	default:
   1226 		break;
   1227 	}
   1228 }
   1229 
   1230 static int
   1231 indent(void)
   1232 {
   1233 	debug_parser_state();
   1234 
   1235 	for (;;) {		/* loop until we reach eof */
   1236 		lexer_symbol lsym = lexi();
   1237 
   1238 		debug_blank_line();
   1239 		debug_printf("line %d: %s", line_no, lsym_name[lsym]);
   1240 		debug_print_buf("token", &token);
   1241 		debug_buffers();
   1242 		debug_blank_line();
   1243 
   1244 		if (lsym == lsym_eof)
   1245 			return process_eof();
   1246 
   1247 		if (lsym == lsym_if && ps.prev_token == lsym_else
   1248 		    && opt.else_if)
   1249 			ps.force_nl = false;
   1250 
   1251 		if (lsym == lsym_newline || lsym == lsym_preprocessing)
   1252 			ps.force_nl = false;
   1253 		else if (lsym == lsym_comment) {
   1254 			/* no special processing */
   1255 		} else {
   1256 			maybe_break_line(lsym);
   1257 			/*
   1258 			 * Add an extra level of indentation; turned off again
   1259 			 * by a ';' or '}'.
   1260 			 */
   1261 			ps.in_stmt_or_decl = true;
   1262 			if (com.len > 0)
   1263 				move_com_to_code(lsym);
   1264 			update_ps_decl_ptr(lsym);
   1265 			update_ps_in_enum(lsym);
   1266 		}
   1267 
   1268 		process_lsym(lsym);
   1269 
   1270 		debug_parser_state();
   1271 
   1272 		if (lsym != lsym_comment && lsym != lsym_newline &&
   1273 		    lsym != lsym_preprocessing)
   1274 			ps.prev_token = lsym;
   1275 	}
   1276 }
   1277 
   1278 int
   1279 main(int argc, char **argv)
   1280 {
   1281 	init_globals();
   1282 	load_profiles(argc, argv);
   1283 	parse_command_line(argc, argv);
   1284 	set_initial_indentation();
   1285 	return indent();
   1286 }
   1287