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