Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.304
      1 /*	$NetBSD: indent.c,v 1.304 2023/05/22 23:03:16 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.304 2023/05/22 23:03:16 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 		out.line_kind = lk_stmt_head;
    519 	}
    520 }
    521 
    522 static bool
    523 want_blank_before_unary_op(void)
    524 {
    525 	if (ps.want_blank)
    526 		return true;
    527 	if (token.st[0] == '+' || token.st[0] == '-')
    528 		return code.len > 0 && code.mem[code.len - 1] == token.st[0];
    529 	return false;
    530 }
    531 
    532 static void
    533 process_unary_op(void)
    534 {
    535 	if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
    536 	    !ps.is_function_definition && ps.line_start_nparen == 0) {
    537 		/* pointer declarations */
    538 		code_add_decl_indent(ps.decl_ind - (int)token.len,
    539 		    ps.tabs_to_var);
    540 		ps.decl_indent_done = true;
    541 	} else if (want_blank_before_unary_op())
    542 		buf_add_char(&code, ' ');
    543 
    544 	buf_add_buf(&code, &token);
    545 	ps.want_blank = false;
    546 }
    547 
    548 static void
    549 process_binary_op(void)
    550 {
    551 	if (code.len > 0 && ps.want_blank)
    552 		buf_add_char(&code, ' ');
    553 	buf_add_buf(&code, &token);
    554 	ps.want_blank = true;
    555 }
    556 
    557 static void
    558 process_postfix_op(void)
    559 {
    560 	buf_add_buf(&code, &token);
    561 	ps.want_blank = true;
    562 }
    563 
    564 static void
    565 process_question(void)
    566 {
    567 	ps.quest_level++;
    568 	if (code.len == 0) {
    569 		ps.in_stmt_cont = true;
    570 		ps.in_stmt_or_decl = true;
    571 		ps.in_decl = false;
    572 	}
    573 	if (ps.want_blank)
    574 		buf_add_char(&code, ' ');
    575 	buf_add_char(&code, '?');
    576 	ps.want_blank = true;
    577 }
    578 
    579 static void
    580 process_colon(void)
    581 {
    582 	if (ps.quest_level > 0) {	/* part of a '?:' operator */
    583 		ps.quest_level--;
    584 		if (code.len == 0) {
    585 			ps.in_stmt_cont = true;
    586 			ps.in_stmt_or_decl = true;
    587 			ps.in_decl = false;
    588 		}
    589 		if (ps.want_blank)
    590 			buf_add_char(&code, ' ');
    591 		buf_add_char(&code, ':');
    592 		ps.want_blank = true;
    593 		return;
    594 	}
    595 
    596 	if (ps.init_or_struct) {	/* bit-field */
    597 		buf_add_char(&code, ':');
    598 		ps.want_blank = false;
    599 		return;
    600 	}
    601 
    602 	buf_add_buf(&lab, &code);	/* 'case' or 'default' or named label
    603 					 */
    604 	buf_add_char(&lab, ':');
    605 	code.len = 0;
    606 
    607 	ps.in_stmt_or_decl = false;
    608 	ps.is_case_label = ps.seen_case;
    609 	ps.force_nl = ps.seen_case;
    610 	ps.seen_case = false;
    611 	ps.want_blank = false;
    612 }
    613 
    614 static void
    615 process_semicolon(void)
    616 {
    617 	if (ps.decl_level == 0)
    618 		ps.init_or_struct = false;
    619 	ps.seen_case = false;	/* only needs to be reset on error */
    620 	ps.quest_level = 0;	/* only needs to be reset on error */
    621 	if (ps.prev_token == lsym_rparen_or_rbracket)
    622 		ps.in_func_def_params = false;
    623 	ps.block_init = false;
    624 	ps.block_init_level = 0;
    625 	ps.declaration = ps.declaration == decl_begin ? decl_end : decl_no;
    626 
    627 	if (ps.in_decl && code.len == 0 && !ps.block_init &&
    628 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    629 		/* indent stray semicolons in declarations */
    630 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    631 		ps.decl_indent_done = true;
    632 	}
    633 
    634 	ps.in_decl = ps.decl_level > 0;	/* if we were in a first level
    635 					 * structure declaration before, we
    636 					 * aren't anymore */
    637 
    638 	if (ps.nparen > 0 && ps.spaced_expr_psym != psym_for_exprs) {
    639 		/* There were unbalanced parentheses in the statement. It is a
    640 		 * bit complicated, because the semicolon might be in a for
    641 		 * statement. */
    642 		diag(1, "Unbalanced parentheses");
    643 		ps.nparen = 0;
    644 		if (ps.spaced_expr_psym != psym_0) {
    645 			parse(ps.spaced_expr_psym);
    646 			ps.spaced_expr_psym = psym_0;
    647 		}
    648 	}
    649 	buf_add_char(&code, ';');
    650 	ps.want_blank = true;
    651 	ps.in_stmt_or_decl = ps.nparen > 0;
    652 
    653 	if (ps.spaced_expr_psym == psym_0) {
    654 		parse(psym_0);	/* let parser know about end of stmt */
    655 		ps.force_nl = true;
    656 	}
    657 }
    658 
    659 static void
    660 process_lbrace(void)
    661 {
    662 	ps.in_stmt_or_decl = false;	/* don't indent the {} */
    663 
    664 	if (!ps.block_init)
    665 		ps.force_nl = true;
    666 	else if (ps.block_init_level <= 0)
    667 		ps.block_init_level = 1;
    668 	else
    669 		ps.block_init_level++;
    670 
    671 	if (code.len > 0 && !ps.block_init) {
    672 		if (!opt.brace_same_line ||
    673 		    (code.len > 0 && code.mem[code.len - 1] == '}'))
    674 			output_line();
    675 		else if (ps.in_func_def_params && !ps.init_or_struct) {
    676 			ps.ind_level_follow = 0;
    677 			if (opt.function_brace_split)
    678 				output_line();
    679 			else
    680 				ps.want_blank = true;
    681 		}
    682 	}
    683 
    684 	if (ps.nparen > 0) {
    685 		diag(1, "Unbalanced parentheses");
    686 		ps.nparen = 0;
    687 		if (ps.spaced_expr_psym != psym_0) {
    688 			parse(ps.spaced_expr_psym);
    689 			ps.spaced_expr_psym = psym_0;
    690 			ps.ind_level = ps.ind_level_follow;
    691 		}
    692 	}
    693 
    694 	if (code.len == 0)
    695 		ps.in_stmt_cont = false;	/* don't indent the '{' itself
    696 						 */
    697 	if (ps.in_decl && ps.init_or_struct) {
    698 		ps.di_stack[ps.decl_level] = ps.decl_ind;
    699 		if (++ps.decl_level == (int)array_length(ps.di_stack)) {
    700 			diag(0, "Reached internal limit of %d struct levels",
    701 			    (int)array_length(ps.di_stack));
    702 			ps.decl_level--;
    703 		}
    704 	} else {
    705 		ps.decl_on_line = false;	/* we can't be in the middle of
    706 						 * a declaration, so don't do
    707 						 * special indentation of
    708 						 * comments */
    709 		ps.in_func_def_params = false;
    710 		ps.in_decl = false;
    711 	}
    712 
    713 	ps.decl_ind = 0;
    714 	parse(psym_lbrace);
    715 	if (ps.want_blank)
    716 		buf_add_char(&code, ' ');
    717 	ps.want_blank = false;
    718 	buf_add_char(&code, '{');
    719 	ps.declaration = decl_no;
    720 }
    721 
    722 static void
    723 process_rbrace(void)
    724 {
    725 	if (ps.nparen > 0) {	/* check for unclosed if, for, else. */
    726 		diag(1, "Unbalanced parentheses");
    727 		ps.nparen = 0;
    728 		ps.spaced_expr_psym = psym_0;
    729 	}
    730 
    731 	ps.declaration = decl_no;
    732 	ps.block_init_level--;
    733 
    734 	if (code.len > 0 && !ps.block_init) {
    735 		if (opt.verbose)
    736 			diag(0, "Line broken");
    737 		output_line();
    738 	}
    739 
    740 	buf_add_char(&code, '}');
    741 	ps.want_blank = true;
    742 	ps.in_stmt_or_decl = false;
    743 	ps.in_stmt_cont = false;
    744 
    745 	if (ps.decl_level > 0) {	/* multi-level structure declaration */
    746 		ps.decl_ind = ps.di_stack[--ps.decl_level];
    747 		if (ps.decl_level == 0 && !ps.in_func_def_params) {
    748 			ps.declaration = decl_begin;
    749 			ps.decl_ind = ps.ind_level == 0
    750 			    ? opt.decl_indent : opt.local_decl_indent;
    751 		}
    752 		ps.in_decl = true;
    753 	}
    754 
    755 	if (ps.tos == 2)
    756 		out.line_kind = lk_func_end;
    757 
    758 	parse(psym_rbrace);
    759 }
    760 
    761 static void
    762 process_do(void)
    763 {
    764 	ps.in_stmt_or_decl = false;
    765 
    766 	if (code.len > 0) {	/* make sure this starts a line */
    767 		if (opt.verbose)
    768 			diag(0, "Line broken");
    769 		output_line();
    770 	}
    771 
    772 	ps.force_nl = true;
    773 	parse(psym_do);
    774 }
    775 
    776 static void
    777 process_else(void)
    778 {
    779 	ps.in_stmt_or_decl = false;
    780 
    781 	if (code.len > 0
    782 	    && !(opt.cuddle_else && code.mem[code.len - 1] == '}')) {
    783 		if (opt.verbose)
    784 			diag(0, "Line broken");
    785 		output_line();
    786 	}
    787 
    788 	ps.force_nl = true;
    789 	parse(psym_else);
    790 }
    791 
    792 static void
    793 process_type(void)
    794 {
    795 	parse(psym_decl);	/* let the parser worry about indentation */
    796 
    797 	if (ps.prev_token == lsym_rparen_or_rbracket && ps.tos <= 1) {
    798 		if (code.len > 0)
    799 			output_line();
    800 	}
    801 
    802 	if (ps.in_func_def_params && opt.indent_parameters &&
    803 	    ps.decl_level == 0) {
    804 		ps.ind_level = ps.ind_level_follow = 1;
    805 		ps.in_stmt_cont = false;
    806 	}
    807 
    808 	ps.init_or_struct = /* maybe */ true;
    809 	ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
    810 	if (ps.decl_level <= 0)
    811 		ps.declaration = decl_begin;
    812 
    813 	int len = (int)token.len + 1;
    814 	int ind = ps.ind_level == 0 || ps.decl_level > 0
    815 	    ? opt.decl_indent	/* global variable or local member */
    816 	    : opt.local_decl_indent;	/* local variable */
    817 	ps.decl_ind = ind > 0 ? ind : len;
    818 	ps.tabs_to_var = opt.use_tabs && ind > 0;
    819 }
    820 
    821 static void
    822 process_ident(lexer_symbol lsym)
    823 {
    824 	if (ps.in_decl) {
    825 		if (lsym == lsym_funcname) {
    826 			ps.in_decl = false;
    827 			if (opt.procnames_start_line && code.len > 0)
    828 				output_line();
    829 			else if (ps.want_blank)
    830 				buf_add_char(&code, ' ');
    831 			ps.want_blank = false;
    832 
    833 		} else if (!ps.block_init && !ps.decl_indent_done &&
    834 		    ps.line_start_nparen == 0) {
    835 			if (opt.decl_indent == 0
    836 			    && code.len > 0 && code.mem[code.len - 1] == '}')
    837 				ps.decl_ind =
    838 				    ind_add(0, code.st, code.len) + 1;
    839 			code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    840 			ps.decl_indent_done = true;
    841 			ps.want_blank = false;
    842 		}
    843 
    844 	} else if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    845 		ps.force_nl = true;
    846 		ps.next_unary = true;
    847 		ps.in_stmt_or_decl = false;
    848 		parse(ps.spaced_expr_psym);
    849 		ps.spaced_expr_psym = psym_0;
    850 	}
    851 }
    852 
    853 static void
    854 process_period(void)
    855 {
    856 	if (code.len > 0 && code.mem[code.len - 1] == ',')
    857 		buf_add_char(&code, ' ');
    858 	buf_add_char(&code, '.');
    859 	ps.want_blank = false;
    860 }
    861 
    862 static void
    863 process_comma(void)
    864 {
    865 	ps.want_blank = code.len > 0;	/* only put blank after comma if comma
    866 					 * does not start the line */
    867 
    868 	if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
    869 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    870 		/* indent leading commas and not the actual identifiers */
    871 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    872 		ps.decl_indent_done = true;
    873 	}
    874 
    875 	buf_add_char(&code, ',');
    876 
    877 	if (ps.nparen == 0) {
    878 		if (ps.block_init_level <= 0)
    879 			ps.block_init = false;
    880 		int typical_varname_length = 8;
    881 		if (break_comma && (opt.break_after_comma ||
    882 		    ind_add(compute_code_indent(), code.st, code.len)
    883 		    >= opt.max_line_length - typical_varname_length))
    884 			ps.force_nl = true;
    885 	}
    886 }
    887 
    888 /* move the whole line to the 'label' buffer */
    889 static void
    890 read_preprocessing_line(void)
    891 {
    892 	enum {
    893 		PLAIN, STR, CHR, COMM
    894 	} state = PLAIN;
    895 
    896 	buf_add_char(&lab, '#');
    897 
    898 	while (ch_isblank(inp.st[0]))
    899 		buf_add_char(&lab, *inp.st++);
    900 
    901 	while (inp.st[0] != '\n' || (state == COMM && !had_eof)) {
    902 		buf_add_char(&lab, inp_next());
    903 		switch (lab.mem[lab.len - 1]) {
    904 		case '\\':
    905 			if (state != COMM)
    906 				buf_add_char(&lab, inp_next());
    907 			break;
    908 		case '/':
    909 			if (inp.st[0] == '*' && state == PLAIN) {
    910 				state = COMM;
    911 				buf_add_char(&lab, *inp.st++);
    912 			}
    913 			break;
    914 		case '"':
    915 			if (state == STR)
    916 				state = PLAIN;
    917 			else if (state == PLAIN)
    918 				state = STR;
    919 			break;
    920 		case '\'':
    921 			if (state == CHR)
    922 				state = PLAIN;
    923 			else if (state == PLAIN)
    924 				state = CHR;
    925 			break;
    926 		case '*':
    927 			if (inp.st[0] == '/' && state == COMM) {
    928 				state = PLAIN;
    929 				buf_add_char(&lab, *inp.st++);
    930 			}
    931 			break;
    932 		}
    933 	}
    934 
    935 	while (lab.len > 0 && ch_isblank(lab.mem[lab.len - 1]))
    936 		lab.len--;
    937 }
    938 
    939 static void
    940 process_preprocessing(void)
    941 {
    942 	if (lab.len > 0 || code.len > 0 || com.len > 0)
    943 		output_line();
    944 
    945 	read_preprocessing_line();
    946 
    947 	ps.is_case_label = false;
    948 
    949 	const char *end = lab.mem + lab.len;
    950 	const char *dir = lab.st + 1;
    951 	while (dir < end && ch_isblank(*dir))
    952 		dir++;
    953 	size_t dir_len = 0;
    954 	while (dir + dir_len < end && ch_isalpha(dir[dir_len]))
    955 		dir_len++;
    956 
    957 	if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
    958 		if ((size_t)ifdef_level < array_length(state_stack))
    959 			state_stack[ifdef_level++] = ps;
    960 		else
    961 			diag(1, "#if stack overflow");
    962 		out.line_kind = lk_if;
    963 
    964 	} else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
    965 		if (ifdef_level <= 0)
    966 			diag(1, dir[2] == 'i'
    967 			    ? "Unmatched #elif" : "Unmatched #else");
    968 		else
    969 			ps = state_stack[ifdef_level - 1];
    970 
    971 	} else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
    972 		if (ifdef_level <= 0)
    973 			diag(1, "Unmatched #endif");
    974 		else
    975 			ifdef_level--;
    976 		out.line_kind = lk_endif;
    977 	}
    978 
    979 	/* subsequent processing of the newline character will cause the line
    980 	 * to be printed */
    981 }
    982 
    983 static int
    984 indent(void)
    985 {
    986 	for (;;) {		/* loop until we reach eof */
    987 		lexer_symbol lsym = lexi();
    988 
    989 		if (lsym == lsym_eof)
    990 			return process_eof();
    991 
    992 		if (lsym == lsym_if && ps.prev_token == lsym_else
    993 		    && opt.else_if)
    994 			ps.force_nl = false;
    995 
    996 		if (lsym == lsym_newline || lsym == lsym_preprocessing)
    997 			ps.force_nl = false;
    998 		else if (lsym != lsym_comment) {
    999 			maybe_break_line(lsym);
   1000 			/*
   1001 			 * Add an extra level of indentation; turned off again
   1002 			 * by a ';' or '}'.
   1003 			 */
   1004 			ps.in_stmt_or_decl = true;
   1005 			if (com.len > 0)
   1006 				move_com_to_code(lsym);
   1007 		}
   1008 
   1009 		switch (lsym) {
   1010 
   1011 		case lsym_newline:
   1012 			process_newline();
   1013 			break;
   1014 
   1015 		case lsym_lparen_or_lbracket:
   1016 			process_lparen_or_lbracket();
   1017 			break;
   1018 
   1019 		case lsym_rparen_or_rbracket:
   1020 			process_rparen_or_rbracket();
   1021 			break;
   1022 
   1023 		case lsym_unary_op:
   1024 			process_unary_op();
   1025 			break;
   1026 
   1027 		case lsym_binary_op:
   1028 			process_binary_op();
   1029 			break;
   1030 
   1031 		case lsym_postfix_op:
   1032 			process_postfix_op();
   1033 			break;
   1034 
   1035 		case lsym_question:
   1036 			process_question();
   1037 			break;
   1038 
   1039 		case lsym_case_label:
   1040 			ps.seen_case = true;
   1041 			goto copy_token;
   1042 
   1043 		case lsym_colon:
   1044 			process_colon();
   1045 			break;
   1046 
   1047 		case lsym_semicolon:
   1048 			process_semicolon();
   1049 			break;
   1050 
   1051 		case lsym_lbrace:
   1052 			process_lbrace();
   1053 			break;
   1054 
   1055 		case lsym_rbrace:
   1056 			process_rbrace();
   1057 			break;
   1058 
   1059 		case lsym_switch:
   1060 			ps.spaced_expr_psym = psym_switch_expr;
   1061 			goto copy_token;
   1062 
   1063 		case lsym_for:
   1064 			ps.spaced_expr_psym = psym_for_exprs;
   1065 			goto copy_token;
   1066 
   1067 		case lsym_if:
   1068 			ps.spaced_expr_psym = psym_if_expr;
   1069 			goto copy_token;
   1070 
   1071 		case lsym_while:
   1072 			ps.spaced_expr_psym = psym_while_expr;
   1073 			goto copy_token;
   1074 
   1075 		case lsym_do:
   1076 			process_do();
   1077 			goto copy_token;
   1078 
   1079 		case lsym_else:
   1080 			process_else();
   1081 			goto copy_token;
   1082 
   1083 		case lsym_typedef:
   1084 		case lsym_storage_class:
   1085 			goto copy_token;
   1086 
   1087 		case lsym_tag:
   1088 			if (ps.nparen > 0)
   1089 				goto copy_token;
   1090 			/* FALLTHROUGH */
   1091 		case lsym_type_outside_parentheses:
   1092 			process_type();
   1093 			goto copy_token;
   1094 
   1095 		case lsym_type_in_parentheses:
   1096 		case lsym_offsetof:
   1097 		case lsym_sizeof:
   1098 		case lsym_word:
   1099 		case lsym_funcname:
   1100 		case lsym_return:
   1101 			process_ident(lsym);
   1102 	copy_token:
   1103 			if (ps.want_blank)
   1104 				buf_add_char(&code, ' ');
   1105 			buf_add_buf(&code, &token);
   1106 			if (lsym != lsym_funcname)
   1107 				ps.want_blank = true;
   1108 			break;
   1109 
   1110 		case lsym_period:
   1111 			process_period();
   1112 			break;
   1113 
   1114 		case lsym_comma:
   1115 			process_comma();
   1116 			break;
   1117 
   1118 		case lsym_preprocessing:
   1119 			process_preprocessing();
   1120 			break;
   1121 
   1122 		case lsym_comment:
   1123 			process_comment();
   1124 			break;
   1125 
   1126 		default:
   1127 			break;
   1128 		}
   1129 
   1130 		if (lsym != lsym_comment && lsym != lsym_newline &&
   1131 		    lsym != lsym_preprocessing)
   1132 			ps.prev_token = lsym;
   1133 	}
   1134 }
   1135 
   1136 int
   1137 main(int argc, char **argv)
   1138 {
   1139 	init_globals();
   1140 	load_profiles(argc, argv);
   1141 	parse_command_line(argc, argv);
   1142 	set_initial_indentation();
   1143 	return indent();
   1144 }
   1145