Home | History | Annotate | Line # | Download | only in indent
io.c revision 1.40
      1 /*	$NetBSD: io.c,v 1.40 2021/03/13 10:20:54 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.40 2021/03/13 10:20:54 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, target_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 (s_code == e_code && s_lab == e_lab && s_com == e_com) {
    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 (e_lab != s_lab || e_code != s_code)
    154 	    ++code_lines;	/* keep count of lines with code */
    155 
    156 
    157 	if (e_lab != s_lab) {	/* print lab, if any */
    158 	    if (comment_open) {
    159 		comment_open = 0;
    160 		output_string(".*/\n");
    161 	    }
    162 	    while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
    163 		e_lab--;
    164 	    *e_lab = '\0';
    165 	    cur_col = 1 + output_indent(0, compute_label_indent());
    166 	    if (s_lab[0] == '#' && (strncmp(s_lab, "#else", 5) == 0
    167 				    || strncmp(s_lab, "#endif", 6) == 0)) {
    168 		char *s = s_lab;
    169 		if (e_lab[-1] == '\n') e_lab--;
    170 		do {
    171 		    output_char(*s++);
    172 		} while (s < e_lab && 'a' <= *s && *s <= 'z');
    173 		while ((*s == ' ' || *s == '\t') && s < e_lab)
    174 		    s++;
    175 		if (s < e_lab) {
    176 		    if (s[0] == '/' && s[1] == '*') {
    177 			output_char('\t');
    178 			output_range(s, e_lab);
    179 		    } else {
    180 		        output_string("\t/* ");
    181 			output_range(s, e_lab);
    182 			output_string(" */");
    183 		    }
    184 		}
    185 	    } else
    186 	        output_range(s_lab, e_lab);
    187 	    cur_col = count_spaces(cur_col, s_lab);
    188 	} else
    189 	    cur_col = 1;	/* there is no label section */
    190 
    191 	ps.pcase = false;
    192 
    193 	if (s_code != e_code) {	/* print code section, if any */
    194 	    if (comment_open) {
    195 		comment_open = 0;
    196 		output_string(".*/\n");
    197 	    }
    198 	    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(s_code, e_code);
    218 	    cur_col = count_spaces(cur_col, s_code);
    219 	}
    220 	if (s_com != e_com) {		/* print comment, if any */
    221 	    int target = ps.com_col;
    222 	    char *com_st = s_com;
    223 
    224 	    target += ps.comment_delta;
    225 	    while (*com_st == '\t')	/* consider original indentation in
    226 				     * case this is a box comment */
    227 		com_st++, target += opt.tabsize;
    228 	    while (target <= 0)
    229 		if (*com_st == ' ')
    230 		    target++, com_st++;
    231 		else if (*com_st == '\t') {
    232 		    target = opt.tabsize * (1 + (target - 1) / opt.tabsize) + 1;
    233 		    com_st++;
    234 		} else
    235 		    target = 1;
    236 	    if (cur_col > target) {	/* 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 (e_com > com_st && isspace((unsigned char)e_com[-1]))
    243 		e_com--;
    244 	    (void)output_indent(cur_col - 1, target - 1);
    245 	    output_range(com_st, e_com);
    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 (e_com - s_com > 1 && s_com[1] == '/')
    264 	output_range(s_token, e_token);
    265 
    266     ps.decl_on_line = ps.in_decl;	/* if we are in the middle of a
    267 					 * declaration, remember that fact for
    268 					 * proper comment indentation */
    269     ps.ind_stmt = ps.in_stmt & ~ps.in_decl;	/* next line should be
    270 						 * indented if we have not
    271 						 * completed this stmt and if
    272 						 * we are not in the middle of
    273 						 * a declaration */
    274     ps.use_ff = false;
    275     ps.dumped_decl_indent = 0;
    276     *(e_lab = s_lab) = '\0';	/* reset buffers */
    277     *(e_code = s_code) = '\0';
    278     *(e_com = s_com = combuf + 1) = '\0';
    279     ps.ind_level = ps.i_l_follow;
    280     ps.paren_level = ps.p_l_follow;
    281     if (ps.paren_level > 0) {
    282         /* TODO: explain what negative indentation means */
    283 	paren_indent = -ps.paren_indents[ps.paren_level - 1];
    284 	debug_println("paren_indent is now %d", paren_indent);
    285     }
    286     not_first_line = 1;
    287 }
    288 
    289 int
    290 compute_code_indent(void)
    291 {
    292     int target_ind = opt.ind_size * ps.ind_level;
    293 
    294     if (ps.paren_level != 0) {
    295 	if (!opt.lineup_to_parens)
    296 	    target_ind += opt.continuation_indent *
    297 		(2 * opt.continuation_indent == opt.ind_size ? 1 : ps.paren_level);
    298 	else if (opt.lineup_to_parens_always)
    299 	    /*
    300 	     * XXX: where does this '- 1' come from?  It looks strange but is
    301 	     * nevertheless needed for proper indentation, as demonstrated in
    302 	     * the test opt-lpl.0.
    303 	     */
    304 	    target_ind = paren_indent - 1;
    305 	else {
    306 	    int w;
    307 	    int t = paren_indent;
    308 
    309 	    if ((w = count_spaces(t, s_code) - opt.max_col) > 0
    310 		    && count_spaces(target_ind + 1, s_code) <= opt.max_col) {
    311 		t -= w + 1;
    312 		if (t > target_ind + 1)
    313 		    target_ind = t - 1;
    314 	    } else
    315 		target_ind = t - 1;
    316 	}
    317     } else if (ps.ind_stmt)
    318 	target_ind += opt.continuation_indent;
    319     return target_ind;
    320 }
    321 
    322 int
    323 compute_label_indent(void)
    324 {
    325     if (ps.pcase)
    326 	return (int) (case_ind * opt.ind_size);
    327     if (s_lab[0] == '#')
    328         return 0;
    329     return opt.ind_size * (ps.ind_level - label_offset);
    330 }
    331 
    332 
    333 /*
    334  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
    335  *
    336  * All rights reserved
    337  *
    338  * FUNCTION: Reads one block of input into the input buffer
    339  */
    340 void
    341 fill_buffer(void)
    342 {				/* this routine reads stuff from the input */
    343     char *p;
    344     int i;
    345     FILE *f = input;
    346 
    347     if (bp_save != NULL) {	/* there is a partly filled input buffer left */
    348 	buf_ptr = bp_save;	/* do not read anything, just switch buffers */
    349 	buf_end = be_save;
    350 	bp_save = be_save = NULL;
    351 	if (buf_ptr < buf_end)
    352 	    return;		/* only return if there is really something in
    353 				 * this buffer */
    354     }
    355     for (p = in_buffer;;) {
    356 	if (p >= in_buffer_limit) {
    357 	    int size = (in_buffer_limit - in_buffer) * 2 + 10;
    358 	    int offset = p - in_buffer;
    359 	    in_buffer = realloc(in_buffer, size);
    360 	    if (in_buffer == NULL)
    361 		errx(1, "input line too long");
    362 	    p = in_buffer + offset;
    363 	    in_buffer_limit = in_buffer + size - 2;
    364 	}
    365 	if ((i = getc(f)) == EOF) {
    366 	    *p++ = ' ';
    367 	    *p++ = '\n';
    368 	    had_eof = true;
    369 	    break;
    370 	}
    371 	if (i != '\0')
    372 	    *p++ = i;
    373 	if (i == '\n')
    374 	    break;
    375     }
    376     buf_ptr = in_buffer;
    377     buf_end = p;
    378     if (p - in_buffer > 2 && p[-2] == '/' && p[-3] == '*') {
    379 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
    380 	    fill_buffer();	/* flush indent error message */
    381 	else {
    382 	    int com = 0;
    383 
    384 	    p = in_buffer;
    385 	    while (*p == ' ' || *p == '\t')
    386 		p++;
    387 	    if (*p == '/' && p[1] == '*') {
    388 		p += 2;
    389 		while (*p == ' ' || *p == '\t')
    390 		    p++;
    391 		if (p[0] == 'I' && p[1] == 'N' && p[2] == 'D' && p[3] == 'E'
    392 			&& p[4] == 'N' && p[5] == 'T') {
    393 		    p += 6;
    394 		    while (*p == ' ' || *p == '\t')
    395 			p++;
    396 		    if (*p == '*')
    397 			com = 1;
    398 		    else if (*p == 'O') {
    399 			if (*++p == 'N')
    400 			    p++, com = 1;
    401 			else if (*p == 'F' && *++p == 'F')
    402 			    p++, com = 2;
    403 		    }
    404 		    while (*p == ' ' || *p == '\t')
    405 			p++;
    406 		    if (p[0] == '*' && p[1] == '/' && p[2] == '\n' && com) {
    407 			if (s_com != e_com || s_lab != e_lab || s_code != e_code)
    408 			    dump_line();
    409 			if (!(inhibit_formatting = com - 1)) {
    410 			    n_real_blanklines = 0;
    411 			    postfix_blankline_requested = 0;
    412 			    prefix_blankline_requested = 0;
    413 			    suppress_blanklines = 1;
    414 			}
    415 		    }
    416 		}
    417 	    }
    418 	}
    419     }
    420     if (inhibit_formatting) {
    421 	p = in_buffer;
    422 	do {
    423 	    output_char(*p);
    424 	} while (*p++ != '\n');
    425     }
    426 }
    427 
    428 int
    429 indentation_after_range(int ind, const char *start, const char *end)
    430 {
    431     for (const char *p = start; *p != '\0' && p != end; ++p) {
    432 	if (*p == '\n' || *p == '\f')
    433 	    ind = 0;
    434 	else if (*p == '\t')
    435 	    ind = opt.tabsize * (ind / opt.tabsize + 1);
    436 	else if (*p == '\b')
    437 	    --ind;
    438 	else
    439 	    ++ind;
    440     }
    441     return ind;
    442 }
    443 
    444 int
    445 indentation_after(int ind, const char *s)
    446 {
    447     return indentation_after_range(ind, s, NULL);
    448 }
    449 
    450 int
    451 count_spaces_until(int col, const char *s, const char *e)
    452 {
    453     return 1 + indentation_after_range(col - 1, s, e);
    454 }
    455 
    456 int
    457 count_spaces(int col, const char *s)
    458 {
    459     return 1 + indentation_after(col - 1, s);
    460 }
    461 
    462 void
    463 diag(int level, const char *msg, ...)
    464 {
    465     va_list ap;
    466     const char *s, *e;
    467 
    468     if (level)
    469 	found_err = 1;
    470 
    471     if (output == stdout) {
    472 	s = "/**INDENT** ";
    473 	e = " */";
    474     } else {
    475 	s = e = "";
    476     }
    477 
    478     va_start(ap, msg);
    479     fprintf(stderr, "%s%s@%d: ", s, level == 0 ? "Warning" : "Error", line_no);
    480     vfprintf(stderr, msg, ap);
    481     fprintf(stderr, "%s\n", e);
    482     va_end(ap);
    483 }
    484