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