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