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