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