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