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