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