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