Home | History | Annotate | Line # | Download | only in indent
io.c revision 1.77
      1 /*	$NetBSD: io.c,v 1.77 2021/10/07 21:52:54 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.77 2021/10/07 21:52:54 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_col;
    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_col = 1 + 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_col = 1 + indentation_after(cur_col - 1, lab.s);
    188 	} else
    189 	    cur_col = 1;	/* 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 	    {
    201 		int i;
    202 
    203 		for (i = 0; i < ps.p_l_follow; i++) {
    204 		    if (ps.paren_indents[i] >= 0) {
    205 			int ind = ps.paren_indents[i];
    206 			/*
    207 			 * XXX: this mix of 'indent' and 'column' smells like
    208 			 * an off-by-one error.
    209 			 */
    210 			ps.paren_indents[i] = (short)-(ind + target_col);
    211 			debug_println(
    212 			    "setting pi[%d] from %d to %d for column %d",
    213 			    i, ind, ps.paren_indents[i], target_col);
    214 		    }
    215 		}
    216 	    }
    217 
    218 	    cur_col = 1 + output_indent(cur_col - 1, target_col - 1);
    219 	    output_range(code.s, code.e);
    220 	    cur_col = 1 + indentation_after(cur_col - 1, code.s);
    221 	}
    222 
    223 	if (com.s != com.e) {	/* print comment, if any */
    224 	    int target_col = ps.com_col;
    225 	    char *com_st = com.s;
    226 
    227 	    target_col += ps.comment_delta;
    228 	    while (*com_st == '\t')	/* consider original indentation in
    229 					 * case this is a box comment */
    230 		com_st++, target_col += opt.tabsize;
    231 	    while (target_col <= 0)
    232 		if (*com_st == ' ')
    233 		    target_col++, com_st++;
    234 		else if (*com_st == '\t') {
    235 		    target_col = opt.tabsize * (1 + (target_col - 1) / opt.tabsize) + 1;
    236 		    com_st++;
    237 		} else
    238 		    target_col = 1;
    239 	    if (cur_col > target_col) {	/* if comment can't fit on this line,
    240 					 * put it on next line */
    241 		output_char('\n');
    242 		cur_col = 1;
    243 		ps.stats.lines++;
    244 	    }
    245 	    while (com.e > com_st && isspace((unsigned char)com.e[-1]))
    246 		com.e--;
    247 	    (void)output_indent(cur_col - 1, target_col - 1);
    248 	    output_range(com_st, com.e);
    249 	    ps.comment_delta = ps.n_comment_delta;
    250 	    ps.stats.comment_lines++;
    251 	}
    252 
    253 	if (ps.use_ff)
    254 	    output_char('\f');
    255 	else
    256 	    output_char('\n');
    257 	ps.stats.lines++;
    258 
    259 	if (ps.just_saw_decl == 1 && opt.blanklines_after_declarations) {
    260 	    prefix_blankline_requested = true;
    261 	    ps.just_saw_decl = 0;
    262 	} else
    263 	    prefix_blankline_requested = postfix_blankline_requested;
    264 	postfix_blankline_requested = false;
    265     }
    266 
    267     /* keep blank lines after '//' comments */
    268     if (com.e - com.s > 1 && com.s[1] == '/'
    269 	&& token.s < token.e && isspace((unsigned char)token.s[0]))
    270 	output_range(token.s, token.e);
    271 
    272     ps.decl_on_line = ps.in_decl;	/* for proper comment indentation */
    273     ps.ind_stmt = ps.in_stmt && !ps.in_decl;
    274     ps.use_ff = false;
    275     ps.dumped_decl_indent = false;
    276 
    277     *(lab.e = lab.s) = '\0';	/* reset buffers */
    278     *(code.e = code.s) = '\0';
    279     *(com.e = com.s = com.buf + 1) = '\0';
    280 
    281     ps.ind_level = ps.ind_level_follow;
    282     ps.paren_level = ps.p_l_follow;
    283 
    284     if (ps.paren_level > 0) {
    285 	/* TODO: explain what negative indentation means */
    286 	paren_indent = -ps.paren_indents[ps.paren_level - 1];
    287 	debug_println("paren_indent is now %d", paren_indent);
    288     }
    289 
    290     not_first_line = true;
    291 }
    292 
    293 int
    294 compute_code_indent(void)
    295 {
    296     int target_ind = opt.indent_size * ps.ind_level;
    297 
    298     if (ps.paren_level != 0) {
    299 	if (!opt.lineup_to_parens)
    300 	    if (2 * opt.continuation_indent == opt.indent_size)
    301 		target_ind += opt.continuation_indent;
    302 	    else
    303 		target_ind += opt.continuation_indent * ps.paren_level;
    304 
    305 	else if (opt.lineup_to_parens_always)
    306 	    /*
    307 	     * XXX: where does this '- 1' come from?  It looks strange but is
    308 	     * nevertheless needed for proper indentation, as demonstrated in
    309 	     * the test opt-lpl.0.
    310 	     */
    311 	    target_ind = paren_indent - 1;
    312 
    313 	else {
    314 	    int w;
    315 	    int t = paren_indent;
    316 
    317 	    if ((w = 1 + indentation_after(t - 1, code.s) - opt.max_line_length) > 0
    318 		&& 1 + indentation_after(target_ind, code.s) <= opt.max_line_length) {
    319 		t -= w + 1;
    320 		if (t > target_ind + 1)
    321 		    target_ind = t - 1;
    322 	    } else
    323 		target_ind = t - 1;
    324 	}
    325 
    326     } else if (ps.ind_stmt)
    327 	target_ind += opt.continuation_indent;
    328 
    329     return target_ind;
    330 }
    331 
    332 int
    333 compute_label_indent(void)
    334 {
    335     if (ps.is_case_label)
    336 	return (int)(case_ind * (float)opt.indent_size);
    337     if (lab.s[0] == '#')
    338 	return 0;
    339     return opt.indent_size * (ps.ind_level - label_offset);
    340 }
    341 
    342 static void
    343 skip_hspace(const char **pp)
    344 {
    345     while (is_hspace(**pp))
    346 	(*pp)++;
    347 }
    348 
    349 static bool
    350 skip_string(const char **pp, const char *s)
    351 {
    352     size_t len = strlen(s);
    353     if (strncmp(*pp, s, len) == 0) {
    354 	*pp += len;
    355 	return true;
    356     }
    357     return false;
    358 }
    359 
    360 static void
    361 parse_indent_comment(void)
    362 {
    363     bool on_off;
    364 
    365     const char *p = in_buffer;
    366 
    367     skip_hspace(&p);
    368     if (!skip_string(&p, "/*"))
    369 	return;
    370     skip_hspace(&p);
    371     if (!skip_string(&p, "INDENT"))
    372 	return;
    373     skip_hspace(&p);
    374 
    375     if (*p == '*' || skip_string(&p, "ON"))
    376 	on_off = true;
    377     else if (skip_string(&p, "OFF"))
    378 	on_off = false;
    379     else
    380 	return;
    381 
    382     skip_hspace(&p);
    383     if (!skip_string(&p, "*/\n"))
    384 	return;
    385 
    386     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
    387 	dump_line();
    388 
    389     inhibit_formatting = !on_off;
    390     if (on_off) {
    391 	next_blank_lines = 0;
    392 	postfix_blankline_requested = false;
    393 	prefix_blankline_requested = false;
    394 	suppress_blanklines = 1;
    395     }
    396 }
    397 
    398 /*
    399  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
    400  *
    401  * All rights reserved
    402  *
    403  * FUNCTION: Reads one block of input into the input buffer
    404  */
    405 void
    406 fill_buffer(void)
    407 {
    408     /* this routine reads stuff from the input */
    409     char *p;
    410     int ch;
    411     FILE *f = input;
    412 
    413     if (bp_save != NULL) {	/* there is a partly filled input buffer left */
    414 	buf_ptr = bp_save;	/* do not read anything, just switch buffers */
    415 	buf_end = be_save;
    416 	bp_save = be_save = NULL;
    417 	debug_println("switched buf_ptr back to bp_save");
    418 	if (buf_ptr < buf_end)
    419 	    return;		/* only return if there is really something in
    420 				 * this buffer */
    421     }
    422 
    423     for (p = in_buffer;;) {
    424 	if (p >= in_buffer_limit) {
    425 	    size_t size = (size_t)(in_buffer_limit - in_buffer) * 2 + 10;
    426 	    size_t offset = (size_t)(p - in_buffer);
    427 	    in_buffer = xrealloc(in_buffer, size);
    428 	    p = in_buffer + offset;
    429 	    in_buffer_limit = in_buffer + size - 2;
    430 	}
    431 
    432 	if ((ch = getc(f)) == EOF) {
    433 	    *p++ = ' ';
    434 	    *p++ = '\n';
    435 	    had_eof = true;
    436 	    break;
    437 	}
    438 
    439 	if (ch != '\0')
    440 	    *p++ = (char)ch;
    441 	if (ch == '\n')
    442 	    break;
    443     }
    444 
    445     buf_ptr = in_buffer;
    446     buf_end = p;
    447 
    448     if (p - in_buffer > 2 && p[-2] == '/' && p[-3] == '*') {
    449 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
    450 	    fill_buffer();	/* flush indent error message */
    451 	else
    452 	    parse_indent_comment();
    453     }
    454 
    455     if (inhibit_formatting) {
    456 	p = in_buffer;
    457 	do {
    458 	    output_char(*p);
    459 	} while (*p++ != '\n');
    460     }
    461 }
    462 
    463 int
    464 indentation_after_range(int ind, const char *start, const char *end)
    465 {
    466     for (const char *p = start; *p != '\0' && p != end; ++p) {
    467 	if (*p == '\n' || *p == '\f')
    468 	    ind = 0;
    469 	else if (*p == '\t')
    470 	    ind = opt.tabsize * (ind / opt.tabsize + 1);
    471 	else if (*p == '\b')
    472 	    --ind;
    473 	else
    474 	    ++ind;
    475     }
    476     return ind;
    477 }
    478 
    479 int
    480 indentation_after(int ind, const char *s)
    481 {
    482     return indentation_after_range(ind, s, NULL);
    483 }
    484 
    485 void
    486 diag(int level, const char *msg, ...)
    487 {
    488     va_list ap;
    489     const char *s, *e;
    490 
    491     if (level != 0)
    492 	found_err = true;
    493 
    494     if (output == stdout) {
    495 	s = "/**INDENT** ";
    496 	e = " */";
    497     } else {
    498 	s = e = "";
    499     }
    500 
    501     va_start(ap, msg);
    502     fprintf(stderr, "%s%s@%d: ", s, level == 0 ? "Warning" : "Error", line_no);
    503     vfprintf(stderr, msg, ap);
    504     fprintf(stderr, "%s\n", e);
    505     va_end(ap);
    506 }
    507