Home | History | Annotate | Line # | Download | only in indent
indent.c revision 1.319
      1 /*	$NetBSD: indent.c,v 1.319 2023/06/04 11:09:18 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.319 2023/06/04 11:09:18 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 float case_ind;
     85 bool had_eof;
     86 int line_no = 1;
     87 enum indent_enabled indent_enabled;
     88 
     89 static int ifdef_level;
     90 static struct parser_state state_stack[5];
     91 
     92 FILE *input;
     93 FILE *output;
     94 
     95 static const char *in_name = "Standard Input";
     96 static const char *out_name = "Standard Output";
     97 static const char *backup_suffix = ".BAK";
     98 static char bakfile[MAXPATHLEN] = "";
     99 
    100 
    101 void *
    102 nonnull(void *p)
    103 {
    104 	if (p == NULL)
    105 		err(EXIT_FAILURE, NULL);
    106 	return p;
    107 }
    108 
    109 static void
    110 buf_expand(struct buffer *buf, size_t add_size)
    111 {
    112 	buf->cap = buf->cap + add_size + 400;
    113 	buf->mem = nonnull(realloc(buf->mem, buf->cap));
    114 	buf->st = buf->mem;
    115 }
    116 
    117 void
    118 buf_add_char(struct buffer *buf, char ch)
    119 {
    120 	if (buf->len == buf->cap)
    121 		buf_expand(buf, 1);
    122 	buf->mem[buf->len++] = ch;
    123 }
    124 
    125 void
    126 buf_add_chars(struct buffer *buf, const char *s, size_t len)
    127 {
    128 	if (len == 0)
    129 		return;
    130 	if (len > buf->cap - buf->len)
    131 		buf_expand(buf, len);
    132 	memcpy(buf->mem + buf->len, s, len);
    133 	buf->len += len;
    134 }
    135 
    136 static void
    137 buf_add_buf(struct buffer *buf, const struct buffer *add)
    138 {
    139 	buf_add_chars(buf, add->st, add->len);
    140 }
    141 
    142 void
    143 diag(int level, const char *msg, ...)
    144 {
    145 	va_list ap;
    146 
    147 	if (level != 0)
    148 		found_err = true;
    149 
    150 	va_start(ap, msg);
    151 	fprintf(stderr, "%s: %s:%d: ",
    152 	    level == 0 ? "warning" : "error", in_name, line_no);
    153 	vfprintf(stderr, msg, ap);
    154 	fprintf(stderr, "\n");
    155 	va_end(ap);
    156 }
    157 
    158 /*
    159  * Compute the indentation from starting at 'ind' and adding the text starting
    160  * at 's'.
    161  */
    162 int
    163 ind_add(int ind, const char *s, size_t len)
    164 {
    165 	for (const char *p = s; len > 0; p++, len--) {
    166 		if (*p == '\n')
    167 			ind = 0;
    168 		else if (*p == '\t')
    169 			ind = next_tab(ind);
    170 		else if (*p == '\b')
    171 			--ind;
    172 		else
    173 			++ind;
    174 	}
    175 	return ind;
    176 }
    177 
    178 static void
    179 init_globals(void)
    180 {
    181 	ps.s_sym[0] = psym_stmt_list;
    182 	ps.prev_token = lsym_semicolon;
    183 	ps.next_col_1 = true;
    184 
    185 	const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
    186 	if (suffix != NULL)
    187 		backup_suffix = suffix;
    188 }
    189 
    190 /*
    191  * Copy the input file to the backup file, then make the backup file the input
    192  * and the original input file the output.
    193  */
    194 static void
    195 bakcopy(void)
    196 {
    197 	ssize_t n;
    198 	int bak_fd;
    199 	char buff[8 * 1024];
    200 
    201 	const char *last_slash = strrchr(in_name, '/');
    202 	snprintf(bakfile, sizeof(bakfile), "%s%s",
    203 	    last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
    204 
    205 	/* copy in_name to backup file */
    206 	bak_fd = creat(bakfile, 0600);
    207 	if (bak_fd < 0)
    208 		err(1, "%s", bakfile);
    209 
    210 	while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
    211 		if (write(bak_fd, buff, (size_t)n) != n)
    212 			err(1, "%s", bakfile);
    213 	if (n < 0)
    214 		err(1, "%s", in_name);
    215 
    216 	close(bak_fd);
    217 	(void)fclose(input);
    218 
    219 	/* re-open backup file as the input file */
    220 	input = fopen(bakfile, "r");
    221 	if (input == NULL)
    222 		err(1, "%s", bakfile);
    223 	/* now the original input file will be the output */
    224 	output = fopen(in_name, "w");
    225 	if (output == NULL) {
    226 		unlink(bakfile);
    227 		err(1, "%s", in_name);
    228 	}
    229 }
    230 
    231 static void
    232 load_profiles(int argc, char **argv)
    233 {
    234 	const char *profile_name = NULL;
    235 
    236 	for (int i = 1; i < argc; ++i) {
    237 		const char *arg = argv[i];
    238 
    239 		if (strcmp(arg, "-npro") == 0)
    240 			return;
    241 		if (arg[0] == '-' && arg[1] == 'P' && arg[2] != '\0')
    242 			profile_name = arg + 2;
    243 	}
    244 
    245 	load_profile_files(profile_name);
    246 }
    247 
    248 static void
    249 parse_command_line(int argc, char **argv)
    250 {
    251 	for (int i = 1; i < argc; ++i) {
    252 		const char *arg = argv[i];
    253 
    254 		if (arg[0] == '-') {
    255 			set_option(arg, "Command line");
    256 
    257 		} else if (input == NULL) {
    258 			in_name = arg;
    259 			if ((input = fopen(in_name, "r")) == NULL)
    260 				err(1, "%s", in_name);
    261 
    262 		} else if (output == NULL) {
    263 			out_name = arg;
    264 			if (strcmp(in_name, out_name) == 0)
    265 				errx(1, "input and output files "
    266 				    "must be different");
    267 			if ((output = fopen(out_name, "w")) == NULL)
    268 				err(1, "%s", out_name);
    269 
    270 		} else
    271 			errx(1, "too many arguments: %s", arg);
    272 	}
    273 
    274 	if (input == NULL) {
    275 		input = stdin;
    276 		output = stdout;
    277 	} else if (output == NULL) {
    278 		out_name = in_name;
    279 		bakcopy();
    280 	}
    281 
    282 	if (opt.comment_column <= 1)
    283 		opt.comment_column = 2;	/* don't put normal comments in column
    284 					 * 1, see opt.format_col1_comments */
    285 	if (opt.block_comment_max_line_length <= 0)
    286 		opt.block_comment_max_line_length = opt.max_line_length;
    287 	if (opt.local_decl_indent < 0)
    288 		opt.local_decl_indent = opt.decl_indent;
    289 	if (opt.decl_comment_column <= 0)
    290 		opt.decl_comment_column = opt.ljust_decl
    291 		    ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
    292 		    : opt.comment_column;
    293 	if (opt.continuation_indent == 0)
    294 		opt.continuation_indent = opt.indent_size;
    295 }
    296 
    297 static void
    298 set_initial_indentation(void)
    299 {
    300 	inp_read_line();
    301 
    302 	int ind = 0;
    303 	for (const char *p = inp.st;; p++) {
    304 		if (*p == ' ')
    305 			ind++;
    306 		else if (*p == '\t')
    307 			ind = next_tab(ind);
    308 		else
    309 			break;
    310 	}
    311 
    312 	ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
    313 }
    314 
    315 static void
    316 code_add_decl_indent(int decl_ind, bool tabs_to_var)
    317 {
    318 	int base = ps.ind_level * opt.indent_size;
    319 	int ind = base + (int)code.len;
    320 	int target = base + decl_ind;
    321 	size_t orig_code_len = code.len;
    322 
    323 	if (tabs_to_var)
    324 		for (int next; (next = next_tab(ind)) <= target; ind = next)
    325 			buf_add_char(&code, '\t');
    326 
    327 	for (; ind < target; ind++)
    328 		buf_add_char(&code, ' ');
    329 
    330 	if (code.len == orig_code_len && ps.want_blank) {
    331 		buf_add_char(&code, ' ');
    332 		ps.want_blank = false;
    333 	}
    334 }
    335 
    336 static void
    337 update_ps_decl_ptr(lexer_symbol lsym)
    338 {
    339 	switch (ps.decl_ptr) {
    340 	case dp_start:
    341 		if (lsym == lsym_storage_class)
    342 			ps.decl_ptr = dp_start;
    343 		else if (lsym == lsym_type_outside_parentheses)
    344 			ps.decl_ptr = dp_word;
    345 		else if (lsym == lsym_word)
    346 			ps.decl_ptr = dp_word;
    347 		else
    348 			ps.decl_ptr = dp_other;
    349 		break;
    350 	case dp_word:
    351 		if (lsym == lsym_unary_op && token.st[0] == '*')
    352 			ps.decl_ptr = dp_word_asterisk;
    353 		else
    354 			ps.decl_ptr = dp_other;
    355 		break;
    356 	case dp_word_asterisk:
    357 		if (lsym == lsym_unary_op && token.st[0] == '*')
    358 			ps.decl_ptr = dp_word_asterisk;
    359 		else
    360 			ps.decl_ptr = dp_other;
    361 		break;
    362 	case dp_other:
    363 		if (lsym == lsym_semicolon || lsym == lsym_rbrace)
    364 			ps.decl_ptr = dp_start;
    365 		if (lsym == lsym_lparen && ps.prev_token != lsym_sizeof)
    366 			ps.decl_ptr = dp_start;
    367 		if (lsym == lsym_comma && ps.in_decl)
    368 			ps.decl_ptr = dp_start;
    369 		break;
    370 	}
    371 }
    372 
    373 static void
    374 update_ps_in_enum(lexer_symbol lsym)
    375 {
    376 	switch (ps.in_enum) {
    377 	case in_enum_no:
    378 		if (lsym == lsym_tag && token.st[0] == 'e')
    379 			ps.in_enum = in_enum_enum;
    380 		break;
    381 	case in_enum_enum:
    382 		if (lsym == lsym_type_outside_parentheses
    383 		    || lsym == lsym_type_in_parentheses)
    384 			ps.in_enum = in_enum_type;
    385 		else if (lsym == lsym_lbrace)
    386 			ps.in_enum = in_enum_brace;
    387 		else
    388 			ps.in_enum = in_enum_no;
    389 		break;
    390 	case in_enum_type:
    391 		if (lsym == lsym_lbrace)
    392 			ps.in_enum = in_enum_brace;
    393 		else
    394 			ps.in_enum = in_enum_no;
    395 		break;
    396 	case in_enum_brace:
    397 		if (lsym == lsym_rbrace)
    398 			ps.in_enum = in_enum_no;
    399 		break;
    400 	}
    401 }
    402 
    403 static int
    404 process_eof(void)
    405 {
    406 	if (lab.len > 0 || code.len > 0 || com.len > 0)
    407 		output_line();
    408 	if (indent_enabled != indent_on) {
    409 		indent_enabled = indent_last_off_line;
    410 		output_line();
    411 	}
    412 
    413 	if (ps.tos > 1)		/* check for balanced braces */
    414 		diag(1, "Stuff missing from end of file");
    415 
    416 	fflush(output);
    417 	return found_err ? EXIT_FAILURE : EXIT_SUCCESS;
    418 }
    419 
    420 static void
    421 maybe_break_line(lexer_symbol lsym)
    422 {
    423 	if (!ps.force_nl)
    424 		return;
    425 	if (lsym == lsym_semicolon)
    426 		return;
    427 	if (lsym == lsym_lbrace && opt.brace_same_line
    428 	    && ps.prev_token != lsym_lbrace)
    429 		return;
    430 
    431 	if (opt.verbose)
    432 		diag(0, "Line broken");
    433 	output_line();
    434 	ps.force_nl = false;
    435 }
    436 
    437 static void
    438 move_com_to_code(lexer_symbol lsym)
    439 {
    440 	if (ps.want_blank)
    441 		buf_add_char(&code, ' ');
    442 	buf_add_buf(&code, &com);
    443 	if (lsym != lsym_rparen && lsym != lsym_rbracket)
    444 		buf_add_char(&code, ' ');
    445 	com.len = 0;
    446 	ps.want_blank = false;
    447 }
    448 
    449 static void
    450 process_newline(void)
    451 {
    452 	if (ps.prev_token == lsym_comma
    453 	    && ps.nparen == 0 && !ps.block_init
    454 	    && !opt.break_after_comma && ps.break_after_comma
    455 	    && lab.len == 0 /* for preprocessing lines */
    456 	    && com.len == 0)
    457 		goto stay_in_line;
    458 	if (ps.s_sym[ps.tos] == psym_switch_expr && opt.brace_same_line) {
    459 		ps.force_nl = true;
    460 		goto stay_in_line;
    461 	}
    462 
    463 	output_line();
    464 
    465 stay_in_line:
    466 	++line_no;
    467 }
    468 
    469 static bool
    470 is_function_pointer_declaration(void)
    471 {
    472 	return ps.in_decl
    473 	    && !ps.block_init
    474 	    && !ps.decl_indent_done
    475 	    && !ps.is_function_definition
    476 	    && ps.line_start_nparen == 0;
    477 }
    478 
    479 static bool
    480 want_blank_before_lparen(void)
    481 {
    482 	if (!ps.want_blank)
    483 		return false;
    484 	if (opt.proc_calls_space)
    485 		return true;
    486 	if (ps.prev_token == lsym_rparen || ps.prev_token == lsym_rbracket)
    487 		return false;
    488 	if (ps.prev_token == lsym_offsetof)
    489 		return false;
    490 	if (ps.prev_token == lsym_sizeof)
    491 		return opt.blank_after_sizeof;
    492 	if (ps.prev_token == lsym_word || ps.prev_token == lsym_funcname)
    493 		return false;
    494 	return true;
    495 }
    496 
    497 static void
    498 process_lparen(void)
    499 {
    500 	if (++ps.nparen == array_length(ps.paren)) {
    501 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    502 		    array_length(ps.paren));
    503 		ps.nparen--;
    504 	}
    505 
    506 	if (is_function_pointer_declaration()) {
    507 		code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    508 		ps.decl_indent_done = true;
    509 	} else if (want_blank_before_lparen())
    510 		buf_add_char(&code, ' ');
    511 	ps.want_blank = false;
    512 	buf_add_char(&code, token.st[0]);
    513 
    514 	if (opt.extra_expr_indent && !opt.lineup_to_parens
    515 	    && ps.spaced_expr_psym != psym_0 && ps.nparen == 1
    516 	    && opt.continuation_indent == opt.indent_size)
    517 		ps.extra_expr_indent = eei_yes;
    518 
    519 	if (ps.init_or_struct && ps.tos <= 2) {
    520 		/* this is a kluge to make sure that declarations will be
    521 		 * aligned right if proc decl has an explicit type on it, i.e.
    522 		 * "int a(x) {..." */
    523 		parse(psym_stmt);
    524 		ps.init_or_struct = false;
    525 	}
    526 
    527 	int indent = ind_add(0, code.st, code.len);
    528 	if (opt.extra_expr_indent && ps.spaced_expr_psym != psym_0
    529 	    && ps.nparen == 1 && indent < 2 * opt.indent_size)
    530 		indent = 2 * opt.indent_size;
    531 
    532 	enum paren_level_cast cast = cast_unknown;
    533 	if (ps.prev_token == lsym_offsetof || ps.prev_token == lsym_sizeof
    534 	    || ps.is_function_definition)
    535 		cast = cast_no;
    536 
    537 	ps.paren[ps.nparen - 1].indent = indent;
    538 	ps.paren[ps.nparen - 1].cast = cast;
    539 	debug_println("paren_indents[%d] is now %s%d",
    540 	    ps.nparen - 1, paren_level_cast_name[cast], indent);
    541 }
    542 
    543 static bool
    544 want_blank_before_lbracket(void)
    545 {
    546 	if (code.len == 0)
    547 		return false;
    548 	if (ps.prev_token == lsym_comma)
    549 		return true;
    550 	if (ps.prev_token == lsym_binary_op)
    551 		return true;
    552 	return false;
    553 }
    554 
    555 static void
    556 process_lbracket(void)
    557 {
    558 	if (++ps.nparen == array_length(ps.paren)) {
    559 		diag(0, "Reached internal limit of %zu unclosed parentheses",
    560 		    array_length(ps.paren));
    561 		ps.nparen--;
    562 	}
    563 
    564 	if (want_blank_before_lbracket())
    565 		buf_add_char(&code, ' ');
    566 	ps.want_blank = false;
    567 	buf_add_char(&code, token.st[0]);
    568 
    569 	int indent = ind_add(0, code.st, code.len);
    570 
    571 	ps.paren[ps.nparen - 1].indent = indent;
    572 	ps.paren[ps.nparen - 1].cast = cast_no;
    573 	debug_println("paren_indents[%d] is now %d", ps.nparen - 1, indent);
    574 }
    575 
    576 static void
    577 process_rparen(void)
    578 {
    579 	if (ps.nparen == 0) {
    580 		diag(0, "Extra '%c'", *token.st);
    581 		goto unbalanced;
    582 	}
    583 
    584 	enum paren_level_cast cast = ps.paren[--ps.nparen].cast;
    585 	if (ps.decl_on_line && !ps.block_init)
    586 		cast = cast_no;
    587 
    588 	if (cast == cast_maybe) {
    589 		ps.next_unary = true;
    590 		ps.want_blank = opt.space_after_cast;
    591 	} else
    592 		ps.want_blank = true;
    593 
    594 	if (code.len == 0)
    595 		ps.line_start_nparen = ps.nparen;
    596 
    597 unbalanced:
    598 	buf_add_char(&code, token.st[0]);
    599 
    600 	if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    601 		if (ps.extra_expr_indent == eei_yes)
    602 			ps.extra_expr_indent = eei_last;
    603 		ps.force_nl = true;
    604 		ps.next_unary = true;
    605 		ps.in_stmt_or_decl = false;
    606 		parse(ps.spaced_expr_psym);
    607 		ps.spaced_expr_psym = psym_0;
    608 		ps.want_blank = true;
    609 		out.line_kind = lk_stmt_head;
    610 	}
    611 }
    612 
    613 static void
    614 process_rbracket(void)
    615 {
    616 	if (ps.nparen == 0) {
    617 		diag(0, "Extra '%c'", *token.st);
    618 		goto unbalanced;
    619 	}
    620 	--ps.nparen;
    621 
    622 	ps.want_blank = true;
    623 	if (code.len == 0)
    624 		ps.line_start_nparen = ps.nparen;
    625 
    626 unbalanced:
    627 	buf_add_char(&code, token.st[0]);
    628 }
    629 
    630 static bool
    631 want_blank_before_unary_op(void)
    632 {
    633 	if (ps.want_blank)
    634 		return true;
    635 	if (token.st[0] == '+' || token.st[0] == '-')
    636 		return code.len > 0 && code.mem[code.len - 1] == token.st[0];
    637 	return false;
    638 }
    639 
    640 static void
    641 process_unary_op(void)
    642 {
    643 	if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
    644 	    !ps.is_function_definition && ps.line_start_nparen == 0) {
    645 		/* pointer declarations */
    646 		code_add_decl_indent(ps.decl_ind - (int)token.len,
    647 		    ps.tabs_to_var);
    648 		ps.decl_indent_done = true;
    649 	} else if (want_blank_before_unary_op())
    650 		buf_add_char(&code, ' ');
    651 
    652 	buf_add_buf(&code, &token);
    653 	ps.want_blank = false;
    654 }
    655 
    656 static void
    657 process_binary_op(void)
    658 {
    659 	if (code.len > 0 && ps.want_blank)
    660 		buf_add_char(&code, ' ');
    661 	buf_add_buf(&code, &token);
    662 	ps.want_blank = true;
    663 }
    664 
    665 static void
    666 process_postfix_op(void)
    667 {
    668 	buf_add_buf(&code, &token);
    669 	ps.want_blank = true;
    670 }
    671 
    672 static void
    673 process_question(void)
    674 {
    675 	ps.quest_level++;
    676 	if (code.len == 0) {
    677 		ps.in_stmt_cont = true;
    678 		ps.in_stmt_or_decl = true;
    679 		ps.in_decl = false;
    680 	}
    681 	if (ps.want_blank)
    682 		buf_add_char(&code, ' ');
    683 	buf_add_char(&code, '?');
    684 	ps.want_blank = true;
    685 }
    686 
    687 static void
    688 process_colon(void)
    689 {
    690 	if (ps.quest_level > 0) {	/* part of a '?:' operator */
    691 		ps.quest_level--;
    692 		if (code.len == 0) {
    693 			ps.in_stmt_cont = true;
    694 			ps.in_stmt_or_decl = true;
    695 			ps.in_decl = false;
    696 		}
    697 		if (ps.want_blank)
    698 			buf_add_char(&code, ' ');
    699 		buf_add_char(&code, ':');
    700 		ps.want_blank = true;
    701 		return;
    702 	}
    703 
    704 	if (ps.init_or_struct) {	/* bit-field */
    705 		buf_add_char(&code, ':');
    706 		ps.want_blank = false;
    707 		return;
    708 	}
    709 
    710 	buf_add_buf(&lab, &code);	/* 'case' or 'default' or named label
    711 					 */
    712 	buf_add_char(&lab, ':');
    713 	code.len = 0;
    714 
    715 	if (ps.seen_case)
    716 		out.line_kind = lk_case_or_default;
    717 	ps.in_stmt_or_decl = false;
    718 	ps.force_nl = ps.seen_case;
    719 	ps.seen_case = false;
    720 	ps.want_blank = false;
    721 }
    722 
    723 static void
    724 process_semicolon(void)
    725 {
    726 	if (ps.decl_level == 0)
    727 		ps.init_or_struct = false;
    728 	ps.seen_case = false;	/* only needs to be reset on error */
    729 	ps.quest_level = 0;	/* only needs to be reset on error */
    730 	if (ps.prev_token == lsym_rparen)
    731 		ps.in_func_def_params = false;
    732 	ps.block_init = false;
    733 	ps.block_init_level = 0;
    734 	ps.declaration = ps.declaration == decl_begin ? decl_end : decl_no;
    735 
    736 	if (ps.in_decl && code.len == 0 && !ps.block_init &&
    737 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    738 		/* indent stray semicolons in declarations */
    739 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    740 		ps.decl_indent_done = true;
    741 	}
    742 
    743 	ps.in_decl = ps.decl_level > 0;	/* if we were in a first level
    744 					 * structure declaration before, we
    745 					 * aren't anymore */
    746 
    747 	if (ps.nparen > 0 && ps.spaced_expr_psym != psym_for_exprs) {
    748 		/* There were unbalanced parentheses in the statement. It is a
    749 		 * bit complicated, because the semicolon might be in a for
    750 		 * statement. */
    751 		diag(1, "Unbalanced parentheses");
    752 		ps.nparen = 0;
    753 		if (ps.spaced_expr_psym != psym_0) {
    754 			parse(ps.spaced_expr_psym);
    755 			ps.spaced_expr_psym = psym_0;
    756 		}
    757 	}
    758 	buf_add_char(&code, ';');
    759 	ps.want_blank = true;
    760 	ps.in_stmt_or_decl = ps.nparen > 0;
    761 	ps.decl_ind = 0;
    762 
    763 	if (ps.spaced_expr_psym == psym_0) {
    764 		parse(psym_stmt);
    765 		ps.force_nl = true;
    766 	}
    767 }
    768 
    769 static void
    770 process_lbrace(void)
    771 {
    772 	ps.in_stmt_or_decl = false;	/* don't indent the {} */
    773 
    774 	if (!ps.block_init)
    775 		ps.force_nl = true;
    776 	else if (ps.block_init_level <= 0)
    777 		ps.block_init_level = 1;
    778 	else
    779 		ps.block_init_level++;
    780 
    781 	if (code.len > 0 && !ps.block_init) {
    782 		if (!opt.brace_same_line ||
    783 		    (code.len > 0 && code.mem[code.len - 1] == '}'))
    784 			output_line();
    785 		else if (ps.in_func_def_params && !ps.init_or_struct) {
    786 			ps.ind_level_follow = 0;
    787 			if (opt.function_brace_split)
    788 				output_line();
    789 			else
    790 				ps.want_blank = true;
    791 		}
    792 	}
    793 
    794 	if (ps.nparen > 0) {
    795 		diag(1, "Unbalanced parentheses");
    796 		ps.nparen = 0;
    797 		if (ps.spaced_expr_psym != psym_0) {
    798 			parse(ps.spaced_expr_psym);
    799 			ps.spaced_expr_psym = psym_0;
    800 			ps.ind_level = ps.ind_level_follow;
    801 		}
    802 	}
    803 
    804 	if (code.len == 0)
    805 		ps.in_stmt_cont = false;	/* don't indent the '{' itself
    806 						 */
    807 	if (ps.in_decl && ps.init_or_struct) {
    808 		ps.di_stack[ps.decl_level] = ps.decl_ind;
    809 		if (++ps.decl_level == (int)array_length(ps.di_stack)) {
    810 			diag(0, "Reached internal limit of %d struct levels",
    811 			    (int)array_length(ps.di_stack));
    812 			ps.decl_level--;
    813 		}
    814 	} else {
    815 		ps.decl_on_line = false;	/* we can't be in the middle of
    816 						 * a declaration, so don't do
    817 						 * special indentation of
    818 						 * comments */
    819 		ps.in_func_def_params = false;
    820 		ps.in_decl = false;
    821 	}
    822 
    823 	ps.decl_ind = 0;
    824 	parse(psym_lbrace);
    825 	if (ps.want_blank)
    826 		buf_add_char(&code, ' ');
    827 	ps.want_blank = false;
    828 	buf_add_char(&code, '{');
    829 	ps.declaration = decl_no;
    830 }
    831 
    832 static void
    833 process_rbrace(void)
    834 {
    835 	if (ps.nparen > 0) {	/* check for unclosed if, for, else. */
    836 		diag(1, "Unbalanced parentheses");
    837 		ps.nparen = 0;
    838 		ps.spaced_expr_psym = psym_0;
    839 	}
    840 
    841 	ps.declaration = decl_no;
    842 	ps.block_init_level--;
    843 
    844 	if (code.len > 0 && !ps.block_init) {
    845 		if (opt.verbose)
    846 			diag(0, "Line broken");
    847 		output_line();
    848 	}
    849 
    850 	buf_add_char(&code, '}');
    851 	ps.want_blank = true;
    852 	ps.in_stmt_or_decl = false;
    853 	ps.in_stmt_cont = false;
    854 
    855 	if (ps.decl_level > 0) {	/* multi-level structure declaration */
    856 		ps.decl_ind = ps.di_stack[--ps.decl_level];
    857 		if (ps.decl_level == 0 && !ps.in_func_def_params) {
    858 			ps.declaration = decl_begin;
    859 			ps.decl_ind = ps.ind_level == 0
    860 			    ? opt.decl_indent : opt.local_decl_indent;
    861 		}
    862 		ps.in_decl = true;
    863 	}
    864 
    865 	if (ps.tos == 2)
    866 		out.line_kind = lk_func_end;
    867 
    868 	parse(psym_rbrace);
    869 
    870 	if (!ps.init_or_struct
    871 	    && ps.s_sym[ps.tos] != psym_do_stmt
    872 	    && ps.s_sym[ps.tos] != psym_if_expr_stmt)
    873 		ps.force_nl = true;
    874 }
    875 
    876 static void
    877 process_do(void)
    878 {
    879 	ps.in_stmt_or_decl = false;
    880 
    881 	if (code.len > 0) {	/* make sure this starts a line */
    882 		if (opt.verbose)
    883 			diag(0, "Line broken");
    884 		output_line();
    885 	}
    886 
    887 	ps.force_nl = true;
    888 	parse(psym_do);
    889 }
    890 
    891 static void
    892 process_else(void)
    893 {
    894 	ps.in_stmt_or_decl = false;
    895 
    896 	if (code.len > 0
    897 	    && !(opt.cuddle_else && code.mem[code.len - 1] == '}')) {
    898 		if (opt.verbose)
    899 			diag(0, "Line broken");
    900 		output_line();
    901 	}
    902 
    903 	ps.force_nl = true;
    904 	parse(psym_else);
    905 }
    906 
    907 static void
    908 process_type(void)
    909 {
    910 	parse(psym_decl);	/* let the parser worry about indentation */
    911 
    912 	if (ps.prev_token == lsym_rparen && ps.tos <= 1) {
    913 		if (code.len > 0)
    914 			output_line();
    915 	}
    916 
    917 	if (ps.in_func_def_params && opt.indent_parameters &&
    918 	    ps.decl_level == 0) {
    919 		ps.ind_level = ps.ind_level_follow = 1;
    920 		ps.in_stmt_cont = false;
    921 	}
    922 
    923 	ps.init_or_struct = /* maybe */ true;
    924 	ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
    925 	if (ps.decl_level <= 0)
    926 		ps.declaration = decl_begin;
    927 
    928 	int len = (int)token.len + 1;
    929 	int ind = ps.ind_level == 0 || ps.decl_level > 0
    930 	    ? opt.decl_indent	/* global variable or local member */
    931 	    : opt.local_decl_indent;	/* local variable */
    932 	ps.decl_ind = ind > 0 ? ind : len;
    933 	ps.tabs_to_var = opt.use_tabs && ind > 0;
    934 }
    935 
    936 static void
    937 process_ident(lexer_symbol lsym)
    938 {
    939 	if (ps.in_decl) {
    940 		if (lsym == lsym_funcname) {
    941 			ps.in_decl = false;
    942 			if (opt.procnames_start_line && code.len > 0)
    943 				output_line();
    944 			else if (ps.want_blank)
    945 				buf_add_char(&code, ' ');
    946 			ps.want_blank = false;
    947 
    948 		} else if (!ps.block_init && !ps.decl_indent_done &&
    949 		    ps.line_start_nparen == 0) {
    950 			if (opt.decl_indent == 0
    951 			    && code.len > 0 && code.mem[code.len - 1] == '}')
    952 				ps.decl_ind =
    953 				    ind_add(0, code.st, code.len) + 1;
    954 			code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
    955 			ps.decl_indent_done = true;
    956 			ps.want_blank = false;
    957 		}
    958 
    959 	} else if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
    960 		ps.force_nl = true;
    961 		ps.next_unary = true;
    962 		ps.in_stmt_or_decl = false;
    963 		parse(ps.spaced_expr_psym);
    964 		ps.spaced_expr_psym = psym_0;
    965 	}
    966 }
    967 
    968 static void
    969 process_period(void)
    970 {
    971 	if (code.len > 0 && code.mem[code.len - 1] == ',')
    972 		buf_add_char(&code, ' ');
    973 	buf_add_char(&code, '.');
    974 	ps.want_blank = false;
    975 }
    976 
    977 static void
    978 process_comma(void)
    979 {
    980 	ps.want_blank = code.len > 0;	/* only put blank after comma if comma
    981 					 * does not start the line */
    982 
    983 	if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
    984 	    !ps.decl_indent_done && ps.line_start_nparen == 0) {
    985 		/* indent leading commas and not the actual identifiers */
    986 		code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
    987 		ps.decl_indent_done = true;
    988 	}
    989 
    990 	buf_add_char(&code, ',');
    991 
    992 	if (ps.nparen == 0) {
    993 		if (ps.block_init_level <= 0)
    994 			ps.block_init = false;
    995 		int typical_varname_length = 8;
    996 		if (ps.break_after_comma && (opt.break_after_comma ||
    997 		    ind_add(compute_code_indent(), code.st, code.len)
    998 		    >= opt.max_line_length - typical_varname_length))
    999 			ps.force_nl = true;
   1000 	}
   1001 }
   1002 
   1003 /* move the whole line to the 'label' buffer */
   1004 static void
   1005 read_preprocessing_line(void)
   1006 {
   1007 	enum {
   1008 		PLAIN, STR, CHR, COMM
   1009 	} state = PLAIN;
   1010 
   1011 	buf_add_char(&lab, '#');
   1012 
   1013 	while (ch_isblank(inp.st[0]))
   1014 		buf_add_char(&lab, *inp.st++);
   1015 
   1016 	while (inp.st[0] != '\n' || (state == COMM && !had_eof)) {
   1017 		buf_add_char(&lab, inp_next());
   1018 		switch (lab.mem[lab.len - 1]) {
   1019 		case '\\':
   1020 			if (state != COMM)
   1021 				buf_add_char(&lab, inp_next());
   1022 			break;
   1023 		case '/':
   1024 			if (inp.st[0] == '*' && state == PLAIN) {
   1025 				state = COMM;
   1026 				buf_add_char(&lab, *inp.st++);
   1027 			}
   1028 			break;
   1029 		case '"':
   1030 			if (state == STR)
   1031 				state = PLAIN;
   1032 			else if (state == PLAIN)
   1033 				state = STR;
   1034 			break;
   1035 		case '\'':
   1036 			if (state == CHR)
   1037 				state = PLAIN;
   1038 			else if (state == PLAIN)
   1039 				state = CHR;
   1040 			break;
   1041 		case '*':
   1042 			if (inp.st[0] == '/' && state == COMM) {
   1043 				state = PLAIN;
   1044 				buf_add_char(&lab, *inp.st++);
   1045 			}
   1046 			break;
   1047 		}
   1048 	}
   1049 
   1050 	while (lab.len > 0 && ch_isblank(lab.mem[lab.len - 1]))
   1051 		lab.len--;
   1052 }
   1053 
   1054 static void
   1055 process_preprocessing(void)
   1056 {
   1057 	if (lab.len > 0 || code.len > 0 || com.len > 0)
   1058 		output_line();
   1059 
   1060 	read_preprocessing_line();
   1061 
   1062 	const char *end = lab.mem + lab.len;
   1063 	const char *dir = lab.st + 1;
   1064 	while (dir < end && ch_isblank(*dir))
   1065 		dir++;
   1066 	size_t dir_len = 0;
   1067 	while (dir + dir_len < end && ch_isalpha(dir[dir_len]))
   1068 		dir_len++;
   1069 
   1070 	if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
   1071 		if ((size_t)ifdef_level < array_length(state_stack))
   1072 			state_stack[ifdef_level++] = ps;
   1073 		else
   1074 			diag(1, "#if stack overflow");
   1075 		out.line_kind = lk_if;
   1076 
   1077 	} else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
   1078 		if (ifdef_level <= 0)
   1079 			diag(1, dir[2] == 'i'
   1080 			    ? "Unmatched #elif" : "Unmatched #else");
   1081 		else
   1082 			ps = state_stack[ifdef_level - 1];
   1083 
   1084 	} else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
   1085 		if (ifdef_level <= 0)
   1086 			diag(1, "Unmatched #endif");
   1087 		else
   1088 			ifdef_level--;
   1089 		out.line_kind = lk_endif;
   1090 	}
   1091 
   1092 	/* subsequent processing of the newline character will cause the line
   1093 	 * to be printed */
   1094 }
   1095 
   1096 static void
   1097 process_lsym(lexer_symbol lsym)
   1098 {
   1099 	switch (lsym) {
   1100 
   1101 	case lsym_newline:
   1102 		process_newline();
   1103 		break;
   1104 
   1105 	case lsym_lparen:
   1106 		process_lparen();
   1107 		break;
   1108 
   1109 	case lsym_lbracket:
   1110 		process_lbracket();
   1111 		break;
   1112 
   1113 	case lsym_rparen:
   1114 		process_rparen();
   1115 		break;
   1116 
   1117 	case lsym_rbracket:
   1118 		process_rbracket();
   1119 		break;
   1120 
   1121 	case lsym_unary_op:
   1122 		process_unary_op();
   1123 		break;
   1124 
   1125 	case lsym_binary_op:
   1126 		process_binary_op();
   1127 		break;
   1128 
   1129 	case lsym_postfix_op:
   1130 		process_postfix_op();
   1131 		break;
   1132 
   1133 	case lsym_question:
   1134 		process_question();
   1135 		break;
   1136 
   1137 	case lsym_case_label:
   1138 		ps.seen_case = true;
   1139 		goto copy_token;
   1140 
   1141 	case lsym_colon:
   1142 		process_colon();
   1143 		break;
   1144 
   1145 	case lsym_semicolon:
   1146 		process_semicolon();
   1147 		break;
   1148 
   1149 	case lsym_lbrace:
   1150 		process_lbrace();
   1151 		break;
   1152 
   1153 	case lsym_rbrace:
   1154 		process_rbrace();
   1155 		break;
   1156 
   1157 	case lsym_switch:
   1158 		ps.spaced_expr_psym = psym_switch_expr;
   1159 		goto copy_token;
   1160 
   1161 	case lsym_for:
   1162 		ps.spaced_expr_psym = psym_for_exprs;
   1163 		goto copy_token;
   1164 
   1165 	case lsym_if:
   1166 		ps.spaced_expr_psym = psym_if_expr;
   1167 		goto copy_token;
   1168 
   1169 	case lsym_while:
   1170 		ps.spaced_expr_psym = psym_while_expr;
   1171 		goto copy_token;
   1172 
   1173 	case lsym_do:
   1174 		process_do();
   1175 		goto copy_token;
   1176 
   1177 	case lsym_else:
   1178 		process_else();
   1179 		goto copy_token;
   1180 
   1181 	case lsym_typedef:
   1182 	case lsym_storage_class:
   1183 		goto copy_token;
   1184 
   1185 	case lsym_tag:
   1186 		if (ps.nparen > 0)
   1187 			goto copy_token;
   1188 		/* FALLTHROUGH */
   1189 	case lsym_type_outside_parentheses:
   1190 		process_type();
   1191 		goto copy_token;
   1192 
   1193 	case lsym_type_in_parentheses:
   1194 	case lsym_offsetof:
   1195 	case lsym_sizeof:
   1196 	case lsym_word:
   1197 	case lsym_funcname:
   1198 	case lsym_return:
   1199 		process_ident(lsym);
   1200 	copy_token:
   1201 		if (ps.want_blank)
   1202 			buf_add_char(&code, ' ');
   1203 		buf_add_buf(&code, &token);
   1204 		if (lsym != lsym_funcname)
   1205 			ps.want_blank = true;
   1206 		break;
   1207 
   1208 	case lsym_period:
   1209 		process_period();
   1210 		break;
   1211 
   1212 	case lsym_comma:
   1213 		process_comma();
   1214 		break;
   1215 
   1216 	case lsym_preprocessing:
   1217 		process_preprocessing();
   1218 		break;
   1219 
   1220 	case lsym_comment:
   1221 		process_comment();
   1222 		break;
   1223 
   1224 	default:
   1225 		break;
   1226 	}
   1227 }
   1228 
   1229 static int
   1230 indent(void)
   1231 {
   1232 	debug_parser_state();
   1233 
   1234 	for (;;) {		/* loop until we reach eof */
   1235 		lexer_symbol lsym = lexi();
   1236 
   1237 		debug_blank_line();
   1238 		debug_printf("line %d: %s", line_no, lsym_name[lsym]);
   1239 		debug_print_buf("token", &token);
   1240 		debug_buffers();
   1241 		debug_blank_line();
   1242 
   1243 		if (lsym == lsym_eof)
   1244 			return process_eof();
   1245 
   1246 		if (lsym == lsym_if && ps.prev_token == lsym_else
   1247 		    && opt.else_if)
   1248 			ps.force_nl = false;
   1249 
   1250 		if (lsym == lsym_newline || lsym == lsym_preprocessing)
   1251 			ps.force_nl = false;
   1252 		else if (lsym == lsym_comment) {
   1253 			/* no special processing */
   1254 		} else {
   1255 			maybe_break_line(lsym);
   1256 			/*
   1257 			 * Add an extra level of indentation; turned off again
   1258 			 * by a ';' or '}'.
   1259 			 */
   1260 			ps.in_stmt_or_decl = true;
   1261 			if (com.len > 0)
   1262 				move_com_to_code(lsym);
   1263 			update_ps_decl_ptr(lsym);
   1264 			update_ps_in_enum(lsym);
   1265 		}
   1266 
   1267 		process_lsym(lsym);
   1268 
   1269 		debug_parser_state();
   1270 
   1271 		if (lsym != lsym_comment && lsym != lsym_newline &&
   1272 		    lsym != lsym_preprocessing)
   1273 			ps.prev_token = lsym;
   1274 	}
   1275 }
   1276 
   1277 int
   1278 main(int argc, char **argv)
   1279 {
   1280 	init_globals();
   1281 	load_profiles(argc, argv);
   1282 	parse_command_line(argc, argv);
   1283 	set_initial_indentation();
   1284 	return indent();
   1285 }
   1286