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