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