Home | History | Annotate | Line # | Download | only in indent
io.c revision 1.83
      1 /*	$NetBSD: io.c,v 1.83 2021/10/08 17:07:36 rillig Exp $	*/
      2 
      3 /*-
      4  * SPDX-License-Identifier: BSD-4-Clause
      5  *
      6  * Copyright (c) 1985 Sun Microsystems, Inc.
      7  * Copyright (c) 1980, 1993
      8  *	The Regents of the University of California.  All rights reserved.
      9  * 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[] = "@(#)io.c	8.1 (Berkeley) 6/6/93";
     42 #endif
     43 
     44 #include <sys/cdefs.h>
     45 #if defined(__NetBSD__)
     46 __RCSID("$NetBSD: io.c,v 1.83 2021/10/08 17:07:36 rillig Exp $");
     47 #elif defined(__FreeBSD__)
     48 __FBSDID("$FreeBSD: head/usr.bin/indent/io.c 334927 2018-06-10 16:44:18Z pstef $");
     49 #endif
     50 
     51 #include <ctype.h>
     52 #include <stdio.h>
     53 #include <string.h>
     54 #include <stdarg.h>
     55 
     56 #include "indent.h"
     57 
     58 static bool comment_open;
     59 static int paren_indent;
     60 static int suppress_blanklines;
     61 
     62 static void
     63 output_char(char ch)
     64 {
     65     fputc(ch, output);
     66     debug_vis_range("output_char '", &ch, &ch + 1, "'\n");
     67 }
     68 
     69 static void
     70 output_range(const char *s, const char *e)
     71 {
     72     fwrite(s, 1, (size_t)(e - s), output);
     73     debug_vis_range("output_range \"", s, e, "\"\n");
     74 }
     75 
     76 static inline void
     77 output_string(const char *s)
     78 {
     79     output_range(s, s + strlen(s));
     80 }
     81 
     82 static int
     83 output_indent(int old_ind, int new_ind)
     84 {
     85     int ind = old_ind;
     86 
     87     if (opt.use_tabs) {
     88 	int tabsize = opt.tabsize;
     89 	int n = new_ind / tabsize - ind / tabsize;
     90 	if (n > 0)
     91 	    ind -= ind % tabsize;
     92 	for (int i = 0; i < n; i++) {
     93 	    fputc('\t', output);
     94 	    ind += tabsize;
     95 	}
     96     }
     97 
     98     for (; ind < new_ind; ind++)
     99 	fputc(' ', output);
    100 
    101     debug_println("output_indent %d", ind);
    102     return ind;
    103 }
    104 
    105 /*
    106  * dump_line is the routine that actually effects the printing of the new
    107  * source. It prints the label section, followed by the code section with
    108  * the appropriate nesting level, followed by any comments.
    109  */
    110 void
    111 dump_line(void)
    112 {
    113     int cur_ind;
    114     static bool not_first_line;
    115 
    116     if (ps.procname[0] != '\0') {
    117 	ps.ind_level = 0;
    118 	ps.procname[0] = '\0';
    119     }
    120 
    121     if (code.s == code.e && lab.s == lab.e && com.s == com.e) {
    122 	if (suppress_blanklines > 0)
    123 	    suppress_blanklines--;
    124 	else
    125 	    next_blank_lines++;
    126 
    127     } else if (!inhibit_formatting) {
    128 	suppress_blanklines = 0;
    129 	if (prefix_blankline_requested && not_first_line) {
    130 	    if (opt.swallow_optional_blanklines) {
    131 		if (next_blank_lines == 1)
    132 		    next_blank_lines = 0;
    133 	    } else {
    134 		if (next_blank_lines == 0)
    135 		    next_blank_lines = 1;
    136 	    }
    137 	}
    138 
    139 	while (--next_blank_lines >= 0)
    140 	    output_char('\n');
    141 	next_blank_lines = 0;
    142 
    143 	if (ps.ind_level == 0)
    144 	    ps.ind_stmt = false;	/* this is a class A kludge. don't do
    145 					 * additional statement indentation if
    146 					 * we are at bracket level 0 */
    147 
    148 	if (lab.e != lab.s || code.e != code.s)
    149 	    ps.stats.code_lines++;
    150 
    151 	if (lab.e != lab.s) {	/* print lab, if any */
    152 	    if (comment_open) {
    153 		comment_open = false;
    154 		output_string(".*/\n");
    155 	    }
    156 
    157 	    while (lab.e > lab.s && is_hspace(lab.e[-1]))
    158 		lab.e--;
    159 	    *lab.e = '\0';
    160 
    161 	    cur_ind = output_indent(0, compute_label_indent());
    162 
    163 	    if (lab.s[0] == '#' && (strncmp(lab.s, "#else", 5) == 0
    164 		    || strncmp(lab.s, "#endif", 6) == 0)) {
    165 		char *s = lab.s;
    166 		if (lab.e[-1] == '\n')
    167 		    lab.e--;
    168 		do {
    169 		    output_char(*s++);
    170 		} while (s < lab.e && 'a' <= *s && *s <= 'z');
    171 
    172 		while (s < lab.e && is_hspace(*s))
    173 		    s++;
    174 
    175 		if (s < lab.e) {
    176 		    if (s[0] == '/' && s[1] == '*') {
    177 			output_char('\t');
    178 			output_range(s, lab.e);
    179 		    } else {
    180 			output_string("\t/* ");
    181 			output_range(s, lab.e);
    182 			output_string(" */");
    183 		    }
    184 		}
    185 	    } else
    186 		output_range(lab.s, lab.e);
    187 	    cur_ind = indentation_after(cur_ind, lab.s);
    188 	} else
    189 	    cur_ind = 0;	/* there is no label section */
    190 
    191 	ps.is_case_label = false;
    192 
    193 	if (code.s != code.e) {	/* print code section, if any */
    194 	    if (comment_open) {
    195 		comment_open = false;
    196 		output_string(".*/\n");
    197 	    }
    198 
    199 	    int target_col = 1 + compute_code_indent();
    200 	    for (int i = 0; i < ps.p_l_follow; i++) {
    201 		if (ps.paren_indents[i] >= 0) {
    202 		    int ind = ps.paren_indents[i];
    203 		    /*
    204 		     * XXX: this mix of 'indent' and 'column' smells like
    205 		     * an off-by-one error.
    206 		     */
    207 		    ps.paren_indents[i] = (short)-(ind + target_col);
    208 		    debug_println(
    209 			"setting pi[%d] from %d to %d for column %d",
    210 			i, ind, ps.paren_indents[i], target_col);
    211 		}
    212 	    }
    213 
    214 	    cur_ind = output_indent(cur_ind, target_col - 1);
    215 	    output_range(code.s, code.e);
    216 	    cur_ind = indentation_after(cur_ind, code.s);
    217 	}
    218 
    219 	if (com.s != com.e) {	/* print comment, if any */
    220 	    int target_ind = ps.com_col - 1;
    221 	    char *com_st = com.s;
    222 
    223 	    target_ind += ps.comment_delta;
    224 	    while (*com_st == '\t')	/* consider original indentation in
    225 					 * case this is a box comment */
    226 		com_st++, target_ind += opt.tabsize;
    227 	    while (target_ind < 0) {
    228 		if (*com_st == ' ')
    229 		    target_ind++, com_st++;
    230 		else if (*com_st == '\t') {
    231 		    target_ind = opt.tabsize * (1 + target_ind / opt.tabsize);
    232 		    com_st++;
    233 		} else
    234 		    target_ind = 0;
    235 	    }
    236 	    if (cur_ind > target_ind) {	/* if comment can't fit on this line,
    237 					 * put it on next line */
    238 		output_char('\n');
    239 		cur_ind = 0;
    240 		ps.stats.lines++;
    241 	    }
    242 	    while (com.e > com_st && isspace((unsigned char)com.e[-1]))
    243 		com.e--;
    244 	    (void)output_indent(cur_ind, target_ind);
    245 	    output_range(com_st, com.e);
    246 	    ps.comment_delta = ps.n_comment_delta;
    247 	    ps.stats.comment_lines++;
    248 	}
    249 
    250 	if (ps.use_ff)
    251 	    output_char('\f');
    252 	else
    253 	    output_char('\n');
    254 	ps.stats.lines++;
    255 
    256 	if (ps.just_saw_decl == 1 && opt.blanklines_after_declarations) {
    257 	    prefix_blankline_requested = true;
    258 	    ps.just_saw_decl = 0;
    259 	} else
    260 	    prefix_blankline_requested = postfix_blankline_requested;
    261 	postfix_blankline_requested = false;
    262     }
    263 
    264     /* keep blank lines after '//' comments */
    265     if (com.e - com.s > 1 && com.s[1] == '/'
    266 	&& token.s < token.e && isspace((unsigned char)token.s[0]))
    267 	output_range(token.s, token.e);
    268 
    269     ps.decl_on_line = ps.in_decl;	/* for proper comment indentation */
    270     ps.ind_stmt = ps.in_stmt && !ps.in_decl;
    271     ps.use_ff = false;
    272     ps.dumped_decl_indent = false;
    273 
    274     *(lab.e = lab.s) = '\0';	/* reset buffers */
    275     *(code.e = code.s) = '\0';
    276     *(com.e = com.s = com.buf + 1) = '\0';
    277 
    278     ps.ind_level = ps.ind_level_follow;
    279     ps.paren_level = ps.p_l_follow;
    280 
    281     if (ps.paren_level > 0) {
    282 	/* TODO: explain what negative indentation means */
    283 	paren_indent = -ps.paren_indents[ps.paren_level - 1];
    284 	debug_println("paren_indent is now %d", paren_indent);
    285     }
    286 
    287     not_first_line = true;
    288 }
    289 
    290 int
    291 compute_code_indent(void)
    292 {
    293     int target_ind = opt.indent_size * ps.ind_level;
    294 
    295     if (ps.paren_level != 0) {
    296 	if (!opt.lineup_to_parens) {
    297 	    if (2 * opt.continuation_indent == opt.indent_size)
    298 		target_ind += opt.continuation_indent;
    299 	    else
    300 		target_ind += opt.continuation_indent * ps.paren_level;
    301 
    302 	} else if (opt.lineup_to_parens_always) {
    303 	    /*
    304 	     * XXX: where does this '- 1' come from?  It looks strange but is
    305 	     * nevertheless needed for proper indentation, as demonstrated in
    306 	     * the test opt-lpl.0.
    307 	     */
    308 	    target_ind = paren_indent - 1;
    309 
    310 	} else {
    311 	    int w;
    312 	    int t = paren_indent;
    313 
    314 	    if ((w = 1 + indentation_after(t - 1, code.s) - opt.max_line_length) > 0
    315 		&& 1 + indentation_after(target_ind, code.s) <= opt.max_line_length) {
    316 		t -= w + 1;
    317 		if (t > target_ind + 1)
    318 		    target_ind = t - 1;
    319 	    } else
    320 		target_ind = t - 1;
    321 	}
    322 
    323     } else if (ps.ind_stmt)
    324 	target_ind += opt.continuation_indent;
    325 
    326     return target_ind;
    327 }
    328 
    329 int
    330 compute_label_indent(void)
    331 {
    332     if (ps.is_case_label)
    333 	return (int)(case_ind * (float)opt.indent_size);
    334     if (lab.s[0] == '#')
    335 	return 0;
    336     return opt.indent_size * (ps.ind_level - label_offset);
    337 }
    338 
    339 static void
    340 skip_hspace(const char **pp)
    341 {
    342     while (is_hspace(**pp))
    343 	(*pp)++;
    344 }
    345 
    346 static bool
    347 skip_string(const char **pp, const char *s)
    348 {
    349     size_t len = strlen(s);
    350     if (strncmp(*pp, s, len) == 0) {
    351 	*pp += len;
    352 	return true;
    353     }
    354     return false;
    355 }
    356 
    357 static void
    358 parse_indent_comment(void)
    359 {
    360     bool on_off;
    361 
    362     const char *p = inp.buf;
    363 
    364     skip_hspace(&p);
    365     if (!skip_string(&p, "/*"))
    366 	return;
    367     skip_hspace(&p);
    368     if (!skip_string(&p, "INDENT"))
    369 	return;
    370     skip_hspace(&p);
    371 
    372     if (*p == '*' || skip_string(&p, "ON"))
    373 	on_off = true;
    374     else if (skip_string(&p, "OFF"))
    375 	on_off = false;
    376     else
    377 	return;
    378 
    379     skip_hspace(&p);
    380     if (!skip_string(&p, "*/\n"))
    381 	return;
    382 
    383     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
    384 	dump_line();
    385 
    386     inhibit_formatting = !on_off;
    387     if (on_off) {
    388 	next_blank_lines = 0;
    389 	postfix_blankline_requested = false;
    390 	prefix_blankline_requested = false;
    391 	suppress_blanklines = 1;
    392     }
    393 }
    394 
    395 /*
    396  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
    397  *
    398  * All rights reserved
    399  *
    400  * FUNCTION: Reads one block of input into the input buffer
    401  */
    402 void
    403 fill_buffer(void)
    404 {
    405     /* this routine reads stuff from the input */
    406     char *p;
    407     int ch;
    408     FILE *f = input;
    409 
    410     if (saved_inp_s != NULL) {	/* there is a partly filled input buffer left */
    411 	inp.s = saved_inp_s;	/* do not read anything, just switch buffers */
    412 	inp.e = saved_inp_e;
    413 	saved_inp_s = saved_inp_e = NULL;
    414 	debug_println("switched inp.s back to saved_inp_s");
    415 	if (inp.s < inp.e)
    416 	    return;		/* only return if there is really something in
    417 				 * this buffer */
    418     }
    419 
    420     for (p = inp.buf;;) {
    421 	if (p >= inp.l) {
    422 	    size_t size = (size_t)(inp.l - inp.buf) * 2 + 10;
    423 	    size_t offset = (size_t)(p - inp.buf);
    424 	    inp.buf = xrealloc(inp.buf, size);
    425 	    p = inp.buf + offset;
    426 	    inp.l = inp.buf + size - 2;
    427 	}
    428 
    429 	if ((ch = getc(f)) == EOF) {
    430 	    *p++ = ' ';
    431 	    *p++ = '\n';
    432 	    had_eof = true;
    433 	    break;
    434 	}
    435 
    436 	if (ch != '\0')
    437 	    *p++ = (char)ch;
    438 	if (ch == '\n')
    439 	    break;
    440     }
    441 
    442     inp.s = inp.buf;
    443     inp.e = p;
    444 
    445     if (p - inp.buf > 2 && p[-2] == '/' && p[-3] == '*') {
    446 	if (inp.buf[3] == 'I' && strncmp(inp.buf, "/**INDENT**", 11) == 0)
    447 	    fill_buffer();	/* flush indent error message */
    448 	else
    449 	    parse_indent_comment();
    450     }
    451 
    452     if (inhibit_formatting) {
    453 	p = inp.buf;
    454 	do {
    455 	    output_char(*p);
    456 	} while (*p++ != '\n');
    457     }
    458 }
    459 
    460 int
    461 indentation_after_range(int ind, const char *start, const char *end)
    462 {
    463     for (const char *p = start; *p != '\0' && p != end; ++p) {
    464 	if (*p == '\n' || *p == '\f')
    465 	    ind = 0;
    466 	else if (*p == '\t')
    467 	    ind = opt.tabsize * (ind / opt.tabsize + 1);
    468 	else if (*p == '\b')
    469 	    --ind;
    470 	else
    471 	    ++ind;
    472     }
    473     return ind;
    474 }
    475 
    476 int
    477 indentation_after(int ind, const char *s)
    478 {
    479     return indentation_after_range(ind, s, NULL);
    480 }
    481 
    482 void
    483 diag(int level, const char *msg, ...)
    484 {
    485     va_list ap;
    486     const char *s, *e;
    487 
    488     if (level != 0)
    489 	found_err = true;
    490 
    491     if (output == stdout) {
    492 	s = "/**INDENT** ";
    493 	e = " */";
    494     } else {
    495 	s = e = "";
    496     }
    497 
    498     va_start(ap, msg);
    499     fprintf(stderr, "%s%s@%d: ", s, level == 0 ? "Warning" : "Error", line_no);
    500     vfprintf(stderr, msg, ap);
    501     fprintf(stderr, "%s\n", e);
    502     va_end(ap);
    503 }
    504