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