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