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