Home | History | Annotate | Line # | Download | only in indent
io.c revision 1.36
      1 /*	$NetBSD: io.c,v 1.36 2021/03/13 09:21:57 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.36 2021/03/13 09:21:57 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_column() - 1);
    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 = compute_code_column();
    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_column(void)
    291 {
    292     int target_col = opt.ind_size * ps.ind_level + 1;
    293 
    294     if (ps.paren_level) {
    295 	if (!opt.lineup_to_parens)
    296 	    target_col += opt.continuation_indent *
    297 		(2 * opt.continuation_indent == opt.ind_size ? 1 : ps.paren_level);
    298 	else if (opt.lineup_to_parens_always)
    299 	    target_col = paren_indent;
    300 	else {
    301 	    int w;
    302 	    int t = paren_indent;
    303 
    304 	    if ((w = count_spaces(t, s_code) - opt.max_col) > 0
    305 		    && count_spaces(target_col, s_code) <= opt.max_col) {
    306 		t -= w + 1;
    307 		if (t > target_col)
    308 		    target_col = t;
    309 	    } else
    310 		target_col = t;
    311 	}
    312     } else if (ps.ind_stmt)
    313 	target_col += opt.continuation_indent;
    314     return target_col;
    315 }
    316 
    317 int
    318 compute_label_column(void)
    319 {
    320     return
    321 	ps.pcase ? (int) (case_ind * opt.ind_size) + 1
    322 	: *s_lab == '#' ? 1
    323 	: opt.ind_size * (ps.ind_level - label_offset) + 1;
    324 }
    325 
    326 
    327 /*
    328  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
    329  *
    330  * All rights reserved
    331  *
    332  * FUNCTION: Reads one block of input into the input buffer
    333  */
    334 void
    335 fill_buffer(void)
    336 {				/* this routine reads stuff from the input */
    337     char *p;
    338     int i;
    339     FILE *f = input;
    340 
    341     if (bp_save != NULL) {	/* there is a partly filled input buffer left */
    342 	buf_ptr = bp_save;	/* do not read anything, just switch buffers */
    343 	buf_end = be_save;
    344 	bp_save = be_save = NULL;
    345 	if (buf_ptr < buf_end)
    346 	    return;		/* only return if there is really something in
    347 				 * this buffer */
    348     }
    349     for (p = in_buffer;;) {
    350 	if (p >= in_buffer_limit) {
    351 	    int size = (in_buffer_limit - in_buffer) * 2 + 10;
    352 	    int offset = p - in_buffer;
    353 	    in_buffer = realloc(in_buffer, size);
    354 	    if (in_buffer == NULL)
    355 		errx(1, "input line too long");
    356 	    p = in_buffer + offset;
    357 	    in_buffer_limit = in_buffer + size - 2;
    358 	}
    359 	if ((i = getc(f)) == EOF) {
    360 		*p++ = ' ';
    361 		*p++ = '\n';
    362 		had_eof = true;
    363 		break;
    364 	}
    365 	if (i != '\0')
    366 	    *p++ = i;
    367 	if (i == '\n')
    368 		break;
    369     }
    370     buf_ptr = in_buffer;
    371     buf_end = p;
    372     if (p - in_buffer > 2 && p[-2] == '/' && p[-3] == '*') {
    373 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
    374 	    fill_buffer();	/* flush indent error message */
    375 	else {
    376 	    int         com = 0;
    377 
    378 	    p = in_buffer;
    379 	    while (*p == ' ' || *p == '\t')
    380 		p++;
    381 	    if (*p == '/' && p[1] == '*') {
    382 		p += 2;
    383 		while (*p == ' ' || *p == '\t')
    384 		    p++;
    385 		if (p[0] == 'I' && p[1] == 'N' && p[2] == 'D' && p[3] == 'E'
    386 			&& p[4] == 'N' && p[5] == 'T') {
    387 		    p += 6;
    388 		    while (*p == ' ' || *p == '\t')
    389 			p++;
    390 		    if (*p == '*')
    391 			com = 1;
    392 		    else if (*p == 'O') {
    393 			if (*++p == 'N')
    394 			    p++, com = 1;
    395 			else if (*p == 'F' && *++p == 'F')
    396 			    p++, com = 2;
    397 		    }
    398 		    while (*p == ' ' || *p == '\t')
    399 			p++;
    400 		    if (p[0] == '*' && p[1] == '/' && p[2] == '\n' && com) {
    401 			if (s_com != e_com || s_lab != e_lab || s_code != e_code)
    402 			    dump_line();
    403 			if (!(inhibit_formatting = com - 1)) {
    404 			    n_real_blanklines = 0;
    405 			    postfix_blankline_requested = 0;
    406 			    prefix_blankline_requested = 0;
    407 			    suppress_blanklines = 1;
    408 			}
    409 		    }
    410 		}
    411 	    }
    412 	}
    413     }
    414     if (inhibit_formatting) {
    415 	p = in_buffer;
    416 	do {
    417 	    output_char(*p);
    418 	} while (*p++ != '\n');
    419     }
    420 }
    421 
    422 /*
    423  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
    424  *
    425  * All rights reserved
    426  */
    427 int
    428 count_spaces_until(int col, const char *buffer, const char *end)
    429 {
    430     for (const char *p = buffer; *p != '\0' && p != end; ++p) {
    431 	switch (*p) {
    432 
    433 	case '\n':
    434 	case 014:		/* form feed */
    435 	    col = 1;
    436 	    break;
    437 
    438 	case '\t':
    439 	    col = 1 + opt.tabsize * ((col - 1) / opt.tabsize + 1);
    440 	    break;
    441 
    442 	case 010:		/* backspace */
    443 	    --col;
    444 	    break;
    445 
    446 	default:
    447 	    ++col;
    448 	    break;
    449 	}			/* end of switch */
    450     }				/* end of for loop */
    451     return col;
    452 }
    453 
    454 int
    455 count_spaces(int col, const char *buffer)
    456 {
    457     return count_spaces_until(col, buffer, NULL);
    458 }
    459 
    460 void
    461 diag(int level, const char *msg, ...)
    462 {
    463     va_list ap;
    464     const char *s, *e;
    465 
    466     if (level)
    467 	found_err = 1;
    468 
    469     if (output == stdout) {
    470 	s = "/**INDENT** ";
    471 	e = " */";
    472     } else {
    473 	s = e = "";
    474     }
    475 
    476     va_start(ap, msg);
    477     fprintf(stderr, "%s%s@%d: ", s, level == 0 ? "Warning" : "Error", line_no);
    478     vfprintf(stderr, msg, ap);
    479     fprintf(stderr, "%s\n", e);
    480     va_end(ap);
    481 }
    482