Home | History | Annotate | Line # | Download | only in indent
io.c revision 1.71
      1 /*	$NetBSD: io.c,v 1.71 2021/10/05 06:24:06 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.71 2021/10/05 06:24:06 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 	    n_real_blanklines++;
    126     } else if (!inhibit_formatting) {
    127 	suppress_blanklines = 0;
    128 	if (prefix_blankline_requested && not_first_line) {
    129 	    if (opt.swallow_optional_blanklines) {
    130 		if (n_real_blanklines == 1)
    131 		    n_real_blanklines = 0;
    132 	    } else {
    133 		if (n_real_blanklines == 0)
    134 		    n_real_blanklines = 1;
    135 	    }
    136 	}
    137 	while (--n_real_blanklines >= 0)
    138 	    output_char('\n');
    139 	n_real_blanklines = 0;
    140 	if (ps.ind_level == 0)
    141 	    ps.ind_stmt = false;	/* this is a class A kludge. don't do
    142 					 * additional statement indentation if
    143 					 * we are at bracket level 0 */
    144 
    145 	if (lab.e != lab.s || code.e != code.s)
    146 	    ps.stats.code_lines++;
    147 
    148 
    149 	if (lab.e != lab.s) {	/* print lab, if any */
    150 	    if (comment_open) {
    151 		comment_open = false;
    152 		output_string(".*/\n");
    153 	    }
    154 	    while (lab.e > lab.s && is_hspace(lab.e[-1]))
    155 		lab.e--;
    156 	    *lab.e = '\0';
    157 	    cur_col = 1 + output_indent(0, compute_label_indent());
    158 	    if (lab.s[0] == '#' && (strncmp(lab.s, "#else", 5) == 0
    159 		    || strncmp(lab.s, "#endif", 6) == 0)) {
    160 		char *s = lab.s;
    161 		if (lab.e[-1] == '\n')
    162 		    lab.e--;
    163 		do {
    164 		    output_char(*s++);
    165 		} while (s < lab.e && 'a' <= *s && *s <= 'z');
    166 		while (s < lab.e && is_hspace(*s))
    167 		    s++;
    168 		if (s < lab.e) {
    169 		    if (s[0] == '/' && s[1] == '*') {
    170 			output_char('\t');
    171 			output_range(s, lab.e);
    172 		    } else {
    173 			output_string("\t/* ");
    174 			output_range(s, lab.e);
    175 			output_string(" */");
    176 		    }
    177 		}
    178 	    } else
    179 		output_range(lab.s, lab.e);
    180 	    cur_col = 1 + indentation_after(cur_col - 1, lab.s);
    181 	} else
    182 	    cur_col = 1;	/* there is no label section */
    183 
    184 	ps.pcase = false;
    185 
    186 	if (code.s != code.e) {	/* print code section, if any */
    187 	    if (comment_open) {
    188 		comment_open = false;
    189 		output_string(".*/\n");
    190 	    }
    191 	    int target_col = 1 + compute_code_indent();
    192 	    {
    193 		int i;
    194 
    195 		for (i = 0; i < ps.p_l_follow; i++) {
    196 		    if (ps.paren_indents[i] >= 0) {
    197 			int ind = ps.paren_indents[i];
    198 			/*
    199 			 * XXX: this mix of 'indent' and 'column' smells like
    200 			 * an off-by-one error.
    201 			 */
    202 			ps.paren_indents[i] = -(ind + target_col);
    203 			debug_println(
    204 			    "setting pi[%d] from %d to %d for column %d",
    205 			    i, ind, ps.paren_indents[i], target_col);
    206 		    }
    207 		}
    208 	    }
    209 	    cur_col = 1 + output_indent(cur_col - 1, target_col - 1);
    210 	    output_range(code.s, code.e);
    211 	    cur_col = 1 + indentation_after(cur_col - 1, code.s);
    212 	}
    213 	if (com.s != com.e) {	/* print comment, if any */
    214 	    int target_col = ps.com_col;
    215 	    char *com_st = com.s;
    216 
    217 	    target_col += ps.comment_delta;
    218 	    while (*com_st == '\t')	/* consider original indentation in
    219 					 * case this is a box comment */
    220 		com_st++, target_col += opt.tabsize;
    221 	    while (target_col <= 0)
    222 		if (*com_st == ' ')
    223 		    target_col++, com_st++;
    224 		else if (*com_st == '\t') {
    225 		    target_col = opt.tabsize * (1 + (target_col - 1) / opt.tabsize) + 1;
    226 		    com_st++;
    227 		} else
    228 		    target_col = 1;
    229 	    if (cur_col > target_col) {	/* if comment can't fit on this line,
    230 					 * put it on next line */
    231 		output_char('\n');
    232 		cur_col = 1;
    233 		ps.stats.lines++;
    234 	    }
    235 	    while (com.e > com_st && isspace((unsigned char)com.e[-1]))
    236 		com.e--;
    237 	    (void)output_indent(cur_col - 1, target_col - 1);
    238 	    output_range(com_st, com.e);
    239 	    ps.comment_delta = ps.n_comment_delta;
    240 	    ps.stats.comment_lines++;
    241 	}
    242 	if (ps.use_ff)
    243 	    output_char('\f');
    244 	else
    245 	    output_char('\n');
    246 	ps.stats.lines++;
    247 	if (ps.just_saw_decl == 1 && opt.blanklines_after_declarations) {
    248 	    prefix_blankline_requested = true;
    249 	    ps.just_saw_decl = 0;
    250 	} else
    251 	    prefix_blankline_requested = postfix_blankline_requested;
    252 	postfix_blankline_requested = false;
    253     }
    254 
    255     /* keep blank lines after '//' comments */
    256     if (com.e - com.s > 1 && com.s[1] == '/'
    257 	&& token.s < token.e && isspace((unsigned char)token.s[0]))
    258 	output_range(token.s, token.e);
    259 
    260     ps.decl_on_line = ps.in_decl;	/* if we are in the middle of a
    261 					 * declaration, remember that fact for
    262 					 * proper comment indentation */
    263     ps.ind_stmt = ps.in_stmt && !ps.in_decl;	/* next line should be
    264 						 * indented if we have not
    265 						 * completed this stmt and if
    266 						 * we are not in the middle of
    267 						 * a declaration */
    268     ps.use_ff = false;
    269     ps.dumped_decl_indent = false;
    270     *(lab.e = lab.s) = '\0';	/* reset buffers */
    271     *(code.e = code.s) = '\0';
    272     *(com.e = com.s = com.buf + 1) = '\0';
    273     ps.ind_level = ps.ind_level_follow;
    274     ps.paren_level = ps.p_l_follow;
    275     if (ps.paren_level > 0) {
    276 	/* TODO: explain what negative indentation means */
    277 	paren_indent = -ps.paren_indents[ps.paren_level - 1];
    278 	debug_println("paren_indent is now %d", paren_indent);
    279     }
    280     not_first_line = true;
    281 }
    282 
    283 int
    284 compute_code_indent(void)
    285 {
    286     int target_ind = opt.indent_size * ps.ind_level;
    287 
    288     if (ps.paren_level != 0) {
    289 	if (!opt.lineup_to_parens)
    290 	    if (2 * opt.continuation_indent == opt.indent_size)
    291 		target_ind += opt.continuation_indent;
    292 	    else
    293 		target_ind += opt.continuation_indent * ps.paren_level;
    294 	else if (opt.lineup_to_parens_always)
    295 	    /*
    296 	     * XXX: where does this '- 1' come from?  It looks strange but is
    297 	     * nevertheless needed for proper indentation, as demonstrated in
    298 	     * the test opt-lpl.0.
    299 	     */
    300 	    target_ind = paren_indent - 1;
    301 	else {
    302 	    int w;
    303 	    int t = paren_indent;
    304 
    305 	    if ((w = 1 + indentation_after(t - 1, code.s) - opt.max_line_length) > 0
    306 		&& 1 + indentation_after(target_ind, code.s) <= opt.max_line_length) {
    307 		t -= w + 1;
    308 		if (t > target_ind + 1)
    309 		    target_ind = t - 1;
    310 	    } else
    311 		target_ind = t - 1;
    312 	}
    313     } else if (ps.ind_stmt)
    314 	target_ind += opt.continuation_indent;
    315     return target_ind;
    316 }
    317 
    318 int
    319 compute_label_indent(void)
    320 {
    321     if (ps.pcase)
    322 	return (int)(case_ind * opt.indent_size);
    323     if (lab.s[0] == '#')
    324 	return 0;
    325     return opt.indent_size * (ps.ind_level - label_offset);
    326 }
    327 
    328 static void
    329 skip_hspace(const char **pp)
    330 {
    331     while (is_hspace(**pp))
    332 	(*pp)++;
    333 }
    334 
    335 static void
    336 parse_indent_comment(void)
    337 {
    338     int on_off = 0;		/* 0 = keep, 1 = ON, 2 = OFF */
    339 
    340     const char *p = in_buffer;
    341 
    342     skip_hspace(&p);
    343 
    344     if (!(*p == '/' && p[1] == '*'))
    345 	return;
    346     p += 2;
    347 
    348     skip_hspace(&p);
    349 
    350     if (!(p[0] == 'I' && p[1] == 'N' && p[2] == 'D'
    351 	    && p[3] == 'E' && p[4] == 'N' && p[5] == 'T'))
    352 	return;
    353     p += 6;
    354 
    355     skip_hspace(&p);
    356 
    357     if (*p == '*')
    358 	on_off = 1;
    359     else if (*p == 'O') {
    360 	if (*++p == 'N')
    361 	    p++, on_off = 1;
    362 	else if (*p == 'F' && *++p == 'F')
    363 	    p++, on_off = 2;
    364     }
    365     if (on_off == 0)
    366 	return;
    367 
    368     skip_hspace(&p);
    369 
    370     if (!(p[0] == '*' && p[1] == '/' && p[2] == '\n'))
    371 	return;
    372 
    373     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
    374 	dump_line();
    375 
    376     if (!(inhibit_formatting = (on_off == 2))) {
    377 	n_real_blanklines = 0;
    378 	postfix_blankline_requested = false;
    379 	prefix_blankline_requested = false;
    380 	suppress_blanklines = 1;
    381     }
    382 }
    383 
    384 /*
    385  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
    386  *
    387  * All rights reserved
    388  *
    389  * FUNCTION: Reads one block of input into the input buffer
    390  */
    391 void
    392 fill_buffer(void)
    393 {
    394     /* this routine reads stuff from the input */
    395     char *p;
    396     int ch;
    397     FILE *f = input;
    398 
    399     if (bp_save != NULL) {	/* there is a partly filled input buffer left */
    400 	buf_ptr = bp_save;	/* do not read anything, just switch buffers */
    401 	buf_end = be_save;
    402 	bp_save = be_save = NULL;
    403 	debug_println("switched buf_ptr back to bp_save");
    404 	if (buf_ptr < buf_end)
    405 	    return;		/* only return if there is really something in
    406 				 * this buffer */
    407     }
    408     for (p = in_buffer;;) {
    409 	if (p >= in_buffer_limit) {
    410 	    size_t size = (in_buffer_limit - in_buffer) * 2 + 10;
    411 	    size_t offset = p - in_buffer;
    412 	    in_buffer = xrealloc(in_buffer, size);
    413 	    p = in_buffer + offset;
    414 	    in_buffer_limit = in_buffer + size - 2;
    415 	}
    416 	if ((ch = getc(f)) == EOF) {
    417 	    *p++ = ' ';
    418 	    *p++ = '\n';
    419 	    had_eof = true;
    420 	    break;
    421 	}
    422 	if (ch != '\0')
    423 	    *p++ = (char)ch;
    424 	if (ch == '\n')
    425 	    break;
    426     }
    427     buf_ptr = in_buffer;
    428     buf_end = p;
    429     if (p - in_buffer > 2 && p[-2] == '/' && p[-3] == '*') {
    430 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
    431 	    fill_buffer();	/* flush indent error message */
    432 	else
    433 	    parse_indent_comment();
    434     }
    435     if (inhibit_formatting) {
    436 	p = in_buffer;
    437 	do {
    438 	    output_char(*p);
    439 	} while (*p++ != '\n');
    440     }
    441 }
    442 
    443 int
    444 indentation_after_range(int ind, const char *start, const char *end)
    445 {
    446     for (const char *p = start; *p != '\0' && p != end; ++p) {
    447 	if (*p == '\n' || *p == '\f')
    448 	    ind = 0;
    449 	else if (*p == '\t')
    450 	    ind = opt.tabsize * (ind / opt.tabsize + 1);
    451 	else if (*p == '\b')
    452 	    --ind;
    453 	else
    454 	    ++ind;
    455     }
    456     return ind;
    457 }
    458 
    459 int
    460 indentation_after(int ind, const char *s)
    461 {
    462     return indentation_after_range(ind, s, NULL);
    463 }
    464 
    465 void
    466 diag(int level, const char *msg, ...)
    467 {
    468     va_list ap;
    469     const char *s, *e;
    470 
    471     if (level != 0)
    472 	found_err = true;
    473 
    474     if (output == stdout) {
    475 	s = "/**INDENT** ";
    476 	e = " */";
    477     } else {
    478 	s = e = "";
    479     }
    480 
    481     va_start(ap, msg);
    482     fprintf(stderr, "%s%s@%d: ", s, level == 0 ? "Warning" : "Error", line_no);
    483     vfprintf(stderr, msg, ap);
    484     fprintf(stderr, "%s\n", e);
    485     va_end(ap);
    486 }
    487