Home | History | Annotate | Line # | Download | only in indent
io.c revision 1.155
      1 /*	$NetBSD: io.c,v 1.155 2023/05/12 10:53:33 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.155 2023/05/12 10:53:33 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 <assert.h>
     52 #include <stdio.h>
     53 #include <stdlib.h>
     54 #include <string.h>
     55 
     56 #include "indent.h"
     57 
     58 /*
     59  * The current line, ready to be split into tokens, terminated with '\n'. The
     60  * current read position is inp.s, and the invariant inp.buf <= inp.s < inp.e
     61  * holds.
     62  */
     63 static struct buffer inp;
     64 
     65 static int paren_indent;
     66 
     67 
     68 void
     69 inp_init(void)
     70 {
     71     inp.buf = xmalloc(10);
     72     inp.l = inp.buf + 8;
     73     inp.s = inp.buf;
     74     inp.e = inp.buf;
     75 }
     76 
     77 const char *
     78 inp_p(void)
     79 {
     80     assert(inp.s < inp.e);
     81     return inp.s;
     82 }
     83 
     84 const char *
     85 inp_line_start(void)
     86 {
     87     return inp.buf;
     88 }
     89 
     90 const char *
     91 inp_line_end(void)
     92 {
     93     return inp.e;
     94 }
     95 
     96 char
     97 inp_peek(void)
     98 {
     99     assert(inp.s < inp.e);
    100     return *inp.s;
    101 }
    102 
    103 char
    104 inp_lookahead(size_t i)
    105 {
    106     assert(i < (size_t)(inp.e - inp.s));
    107     return inp.s[i];
    108 }
    109 
    110 void
    111 inp_skip(void)
    112 {
    113     assert(inp.s < inp.e);
    114     inp.s++;
    115     if (inp.s >= inp.e)
    116 	inp_read_line();
    117 }
    118 
    119 char
    120 inp_next(void)
    121 {
    122     char ch = inp_peek();
    123     inp_skip();
    124     return ch;
    125 }
    126 
    127 static void
    128 inp_add(char ch)
    129 {
    130     if (inp.e >= inp.l) {
    131 	size_t new_size = (size_t)(inp.l - inp.buf) * 2 + 10;
    132 	size_t offset = (size_t)(inp.e - inp.buf);
    133 	inp.buf = xrealloc(inp.buf, new_size);
    134 	inp.s = inp.buf;
    135 	inp.e = inp.buf + offset;
    136 	inp.l = inp.buf + new_size - 2;
    137     }
    138     *inp.e++ = ch;
    139 }
    140 
    141 static void
    142 inp_read_next_line(FILE *f)
    143 {
    144     inp.s = inp.buf;
    145     inp.e = inp.buf;
    146 
    147     for (;;) {
    148 	int ch = getc(f);
    149 	if (ch == EOF) {
    150 	    if (!inhibit_formatting) {
    151 		inp_add(' ');
    152 		inp_add('\n');
    153 	    }
    154 	    had_eof = true;
    155 	    break;
    156 	}
    157 
    158 	if (ch != '\0')
    159 	    inp_add((char)ch);
    160 	if (ch == '\n')
    161 	    break;
    162     }
    163 }
    164 
    165 static void
    166 output_char(char ch)
    167 {
    168     fputc(ch, output);
    169     debug_vis_range("output_char '", &ch, &ch + 1, "'\n");
    170 }
    171 
    172 static void
    173 output_range(const char *s, const char *e)
    174 {
    175     fwrite(s, 1, (size_t)(e - s), output);
    176     debug_vis_range("output_range \"", s, e, "\"\n");
    177 }
    178 
    179 static int
    180 output_indent(int old_ind, int new_ind)
    181 {
    182     int ind = old_ind;
    183 
    184     if (opt.use_tabs) {
    185 	int tabsize = opt.tabsize;
    186 	int n = new_ind / tabsize - ind / tabsize;
    187 	if (n > 0)
    188 	    ind -= ind % tabsize;
    189 	for (int i = 0; i < n; i++) {
    190 	    fputc('\t', output);
    191 	    ind += tabsize;
    192 	}
    193     }
    194 
    195     for (; ind < new_ind; ind++)
    196 	fputc(' ', output);
    197 
    198     debug_println("output_indent %d", ind);
    199     return ind;
    200 }
    201 
    202 static int
    203 output_line_label(void)
    204 {
    205     int ind;
    206 
    207     while (lab.e > lab.s && ch_isblank(lab.e[-1]))
    208 	lab.e--;
    209     *lab.e = '\0';
    210 
    211     ind = output_indent(0, compute_label_indent());
    212     output_range(lab.s, lab.e);
    213     ind = ind_add(ind, lab.s, lab.e);
    214 
    215     ps.is_case_label = false;
    216     return ind;
    217 }
    218 
    219 static int
    220 output_line_code(int ind)
    221 {
    222 
    223     int target_ind = compute_code_indent();
    224     for (int i = 0; i < ps.nparen; i++) {
    225 	if (ps.paren[i].indent >= 0) {
    226 	    int paren_ind = ps.paren[i].indent;
    227 	    ps.paren[i].indent = (short)(-1 - (paren_ind + target_ind));
    228 	    debug_println(
    229 		"setting paren_indents[%d] from %d to %d for column %d",
    230 		i, paren_ind, ps.paren[i].indent, target_ind + 1);
    231 	}
    232     }
    233 
    234     ind = output_indent(ind, target_ind);
    235     output_range(code.s, code.e);
    236     return ind_add(ind, code.s, code.e);
    237 }
    238 
    239 static void
    240 output_line_comment(int ind)
    241 {
    242     int target_ind = ps.com_ind;
    243     const char *p = com.s;
    244 
    245     target_ind += ps.comment_delta;
    246 
    247     /* consider original indentation in case this is a box comment */
    248     for (; *p == '\t'; p++)
    249 	target_ind += opt.tabsize;
    250 
    251     for (; target_ind < 0; p++) {
    252 	if (*p == ' ')
    253 	    target_ind++;
    254 	else if (*p == '\t')
    255 	    target_ind = next_tab(target_ind);
    256 	else {
    257 	    target_ind = 0;
    258 	    break;
    259 	}
    260     }
    261 
    262     /* if comment can't fit on this line, put it on the next line */
    263     if (ind > target_ind) {
    264 	output_char('\n');
    265 	ind = 0;
    266     }
    267 
    268     while (com.e > p && ch_isspace(com.e[-1]))
    269 	com.e--;
    270 
    271     (void)output_indent(ind, target_ind);
    272     output_range(p, com.e);
    273 
    274     ps.comment_delta = ps.n_comment_delta;
    275 }
    276 
    277 /*
    278  * Write a line of formatted source to the output file. The line consists of
    279  * the label, the code and the comment.
    280  */
    281 static void
    282 output_complete_line(char line_terminator)
    283 {
    284     ps.is_function_definition = false;
    285 
    286     if (!inhibit_formatting) {
    287 	if (ps.ind_level == 0)
    288 	    ps.in_stmt_cont = false;	/* this is a class A kludge */
    289 
    290 	int ind = 0;
    291 	if (lab.e != lab.s)
    292 	    ind = output_line_label();
    293 	if (code.e != code.s)
    294 	    ind = output_line_code(ind);
    295 	if (com.e != com.s)
    296 	    output_line_comment(ind);
    297 
    298 	output_char(line_terminator);
    299 
    300 	/* TODO: rename to blank_line_after_decl */
    301 	if (ps.just_saw_decl == 1 && opt.blanklines_after_decl)
    302 	    ps.just_saw_decl = 0;
    303     }
    304 
    305     ps.decl_on_line = ps.in_decl;	/* for proper comment indentation */
    306     ps.in_stmt_cont = ps.in_stmt_or_decl && !ps.in_decl;
    307     ps.decl_indent_done = false;
    308 
    309     *(lab.e = lab.s) = '\0';	/* reset buffers */
    310     *(code.e = code.s) = '\0';
    311     *(com.e = com.s = com.buf + 1) = '\0';
    312 
    313     ps.ind_level = ps.ind_level_follow;
    314     ps.line_start_nparen = ps.nparen;
    315 
    316     if (ps.nparen > 0) {
    317 	/* TODO: explain what negative indentation means */
    318 	paren_indent = -1 - ps.paren[ps.nparen - 1].indent;
    319 	debug_println("paren_indent is now %d", paren_indent);
    320     }
    321 }
    322 
    323 void
    324 output_line(void)
    325 {
    326     output_complete_line('\n');
    327 }
    328 
    329 void
    330 output_line_ff(void)
    331 {
    332     output_complete_line('\f');
    333 }
    334 
    335 static int
    336 compute_code_indent_lineup(int base_ind)
    337 {
    338     int ti = paren_indent;
    339     int overflow = ind_add(ti, code.s, code.e) - opt.max_line_length;
    340     if (overflow < 0)
    341 	return ti;
    342 
    343     if (ind_add(base_ind, code.s, code.e) < opt.max_line_length) {
    344 	ti -= overflow + 2;
    345 	if (ti > base_ind)
    346 	    return ti;
    347 	return base_ind;
    348     }
    349 
    350     return ti;
    351 }
    352 
    353 int
    354 compute_code_indent(void)
    355 {
    356     int base_ind = ps.ind_level * opt.indent_size;
    357 
    358     if (ps.line_start_nparen == 0) {
    359 	if (ps.in_stmt_cont && ps.in_enum != in_enum_brace)
    360 	    return base_ind + opt.continuation_indent;
    361 	return base_ind;
    362     }
    363 
    364     if (opt.lineup_to_parens) {
    365 	if (opt.lineup_to_parens_always)
    366 	    return paren_indent;
    367 	return compute_code_indent_lineup(base_ind);
    368     }
    369 
    370     if (2 * opt.continuation_indent == opt.indent_size)
    371 	return base_ind + opt.continuation_indent;
    372     else
    373 	return base_ind + opt.continuation_indent * ps.line_start_nparen;
    374 }
    375 
    376 int
    377 compute_label_indent(void)
    378 {
    379     if (ps.is_case_label)
    380 	return (int)(case_ind * (float)opt.indent_size);
    381     if (lab.s[0] == '#')
    382 	return 0;
    383     return opt.indent_size * (ps.ind_level - 2);
    384 }
    385 
    386 static void
    387 skip_blank(const char **pp)
    388 {
    389     while (ch_isblank(**pp))
    390 	(*pp)++;
    391 }
    392 
    393 static bool
    394 skip_string(const char **pp, const char *s)
    395 {
    396     size_t len = strlen(s);
    397     if (strncmp(*pp, s, len) == 0) {
    398 	*pp += len;
    399 	return true;
    400     }
    401     return false;
    402 }
    403 
    404 static void
    405 parse_indent_comment(void)
    406 {
    407     bool on;
    408 
    409     const char *p = inp.buf;
    410 
    411     skip_blank(&p);
    412     if (!skip_string(&p, "/*"))
    413 	return;
    414     skip_blank(&p);
    415     if (!skip_string(&p, "INDENT"))
    416 	return;
    417 
    418     skip_blank(&p);
    419     if (*p == '*' || skip_string(&p, "ON"))
    420 	on = true;
    421     else if (skip_string(&p, "OFF"))
    422 	on = false;
    423     else
    424 	return;
    425 
    426     skip_blank(&p);
    427     if (!skip_string(&p, "*/\n"))
    428 	return;
    429 
    430     if (com.s != com.e || lab.s != lab.e || code.s != code.e)
    431 	output_line();
    432 
    433     inhibit_formatting = !on;
    434 }
    435 
    436 void
    437 inp_read_line(void)
    438 {
    439     inp_read_next_line(input);
    440 
    441     parse_indent_comment();
    442 
    443     if (inhibit_formatting)
    444 	output_range(inp.s, inp.e);
    445 }
    446