xref: /netbsd-src/usr.bin/indent/io.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: io.c,v 1.49 2021/03/14 01:44:37 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.49 2021/03/14 01:44:37 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;
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 = 1 + indentation_after(cur_col - 1, 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 	    int 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 = 1 + indentation_after(cur_col - 1, s_code);
219 	}
220 	if (s_com != e_com) {		/* print comment, if any */
221 	    int target_col = ps.com_col;
222 	    char *com_st = s_com;
223 
224 	    target_col += ps.comment_delta;
225 	    while (*com_st == '\t')	/* consider original indentation in
226 				 * case this is a box comment */
227 		com_st++, target_col += opt.tabsize;
228 	    while (target_col <= 0)
229 		if (*com_st == ' ')
230 		    target_col++, com_st++;
231 		else if (*com_st == '\t') {
232 		    target_col = opt.tabsize * (1 + (target_col - 1) / opt.tabsize) + 1;
233 		    com_st++;
234 		} else
235 		    target_col = 1;
236 	    if (cur_col > target_col) {	/* 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_col - 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 declaration,
267 				 * remember that fact for proper comment
268 				 * indentation */
269     ps.ind_stmt = ps.in_stmt & ~ps.in_decl; /* next line should be indented if
270 				 * we have not completed this stmt and if we
271 				 * are not in the middle of a declaration */
272     ps.use_ff = false;
273     ps.dumped_decl_indent = 0;
274     *(e_lab = s_lab) = '\0';	/* reset buffers */
275     *(e_code = s_code) = '\0';
276     *(e_com = s_com = combuf + 1) = '\0';
277     ps.ind_level = ps.i_l_follow;
278     ps.paren_level = ps.p_l_follow;
279     if (ps.paren_level > 0) {
280         /* TODO: explain what negative indentation means */
281 	paren_indent = -ps.paren_indents[ps.paren_level - 1];
282 	debug_println("paren_indent is now %d", paren_indent);
283     }
284     not_first_line = 1;
285 }
286 
287 int
288 compute_code_indent(void)
289 {
290     int target_ind = opt.indent_size * ps.ind_level;
291 
292     if (ps.paren_level != 0) {
293 	if (!opt.lineup_to_parens)
294 	    if (2 * opt.continuation_indent == opt.indent_size)
295 		target_ind += opt.continuation_indent;
296 	    else
297 		target_ind += opt.continuation_indent * 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 = 1 + indentation_after(t - 1, s_code) - opt.max_line_length) > 0
310 		&& 1 + indentation_after(target_ind, s_code) <= opt.max_line_length) {
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.indent_size);
327     if (s_lab[0] == '#')
328         return 0;
329     return opt.indent_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 	debug_println("switched buf_ptr back to bp_save");
352 	if (buf_ptr < buf_end)
353 	    return;		/* only return if there is really something in
354 				 * this buffer */
355     }
356     for (p = in_buffer;;) {
357 	if (p >= in_buffer_limit) {
358 	    size_t size = (in_buffer_limit - in_buffer) * 2 + 10;
359 	    size_t offset = p - in_buffer;
360 	    in_buffer = realloc(in_buffer, size);
361 	    if (in_buffer == NULL)
362 		errx(1, "input line too long");
363 	    p = in_buffer + offset;
364 	    in_buffer_limit = in_buffer + size - 2;
365 	}
366 	if ((i = getc(f)) == EOF) {
367 	    *p++ = ' ';
368 	    *p++ = '\n';
369 	    had_eof = true;
370 	    break;
371 	}
372 	if (i != '\0')
373 	    *p++ = i;
374 	if (i == '\n')
375 	    break;
376     }
377     buf_ptr = in_buffer;
378     buf_end = p;
379     if (p - in_buffer > 2 && p[-2] == '/' && p[-3] == '*') {
380 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
381 	    fill_buffer();	/* flush indent error message */
382 	else {
383 	    int com = 0;
384 
385 	    p = in_buffer;
386 	    while (*p == ' ' || *p == '\t')
387 		p++;
388 	    if (*p == '/' && p[1] == '*') {
389 		p += 2;
390 		while (*p == ' ' || *p == '\t')
391 		    p++;
392 		if (p[0] == 'I' && p[1] == 'N' && p[2] == 'D' && p[3] == 'E'
393 			&& p[4] == 'N' && p[5] == 'T') {
394 		    p += 6;
395 		    while (*p == ' ' || *p == '\t')
396 			p++;
397 		    if (*p == '*')
398 			com = 1;
399 		    else if (*p == 'O') {
400 			if (*++p == 'N')
401 			    p++, com = 1;
402 			else if (*p == 'F' && *++p == 'F')
403 			    p++, com = 2;
404 		    }
405 		    while (*p == ' ' || *p == '\t')
406 			p++;
407 		    if (p[0] == '*' && p[1] == '/' && p[2] == '\n' && com) {
408 			if (s_com != e_com || s_lab != e_lab || s_code != e_code)
409 			    dump_line();
410 			if (!(inhibit_formatting = com - 1)) {
411 			    n_real_blanklines = 0;
412 			    postfix_blankline_requested = 0;
413 			    prefix_blankline_requested = 0;
414 			    suppress_blanklines = 1;
415 			}
416 		    }
417 		}
418 	    }
419 	}
420     }
421     if (inhibit_formatting) {
422 	p = in_buffer;
423 	do {
424 	    output_char(*p);
425 	} while (*p++ != '\n');
426     }
427 }
428 
429 int
430 indentation_after_range(int ind, const char *start, const char *end)
431 {
432     for (const char *p = start; *p != '\0' && p != end; ++p) {
433 	if (*p == '\n' || *p == '\f')
434 	    ind = 0;
435 	else if (*p == '\t')
436 	    ind = opt.tabsize * (ind / opt.tabsize + 1);
437 	else if (*p == '\b')
438 	    --ind;
439 	else
440 	    ++ind;
441     }
442     return ind;
443 }
444 
445 int
446 indentation_after(int ind, const char *s)
447 {
448     return indentation_after_range(ind, s, NULL);
449 }
450 
451 void
452 diag(int level, const char *msg, ...)
453 {
454     va_list ap;
455     const char *s, *e;
456 
457     if (level)
458 	found_err = 1;
459 
460     if (output == stdout) {
461 	s = "/**INDENT** ";
462 	e = " */";
463     } else {
464 	s = e = "";
465     }
466 
467     va_start(ap, msg);
468     fprintf(stderr, "%s%s@%d: ", s, level == 0 ? "Warning" : "Error", line_no);
469     vfprintf(stderr, msg, ap);
470     fprintf(stderr, "%s\n", e);
471     va_end(ap);
472 }
473