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