Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.365
      1 /*	$NetBSD: indent.c,v 1.365 2023/06/14 16:14:30 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.365 2023/06/14 16:14:30 rillig Exp $");
     42 
     43 #include <sys/param.h>
     44 #include <err.h>
     45 #include <stdarg.h>
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 
     50 #include "indent.h"
     51 
     52 struct options opt = {
     53 	.brace_same_line = true,
     54 	.comment_delimiter_on_blank_line = true,
     55 	.cuddle_else = true,
     56 	.comment_column = 33,
     57 	.decl_indent = 16,
     58 	.else_if_in_same_line = true,
     59 	.function_brace_split = true,
     60 	.format_col1_comments = true,
     61 	.format_block_comments = true,
     62 	.indent_parameters = true,
     63 	.indent_size = 8,
     64 	.local_decl_indent = -1,
     65 	.lineup_to_parens = true,
     66 	.procnames_start_line = true,
     67 	.star_comment_cont = true,
     68 	.tabsize = 8,
     69 	.max_line_length = 78,
     70 	.use_tabs = true,
     71 };
     72 
     73 struct parser_state ps;
     74 
     75 struct buffer token;
     76 
     77 struct buffer lab;
     78 struct buffer code;
     79 struct buffer com;
     80 
     81 bool found_err;
     82 bool had_eof;
     83 int line_no = 1;
     84 
     85 static struct {
     86 	struct parser_state *item;
     87 	size_t len;
     88 	size_t cap;
     89 } ifdef;
     90 
     91 FILE *input;
     92 FILE *output;
     93 
     94 static const char *in_name = "Standard Input";
     95 static char backup_name[PATH_MAX];
     96 static const char *backup_suffix = ".BAK";
     97 
     98 
     99 void *
    100 nonnull(void *p)
    101 {
    102 	if (p == NULL)
    103 		err(EXIT_FAILURE, NULL);
    104 	return p;
    105 }
    106 
    107 static void
    108 buf_expand(struct buffer *buf, size_t add_size)
    109 {
    110 	buf->cap = buf->cap + add_size + 400;
    111 	buf->s = nonnull(realloc(buf->s, buf->cap));
    112 }
    113 
    114 #ifdef debug
    115 void
    116 buf_terminate(struct buffer *buf)
    117 {
    118 	if (buf->len == buf->cap)
    119 		buf_expand(buf, 1);
    120 	buf->s[buf->len] = '\0';
    121 }
    122 #endif
    123 
    124 void
    125 buf_add_char(struct buffer *buf, char ch)
    126 {
    127 	if (buf->len == buf->cap)
    128 		buf_expand(buf, 1);
    129 	buf->s[buf->len++] = ch;
    130 	buf_terminate(buf);
    131 }
    132 
    133 void
    134 buf_add_chars(struct buffer *buf, const char *s, size_t len)
    135 {
    136 	if (len == 0)
    137 		return;
    138 	if (len > buf->cap - buf->len)
    139 		buf_expand(buf, len);
    140 	memcpy(buf->s + buf->len, s, len);
    141 	buf->len += len;
    142 	buf_terminate(buf);
    143 }
    144 
    145 static void
    146 buf_add_buf(struct buffer *buf, const struct buffer *add)
    147 {
    148 	buf_add_chars(buf, add->s, add->len);
    149 }
    150 
    151 void
    152 diag(int level, const char *msg, ...)
    153 {
    154 	va_list ap;
    155 
    156 	if (level != 0)
    157 		found_err = true;
    158 
    159 	va_start(ap, msg);
    160 	fprintf(stderr, "%s: %s:%d: ",
    161 	    level == 0 ? "warning" : "error", in_name, line_no);
    162 	vfprintf(stderr, msg, ap);
    163 	fprintf(stderr, "\n");
    164 	va_end(ap);
    165 }
    166 
    167 /*
    168  * Compute the indentation from starting at 'ind' and adding the text starting
    169  * at 's'.
    170  */
    171 int
    172 ind_add(int ind, const char *s, size_t len)
    173 {
    174 	for (const char *p = s; len > 0; p++, len--) {
    175 		if (*p == '\n')
    176 			ind = 0;
    177 		else if (*p == '\t')
    178 			ind = next_tab(ind);
    179 		else if (*p == '\b')
    180 			--ind;
    181 		else
    182 			++ind;
    183 	}
    184 	return ind;
    185 }
    186 
    187 static void
    188 init_globals(void)
    189 {
    190 	ps.psyms.sym[ps.psyms.len++] = psym_stmt;
    191 	ps.prev_lsym = lsym_semicolon;
    192 	ps.lbrace_kind = psym_lbrace_block;
    193 
    194 	const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
    195 	if (suffix != NULL)
    196 		backup_suffix = suffix;
    197 }
    198 
    199 static void
    200 load_profiles(int argc, char **argv)
    201 {
    202 	const char *profile_name = NULL;
    203 
    204 	for (int i = 1; i < argc; ++i) {
    205 		const char *arg = argv[i];
    206 
    207 		if (strcmp(arg, "-npro") == 0)
    208 			return;
    209 		if (arg[0] == '-' && arg[1] == 'P' && arg[2] != '\0')
    210 			profile_name = arg + 2;
    211 	}
    212 
    213 	load_profile_files(profile_name);
    214 }
    215 
    216 /*
    217  * Copy the input file to the backup file, then make the backup file the input
    218  * and the original input file the output.
    219  */
    220 static void
    221 copy_to_bak_file(void)
    222 {
    223 	size_t n;
    224 	char buff[BUFSIZ];
    225 
    226 	const char *last_slash = strrchr(in_name, '/');
    227 	const char *base = last_slash != NULL ? last_slash + 1 : in_name;
    228 	snprintf(backup_name, sizeof(backup_name), "%s%s", base, backup_suffix);
    229 
    230 	/* copy the input file to the backup file */
    231 	FILE *bak = fopen(backup_name, "w");
    232 	if (bak == NULL)
    233 		err(1, "%s", backup_name);
    234 
    235 	while ((n = fread(buff, 1, sizeof(buff), input)) > 0)
    236 		if (fwrite(buff, 1, n, bak) != n)
    237 			err(1, "%s", backup_name);
    238 	if (fclose(input) != 0)
    239 		err(1, "%s", in_name);
    240 	if (fclose(bak) != 0)
    241 		err(1, "%s", backup_name);
    242 
    243 	/* re-open the backup file as the input file */
    244 	input = fopen(backup_name, "r");
    245 	if (input == NULL)
    246 		err(1, "%s", backup_name);
    247 	/* now the original input file will be the output */
    248 	output = fopen(in_name, "w");
    249 	if (output == NULL) {
    250 		remove(backup_name);
    251 		err(1, "%s", in_name);
    252 	}
    253 }
    254 
    255 static void
    256 parse_command_line(int argc, char **argv)
    257 {
    258 	for (int i = 1; i < argc; ++i) {
    259 		const char *arg = argv[i];
    260 
    261 		if (arg[0] == '-') {
    262 			set_option(arg, "Command line");
    263 
    264 		} else if (input == NULL) {
    265 			in_name = arg;
    266 			if ((input = fopen(in_name, "r")) == NULL)
    267 				err(1, "%s", in_name);
    268 
    269 		} else if (output == NULL) {
    270 			if (strcmp(arg, in_name) == 0)
    271 				errx(1, "input and output files "
    272 				    "must be different");
    273 			if ((output = fopen(arg, "w")) == NULL)
    274 				err(1, "%s", arg);
    275 
    276 		} else
    277 			errx(1, "too many arguments: %s", arg);
    278 	}
    279 
    280 	if (input == NULL) {
    281 		input = stdin;
    282 		output = stdout;
    283 	} else if (output == NULL)
    284 		copy_to_bak_file();
    285 
    286 	if (opt.comment_column <= 1)
    287 		opt.comment_column = 2;	/* don't put normal comments in column
    288 					 * 1, see opt.format_col1_comments */
    289 	if (opt.block_comment_max_line_length <= 0)
    290 		opt.block_comment_max_line_length = opt.max_line_length;
    291 	if (opt.local_decl_indent < 0)
    292 		opt.local_decl_indent = opt.decl_indent;
    293 	if (opt.decl_comment_column <= 0)
    294 		opt.decl_comment_column = opt.left_justify_decl
    295 		    ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
    296 		    : opt.comment_column;
    297 	if (opt.continuation_indent == 0)
    298 		opt.continuation_indent = opt.indent_size;
    299 }
    300 
    301 static void
    302 set_initial_indentation(void)
    303 {
    304 	inp_read_line();
    305 
    306 	int ind = 0;
    307 	for (const char *p = inp_p;; p++) {
    308 		if (*p == ' ')
    309 			ind++;
    310 		else if (*p == '\t')
    311 			ind = next_tab(ind);
    312 		else
    313 			break;
    314 	}
    315 
    316 	ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
    317 }
    318 
    319 static bool
    320 should_break_line(lexer_symbol lsym)
    321 {
    322 	if (lsym == lsym_semicolon)
    323 		return false;
    324 	if (ps.prev_lsym == lsym_lbrace || ps.prev_lsym == lsym_semicolon)
    325 		return true;
    326 	if (lsym == lsym_lbrace && opt.brace_same_line)
    327 		return false;
    328 	return true;
    329 }
    330 
    331 static void
    332 move_com_to_code(lexer_symbol lsym)
    333 {
    334 	if (ps.want_blank)
    335 		buf_add_char(&code, ' ');
    336 	buf_add_buf(&code, &com);
    337 	buf_clear(&com);
    338 	ps.want_blank = lsym != lsym_rparen && lsym != lsym_rbracket;
    339 }
    340 
    341 static void
    342 update_ps_lbrace_kind(lexer_symbol lsym)
    343 {
    344 	if (lsym == lsym_tag) {
    345 		ps.lbrace_kind = token.s[0] == 's' ? psym_lbrace_struct :
    346 		    token.s[0] == 'u' ? psym_lbrace_union :
    347 		    psym_lbrace_enum;
    348 	} else if (lsym != lsym_type_outside_parentheses
    349 	    && lsym != lsym_word
    350 	    && lsym != lsym_lbrace)
    351 		ps.lbrace_kind = psym_lbrace_block;
    352 }
    353 
    354 static void
    355 indent_declarator(int decl_ind, bool tabs_to_var)
    356 {
    357 	int base = ps.ind_level * opt.indent_size;
    358 	int ind = base + (int)code.len;
    359 	int target = base + decl_ind;
    360 	size_t orig_code_len = code.len;
    361 
    362 	if (tabs_to_var)
    363 		for (int next; (next = next_tab(ind)) <= target; ind = next)
    364 			buf_add_char(&code, '\t');
    365 
    366 	for (; ind < target; ind++)
    367 		buf_add_char(&code, ' ');
    368 
    369 	if (code.len == orig_code_len && ps.want_blank) {
    370 		buf_add_char(&code, ' ');
    371 		ps.want_blank = false;
    372 	}
    373 	ps.decl_indent_done = true;
    374 }
    375 
    376 static bool
    377 is_function_pointer_declaration(void)
    378 {
    379 	return ps.in_decl
    380 	    && !ps.in_init
    381 	    && !ps.decl_indent_done
    382 	    && !ps.line_has_func_def
    383 	    && ps.ind_paren_level == 0;
    384 }
    385 
    386 static int
    387 process_eof(void)
    388 {
    389 	finish_output();
    390 
    391 	if (ps.psyms.len > 2)	/* check for balanced braces */
    392 		diag(1, "Stuff missing from end of file");
    393 
    394 	return found_err ? EXIT_FAILURE : EXIT_SUCCESS;
    395 }
    396 
    397 /* move the whole line to the 'label' buffer */
    398 static void
    399 read_preprocessing_line(void)
    400 {
    401 	enum {
    402 		PLAIN, STR, CHR, COMM
    403 	} state = PLAIN;
    404 
    405 	buf_add_char(&lab, '#');
    406 
    407 	while (inp_p[0] != '\n' || (state == COMM && !had_eof)) {
    408 		buf_add_char(&lab, inp_next());
    409 		switch (lab.s[lab.len - 1]) {
    410 		case '\\':
    411 			if (state != COMM)
    412 				buf_add_char(&lab, inp_next());
    413 			break;
    414 		case '/':
    415 			if (inp_p[0] == '*' && state == PLAIN) {
    416 				state = COMM;
    417 				buf_add_char(&lab, *inp_p++);
    418 			}
    419 			break;
    420 		case '"':
    421 			if (state == STR)
    422 				state = PLAIN;
    423 			else if (state == PLAIN)
    424 				state = STR;
    425 			break;
    426 		case '\'':
    427 			if (state == CHR)
    428 				state = PLAIN;
    429 			else if (state == PLAIN)
    430 				state = CHR;
    431 			break;
    432 		case '*':
    433 			if (inp_p[0] == '/' && state == COMM) {
    434 				state = PLAIN;
    435 				buf_add_char(&lab, *inp_p++);
    436 			}
    437 			break;
    438 		}
    439 	}
    440 
    441 	while (lab.len > 0 && ch_isblank(lab.s[lab.len - 1]))
    442 		lab.len--;
    443 	buf_terminate(&lab);
    444 }
    445 
    446 static void
    447 paren_stack_push(struct paren_stack *s, int indent, enum paren_level_cast cast)
    448 {
    449 	if (s->len == s->cap) {
    450 		s->cap = 10 + s->cap;
    451 		s->item = nonnull(realloc(s->item,
    452 			sizeof(s->item[0]) * s->cap));
    453 	}
    454 	s->item[s->len++] = (struct paren_level){indent, cast};
    455 }
    456 
    457 static void
    458 parser_state_backup(struct parser_state *dst)
    459 {
    460 	*dst = ps;
    461 
    462 	dst->paren.item = nonnull(
    463 	    malloc(sizeof(dst->paren.item[0]) * ps.paren.cap));
    464 	dst->paren.len = ps.paren.len;
    465 	dst->paren.cap = ps.paren.cap;
    466 	memcpy(dst->paren.item, ps.paren.item,
    467 	    sizeof(dst->paren.item[0]) * ps.paren.len);
    468 }
    469 
    470 static void
    471 parser_state_restore(const struct parser_state *src)
    472 {
    473 	struct paren_stack dst_paren = ps.paren;
    474 	ps = *src;
    475 	ps.paren = dst_paren;
    476 
    477 	ps.paren.len = 0;
    478 	for (size_t i = 0; i < src->paren.len; i++)
    479 		paren_stack_push(&ps.paren,
    480 		    src->paren.item[i].indent, src->paren.item[i].cast);
    481 }
    482 
    483 static void
    484 parser_state_free(struct parser_state *pst)
    485 {
    486 	free(pst->paren.item);
    487 }
    488 
    489 static void
    490 process_preprocessing(void)
    491 {
    492 	if (lab.len > 0 || code.len > 0 || com.len > 0)
    493 		output_line();
    494 
    495 	read_preprocessing_line();
    496 
    497 	const char *dir = lab.s + 1, *line_end = lab.s + lab.len;
    498 	while (dir < line_end && ch_isblank(*dir))
    499 		dir++;
    500 	size_t dir_len = 0;
    501 	while (dir + dir_len < line_end && ch_isalpha(dir[dir_len]))
    502 		dir_len++;
    503 
    504 	if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
    505 		if (ifdef.len >= ifdef.cap) {
    506 			ifdef.cap += 5;
    507 			ifdef.item = nonnull(realloc(ifdef.item,
    508 				sizeof(ifdef.item[0]) * ifdef.cap));
    509 		}
    510 		parser_state_backup(ifdef.item + ifdef.len++);
    511 		out.line_kind = lk_if;
    512 
    513 	} else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
    514 		if (ifdef.len == 0)
    515 			diag(1, "Unmatched #%.*s", (int)dir_len, dir);
    516 		else
    517 			parser_state_restore(ifdef.item + ifdef.len - 1);
    518 
    519 	} else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
    520 		if (ifdef.len == 0)
    521 			diag(1, "Unmatched #endif");
    522 		else
    523 			parser_state_free(ifdef.item + --ifdef.len);
    524 		out.line_kind = lk_endif;
    525 	}
    526 }
    527 
    528 static void
    529 process_newline(void)
    530 {
    531 	if (ps.prev_lsym == lsym_comma
    532 	    && ps.paren.len == 0 && !ps.in_init
    533 	    && !opt.break_after_comma && ps.break_after_comma
    534 	    && lab.len == 0	/* for preprocessing lines */
    535 	    && com.len == 0)
    536 		goto stay_in_line;
    537 	if (ps.psyms.sym[ps.psyms.len - 1] == psym_switch_expr
    538 	    && opt.brace_same_line
    539 	    && com.len == 0) {
    540 		ps.force_nl = true;
    541 		goto stay_in_line;
    542 	}
    543 
    544 	output_line();
    545 
    546 stay_in_line:
    547 	++line_no;
    548 }
    549 
    550 static bool
    551 want_blank_before_lparen(void)
    552 {
    553 	if (opt.proc_calls_space)
    554 		return true;
    555 	if (ps.prev_lsym == lsym_rparen || ps.prev_lsym == lsym_rbracket)
    556 		return false;
    557 	if (ps.prev_lsym == lsym_offsetof)
    558 		return false;
    559 	if (ps.prev_lsym == lsym_sizeof)
    560 		return opt.blank_after_sizeof;
    561 	if (ps.prev_lsym == lsym_word || ps.prev_lsym == lsym_funcname)
    562 		return false;
    563 	return true;
    564 }
    565 
    566 static void
    567 process_lparen(void)
    568 {
    569 
    570 	if (is_function_pointer_declaration())
    571 		indent_declarator(ps.decl_ind, ps.tabs_to_var);
    572 	else if (ps.want_blank && want_blank_before_lparen())
    573 		buf_add_char(&code, ' ');
    574 	ps.want_blank = false;
    575 	buf_add_char(&code, token.s[0]);
    576 
    577 	if (opt.extra_expr_indent && ps.spaced_expr_psym != psym_0)
    578 		ps.extra_expr_indent = eei_maybe;
    579 
    580 	if (ps.in_var_decl && ps.psyms.len <= 3 && !ps.in_init) {
    581 		parse(psym_stmt);	/* prepare for function definition */
    582 		ps.in_var_decl = false;
    583 	}
    584 
    585 	enum paren_level_cast cast = cast_unknown;
    586 	if (ps.prev_lsym == lsym_offsetof
    587 	    || ps.prev_lsym == lsym_sizeof
    588 	    || ps.prev_lsym == lsym_for
    589 	    || ps.prev_lsym == lsym_if
    590 	    || ps.prev_lsym == lsym_switch
    591 	    || ps.prev_lsym == lsym_while
    592 	    || ps.line_has_func_def)
    593 		cast = cast_no;
    594 
    595 	paren_stack_push(&ps.paren, ind_add(0, code.s, code.len), cast);
    596 }
    597 
    598 static void
    599 process_rparen(void)
    600 {
    601 	if (ps.paren.len == 0) {
    602 		diag(0, "Extra '%c'", *token.s);
    603 		goto unbalanced;
    604 	}
    605 
    606 	enum paren_level_cast cast = ps.paren.item[--ps.paren.len].cast;
    607 	if (ps.in_func_def_params || (ps.line_has_decl && !ps.in_init))
    608 		cast = cast_no;
    609 
    610 	ps.prev_paren_was_cast = cast == cast_maybe;
    611 	if (cast == cast_maybe) {
    612 		ps.next_unary = true;
    613 		ps.want_blank = opt.space_after_cast;
    614 	} else
    615 		ps.want_blank = true;
    616 
    617 	if (code.len == 0)
    618 		ps.ind_paren_level = (int)ps.paren.len;
    619 
    620 unbalanced:
    621 	buf_add_char(&code, token.s[0]);
    622 
    623 	if (ps.spaced_expr_psym != psym_0 && ps.paren.len == 0) {
    624 		if (ps.extra_expr_indent == eei_maybe)
    625 			ps.extra_expr_indent = eei_last;
    626 		ps.force_nl = true;
    627 		ps.next_unary = true;
    628 		ps.in_stmt_or_decl = false;
    629 		parse(ps.spaced_expr_psym);
    630 		ps.spaced_expr_psym = psym_0;
    631 		ps.want_blank = true;
    632 		out.line_kind = lk_stmt_head;
    633 	}
    634 }
    635 
    636 static void
    637 process_lbracket(void)
    638 {
    639 	if (code.len > 0
    640 	    && (ps.prev_lsym == lsym_comma || ps.prev_lsym == lsym_binary_op))
    641 		buf_add_char(&code, ' ');
    642 	ps.want_blank = false;
    643 	buf_add_char(&code, token.s[0]);
    644 
    645 	paren_stack_push(&ps.paren, ind_add(0, code.s, code.len), cast_no);
    646 }
    647 
    648 static void
    649 process_rbracket(void)
    650 {
    651 	if (ps.paren.len == 0) {
    652 		diag(0, "Extra '%c'", *token.s);
    653 		goto unbalanced;
    654 	}
    655 	ps.paren.len--;
    656 
    657 	ps.want_blank = true;
    658 	if (code.len == 0)
    659 		ps.ind_paren_level = (int)ps.paren.len;
    660 
    661 unbalanced:
    662 	buf_add_char(&code, token.s[0]);
    663 }
    664 
    665 static void
    666 process_lbrace(void)
    667 {
    668 	if (ps.prev_lsym == lsym_rparen && ps.prev_paren_was_cast) {
    669 		ps.in_var_decl = true;	// XXX: not really
    670 		ps.in_init = true;
    671 	}
    672 
    673 	if (out.line_kind == lk_stmt_head)
    674 		out.line_kind = lk_other;
    675 
    676 	ps.in_stmt_or_decl = false;	/* don't indent the {} */
    677 
    678 	if (ps.in_init)
    679 		ps.init_level++;
    680 	else
    681 		ps.force_nl = true;
    682 
    683 	if (code.len > 0 && !ps.in_init) {
    684 		if (!opt.brace_same_line ||
    685 		    (code.len > 0 && code.s[code.len - 1] == '}'))
    686 			output_line();
    687 		else if (ps.in_func_def_params && !ps.in_var_decl) {
    688 			ps.ind_level_follow = 0;
    689 			if (opt.function_brace_split)
    690 				output_line();
    691 			else
    692 				ps.want_blank = true;
    693 		}
    694 	}
    695 
    696 	if (ps.paren.len > 0 && ps.init_level == 0) {
    697 		diag(1, "Unbalanced parentheses");
    698 		ps.paren.len = 0;
    699 		if (ps.spaced_expr_psym != psym_0) {
    700 			parse(ps.spaced_expr_psym);
    701 			ps.spaced_expr_psym = psym_0;
    702 			ps.ind_level = ps.ind_level_follow;
    703 		}
    704 	}
    705 
    706 	if (code.len == 0)
    707 		ps.in_stmt_cont = false;	/* don't indent the '{' itself
    708 						 */
    709 	if (ps.in_decl && ps.in_var_decl) {
    710 		ps.di_stack[ps.decl_level] = ps.decl_ind;
    711 		if (++ps.decl_level == (int)array_length(ps.di_stack)) {
    712 			diag(0, "Reached internal limit of %zu struct levels",
    713 			    array_length(ps.di_stack));
    714 			ps.decl_level--;
    715 		}
    716 	} else {
    717 		ps.line_has_decl = false;	/* we can't be in the middle of
    718 						 * a declaration, so don't do
    719 						 * special indentation of
    720 						 * comments */
    721 		ps.in_func_def_params = false;
    722 		ps.in_decl = false;
    723 	}
    724 
    725 	ps.decl_ind = 0;
    726 	parse(ps.lbrace_kind);
    727 	if (ps.want_blank)
    728 		buf_add_char(&code, ' ');
    729 	ps.want_blank = false;
    730 	buf_add_char(&code, '{');
    731 	ps.declaration = decl_no;
    732 }
    733 
    734 static void
    735 process_rbrace(void)
    736 {
    737 	if (ps.paren.len > 0 && ps.init_level == 0) {
    738 		diag(1, "Unbalanced parentheses");
    739 		ps.paren.len = 0;
    740 		ps.spaced_expr_psym = psym_0;
    741 	}
    742 
    743 	ps.declaration = decl_no;
    744 	if (ps.init_level > 0)
    745 		ps.init_level--;
    746 
    747 	if (code.len > 0 && !ps.in_init)
    748 		output_line();
    749 
    750 	buf_add_char(&code, '}');
    751 	ps.want_blank = true;
    752 	ps.in_stmt_or_decl = false;	// XXX: Initializers don't end a stmt
    753 	ps.in_stmt_cont = false;
    754 
    755 	if (ps.decl_level > 0) {	/* multi-level structure declaration */
    756 		ps.decl_ind = ps.di_stack[--ps.decl_level];
    757 		if (ps.decl_level == 0 && !ps.in_func_def_params) {
    758 			ps.declaration = decl_begin;
    759 			ps.decl_ind = ps.ind_level == 0
    760 			    ? opt.decl_indent : opt.local_decl_indent;
    761 		}
    762 		ps.in_decl = true;
    763 	}
    764 
    765 	if (ps.psyms.len == 3)
    766 		out.line_kind = lk_func_end;
    767 
    768 	parse(psym_rbrace);
    769 
    770 	if (!ps.in_var_decl
    771 	    && ps.psyms.sym[ps.psyms.len - 1] != psym_do_stmt
    772 	    && ps.psyms.sym[ps.psyms.len - 1] != psym_if_expr_stmt)
    773 		ps.force_nl = true;
    774 }
    775 
    776 static void
    777 process_period(void)
    778 {
    779 	if (code.len > 0 && code.s[code.len - 1] == ',')
    780 		buf_add_char(&code, ' ');
    781 	buf_add_char(&code, '.');
    782 	ps.want_blank = false;
    783 }
    784 
    785 static void
    786 process_unary_op(void)
    787 {
    788 	if (is_function_pointer_declaration()) {
    789 		int ind = ps.decl_ind - (int)token.len;
    790 		indent_declarator(ind, ps.tabs_to_var);
    791 		ps.want_blank = false;
    792 	} else if ((token.s[0] == '+' || token.s[0] == '-')
    793 	    && code.len > 0 && code.s[code.len - 1] == token.s[0])
    794 		ps.want_blank = true;
    795 
    796 	if (ps.want_blank)
    797 		buf_add_char(&code, ' ');
    798 	buf_add_buf(&code, &token);
    799 	ps.want_blank = false;
    800 }
    801 
    802 static void
    803 process_postfix_op(void)
    804 {
    805 	buf_add_buf(&code, &token);
    806 	ps.want_blank = true;
    807 }
    808 
    809 static void
    810 process_comma(void)
    811 {
    812 	ps.want_blank = code.len > 0;	/* only put blank after comma if comma
    813 					 * does not start the line */
    814 
    815 	if (ps.in_decl && !ps.line_has_func_def && !ps.in_init &&
    816 	    !ps.decl_indent_done && ps.ind_paren_level == 0) {
    817 		/* indent leading commas and not the actual identifiers */
    818 		indent_declarator(ps.decl_ind - 1, ps.tabs_to_var);
    819 	}
    820 
    821 	buf_add_char(&code, ',');
    822 
    823 	if (ps.paren.len == 0) {
    824 		if (ps.init_level == 0)
    825 			ps.in_init = false;
    826 		int typical_varname_length = 8;
    827 		if (ps.break_after_comma && (opt.break_after_comma ||
    828 			ind_add(compute_code_indent(), code.s, code.len)
    829 			>= opt.max_line_length - typical_varname_length))
    830 			ps.force_nl = true;
    831 	}
    832 }
    833 
    834 static void
    835 process_label_colon(void)
    836 {
    837 	buf_add_buf(&lab, &code);
    838 	buf_add_char(&lab, ':');
    839 	buf_clear(&code);
    840 
    841 	if (ps.seen_case)
    842 		out.line_kind = lk_case_or_default;
    843 	ps.in_stmt_or_decl = false;
    844 	ps.force_nl = ps.seen_case;
    845 	ps.seen_case = false;
    846 	ps.want_blank = false;
    847 }
    848 
    849 static void
    850 process_other_colon(void)
    851 {
    852 	buf_add_char(&code, ':');
    853 	ps.want_blank = ps.decl_level == 0;
    854 }
    855 
    856 static void
    857 process_semicolon(void)
    858 {
    859 	if (out.line_kind == lk_stmt_head)
    860 		out.line_kind = lk_other;
    861 	if (ps.decl_level == 0)
    862 		ps.in_var_decl = false;
    863 	ps.seen_case = false;	/* only needs to be reset on error */
    864 	ps.quest_level = 0;	/* only needs to be reset on error */
    865 	if (ps.prev_lsym == lsym_rparen)
    866 		ps.in_func_def_params = false;
    867 	ps.in_init = false;
    868 	ps.init_level = 0;
    869 	ps.declaration = ps.declaration == decl_begin ? decl_end : decl_no;
    870 
    871 	if (ps.in_decl && code.len == 0 && !ps.in_init &&
    872 	    !ps.decl_indent_done && ps.ind_paren_level == 0) {
    873 		/* indent stray semicolons in declarations */
    874 		indent_declarator(ps.decl_ind - 1, ps.tabs_to_var);
    875 	}
    876 
    877 	ps.in_decl = ps.decl_level > 0;	/* if we were in a first level
    878 					 * structure declaration before, we
    879 					 * aren't anymore */
    880 
    881 	if (ps.paren.len > 0 && ps.spaced_expr_psym != psym_for_exprs) {
    882 		/* There were unbalanced parentheses in the statement. It is a
    883 		 * bit complicated, because the semicolon might be in a for
    884 		 * statement. */
    885 		diag(1, "Unbalanced parentheses");
    886 		ps.paren.len = 0;
    887 		if (ps.spaced_expr_psym != psym_0) {
    888 			parse(ps.spaced_expr_psym);
    889 			ps.spaced_expr_psym = psym_0;
    890 		}
    891 	}
    892 	buf_add_char(&code, ';');
    893 	ps.want_blank = true;
    894 	ps.in_stmt_or_decl = ps.paren.len > 0;
    895 	ps.decl_ind = 0;
    896 
    897 	if (ps.spaced_expr_psym == psym_0) {
    898 		parse(psym_stmt);
    899 		ps.force_nl = true;
    900 	}
    901 }
    902 
    903 static void
    904 process_type_outside_parentheses(void)
    905 {
    906 	parse(psym_decl);	/* let the parser worry about indentation */
    907 
    908 	if (ps.prev_lsym == lsym_rparen && ps.psyms.len <= 2 && code.len > 0)
    909 		output_line();
    910 
    911 	if (ps.in_func_def_params && opt.indent_parameters &&
    912 	    ps.decl_level == 0) {
    913 		ps.ind_level = ps.ind_level_follow = 1;
    914 		ps.in_stmt_cont = false;
    915 	}
    916 
    917 	ps.in_var_decl = /* maybe */ true;
    918 	ps.in_decl = ps.line_has_decl = ps.prev_lsym != lsym_typedef;
    919 	if (ps.decl_level <= 0)
    920 		ps.declaration = decl_begin;
    921 
    922 	int len = (int)token.len + 1;
    923 	int ind = ps.ind_level > 0 && ps.decl_level == 0
    924 	    ? opt.local_decl_indent	/* local variable */
    925 	    : opt.decl_indent;	/* global variable, or member */
    926 	ps.decl_ind = ind > 0 ? ind : len;
    927 	ps.tabs_to_var = opt.use_tabs && ind > 0;
    928 }
    929 
    930 static void
    931 process_word(lexer_symbol lsym)
    932 {
    933 	if (ps.in_decl) {
    934 		if (lsym == lsym_funcname) {
    935 			ps.in_decl = false;
    936 			if (opt.procnames_start_line && code.len > 0)
    937 				output_line();
    938 			else if (ps.want_blank)
    939 				buf_add_char(&code, ' ');
    940 			ps.want_blank = false;
    941 
    942 		} else if (!ps.in_init && !ps.decl_indent_done &&
    943 		    ps.ind_paren_level == 0) {
    944 			if (opt.decl_indent == 0
    945 			    && code.len > 0 && code.s[code.len - 1] == '}')
    946 				ps.decl_ind = ind_add(0, code.s, code.len) + 1;
    947 			indent_declarator(ps.decl_ind, ps.tabs_to_var);
    948 			ps.want_blank = false;
    949 		}
    950 
    951 	} else if (ps.spaced_expr_psym != psym_0 && ps.paren.len == 0) {
    952 		ps.force_nl = true;
    953 		ps.in_stmt_or_decl = false;
    954 		ps.next_unary = true;
    955 		parse(ps.spaced_expr_psym);
    956 		ps.spaced_expr_psym = psym_0;
    957 	}
    958 }
    959 
    960 static void
    961 process_do(void)
    962 {
    963 	ps.in_stmt_or_decl = false;
    964 	ps.in_decl = false;
    965 
    966 	if (code.len > 0)
    967 		output_line();
    968 
    969 	ps.force_nl = true;
    970 	parse(psym_do);
    971 }
    972 
    973 static void
    974 process_else(void)
    975 {
    976 	ps.in_stmt_or_decl = false;
    977 
    978 	if (code.len > 0
    979 	    && !(opt.cuddle_else && code.s[code.len - 1] == '}'))
    980 		output_line();
    981 
    982 	ps.force_nl = true;
    983 	parse(psym_else);
    984 }
    985 
    986 static void
    987 process_lsym(lexer_symbol lsym)
    988 {
    989 	switch (lsym) {
    990 		/* INDENT OFF */
    991 	case lsym_preprocessing: process_preprocessing(); break;
    992 	case lsym_newline:	process_newline();	break;
    993 	case lsym_comment:	process_comment();	break;
    994 	case lsym_lparen:	process_lparen();	break;
    995 	case lsym_lbracket:	process_lbracket();	break;
    996 	case lsym_rparen:	process_rparen();	break;
    997 	case lsym_rbracket:	process_rbracket();	break;
    998 	case lsym_lbrace:	process_lbrace();	break;
    999 	case lsym_rbrace:	process_rbrace();	break;
   1000 	case lsym_period:	process_period();	break;
   1001 	case lsym_unary_op:	process_unary_op();	break;
   1002 	case lsym_postfix_op:	process_postfix_op();	break;
   1003 	case lsym_binary_op:				goto copy_token;
   1004 	case lsym_question:	ps.quest_level++;	goto copy_token;
   1005 	case lsym_question_colon:			goto copy_token;
   1006 	case lsym_label_colon:	process_label_colon();	break;
   1007 	case lsym_other_colon:	process_other_colon();	break;
   1008 	case lsym_comma:	process_comma();	break;
   1009 	case lsym_semicolon:	process_semicolon();	break;
   1010 	case lsym_typedef:				goto copy_token;
   1011 	case lsym_modifier:				goto copy_token;
   1012 	case lsym_case:		ps.seen_case = true;	goto copy_token;
   1013 	case lsym_default:	ps.seen_case = true;	goto copy_token;
   1014 	case lsym_do:		process_do();		goto copy_token;
   1015 	case lsym_else:		process_else();		goto copy_token;
   1016 	case lsym_for:		ps.spaced_expr_psym = psym_for_exprs; goto copy_token;
   1017 	case lsym_if:		ps.spaced_expr_psym = psym_if_expr; goto copy_token;
   1018 	case lsym_switch:	ps.spaced_expr_psym = psym_switch_expr; goto copy_token;
   1019 	case lsym_while:	ps.spaced_expr_psym = psym_while_expr; goto copy_token;
   1020 		/* INDENT ON */
   1021 
   1022 	case lsym_tag:
   1023 		if (ps.paren.len > 0)
   1024 			goto copy_token;
   1025 		/* FALLTHROUGH */
   1026 	case lsym_type_outside_parentheses:
   1027 		process_type_outside_parentheses();
   1028 		goto copy_token;
   1029 
   1030 	case lsym_type_in_parentheses:
   1031 	case lsym_sizeof:
   1032 	case lsym_offsetof:
   1033 	case lsym_word:
   1034 	case lsym_funcname:
   1035 	case lsym_return:
   1036 		process_word(lsym);
   1037 copy_token:
   1038 		if (ps.want_blank)
   1039 			buf_add_char(&code, ' ');
   1040 		buf_add_buf(&code, &token);
   1041 		if (lsym != lsym_funcname)
   1042 			ps.want_blank = true;
   1043 		break;
   1044 
   1045 	default:
   1046 		break;
   1047 	}
   1048 }
   1049 
   1050 static int
   1051 indent(void)
   1052 {
   1053 	debug_parser_state();
   1054 
   1055 	for (;;) {		/* loop until we reach eof */
   1056 		lexer_symbol lsym = lexi();
   1057 
   1058 		debug_blank_line();
   1059 		debug_printf("line %d: %s", line_no, lsym_name[lsym]);
   1060 		debug_print_buf("token", &token);
   1061 		debug_buffers();
   1062 		debug_blank_line();
   1063 
   1064 		if (lsym == lsym_eof)
   1065 			return process_eof();
   1066 
   1067 		if (lsym == lsym_if && ps.prev_lsym == lsym_else
   1068 		    && opt.else_if_in_same_line)
   1069 			ps.force_nl = false;
   1070 
   1071 		if (lsym == lsym_preprocessing || lsym == lsym_newline)
   1072 			ps.force_nl = false;
   1073 		else if (lsym == lsym_comment) {
   1074 			/* no special processing */
   1075 		} else {
   1076 			if (ps.force_nl && should_break_line(lsym)) {
   1077 				ps.force_nl = false;
   1078 				output_line();
   1079 			}
   1080 			ps.in_stmt_or_decl = true;
   1081 			if (com.len > 0)
   1082 				move_com_to_code(lsym);
   1083 			update_ps_lbrace_kind(lsym);
   1084 		}
   1085 
   1086 		process_lsym(lsym);
   1087 
   1088 		if (lsym != lsym_preprocessing
   1089 		    && lsym != lsym_newline
   1090 		    && lsym != lsym_comment)
   1091 			ps.prev_lsym = lsym;
   1092 
   1093 		debug_parser_state();
   1094 	}
   1095 }
   1096 
   1097 int
   1098 main(int argc, char **argv)
   1099 {
   1100 	init_globals();
   1101 	load_profiles(argc, argv);
   1102 	parse_command_line(argc, argv);
   1103 	set_initial_indentation();
   1104 	return indent();
   1105 }
   1106