xref: /netbsd-src/usr.bin/indent/pr_comment.c (revision 4170684f22077e3779c5c14826430de0dec964b2)
1 /*	$NetBSD: pr_comment.c,v 1.149 2023/05/21 10:18:44 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 #include <sys/cdefs.h>
41 __RCSID("$NetBSD: pr_comment.c,v 1.149 2023/05/21 10:18:44 rillig Exp $");
42 
43 #include <string.h>
44 
45 #include "indent.h"
46 
47 static void
48 com_add_char(char ch)
49 {
50 	buf_add_char(&com, ch);
51 }
52 
53 static void
54 com_add_delim(void)
55 {
56 	if (!opt.star_comment_cont)
57 		return;
58 	buf_add_chars(&com, " * ", 3);
59 }
60 
61 static bool
62 fits_in_one_line(int com_ind, int max_line_length)
63 {
64 	for (const char *start = inp.st, *p = start; *p != '\n'; p++) {
65 		if (p[0] == '*' && p[1] == '/') {
66 			int len = ind_add(com_ind + 3,
67 			    start, (size_t)(p - start));
68 			len += p == start || ch_isblank(p[-1]) ? 2 : 3;
69 			return len <= max_line_length;
70 		}
71 	}
72 	return false;
73 }
74 
75 static void
76 analyze_comment(bool *p_may_wrap, bool *p_delim, int *p_line_length)
77 {
78 	bool may_wrap = true;
79 	bool delim = opt.comment_delimiter_on_blankline;
80 	int ind;
81 	int line_length = opt.max_line_length;
82 
83 	if (ps.curr_col_1 && !opt.format_col1_comments) {
84 		may_wrap = false;
85 		delim = false;
86 		ind = 0;
87 
88 	} else {
89 		if (inp.st[0] == '-' || inp.st[0] == '*' ||
90 		    token.mem[token.len - 1] == '/' ||
91 		    (inp.st[0] == '\n' && !opt.format_block_comments)) {
92 			may_wrap = false;
93 			delim = false;
94 		}
95 		if (code.len == 0 && inp.st[strspn(inp.st, "*")] == '\n')
96 			out.line_kind = lk_block_comment;
97 
98 		if (com.len > 0)
99 			output_line();
100 		if (lab.len == 0 && code.len == 0) {
101 			ind = (ps.ind_level - opt.unindent_displace)
102 			    * opt.indent_size;
103 			if (ind <= 0)
104 				ind = opt.format_col1_comments ? 0 : 1;
105 			line_length = opt.block_comment_max_line_length;
106 		} else {
107 			delim = false;
108 
109 			int target_ind = code.len > 0
110 			    ? ind_add(compute_code_indent(), code.st, code.len)
111 			    : ind_add(compute_label_indent(), lab.st, lab.len);
112 
113 			ind = ps.decl_on_line || ps.ind_level == 0
114 			    ? opt.decl_comment_column - 1
115 			    : opt.comment_column - 1;
116 			if (ind <= target_ind)
117 				ind = next_tab(target_ind);
118 			if (ind + 25 > line_length)
119 				line_length = ind + 25;
120 		}
121 	}
122 
123 	ps.com_ind = ind;
124 
125 	if (!may_wrap) {
126 		/* Find out how much indentation there was originally, because
127 		 * that much will have to be ignored by output_line. */
128 		size_t len = (size_t)(inp.st - 2 - inp.mem);
129 		ps.n_comment_delta = -ind_add(0, inp.mem, len);
130 	} else {
131 		ps.n_comment_delta = 0;
132 		if (!(inp.st[0] == '\t' && !ch_isblank(inp.st[1])))
133 			while (ch_isblank(inp.st[0]))
134 				inp.st++;
135 	}
136 
137 	ps.comment_delta = 0;
138 	com_add_char('/');
139 	com_add_char(token.mem[token.len - 1]);	/* either '*' or '/' */
140 
141 	if (may_wrap && !ch_isblank(inp.st[0]))
142 		com_add_char(' ');
143 
144 	if (delim && fits_in_one_line(ind, line_length))
145 		delim = false;
146 
147 	if (delim) {
148 		output_line();
149 		com_add_delim();
150 	}
151 
152 	*p_line_length = line_length;
153 	*p_delim = delim;
154 	*p_may_wrap = may_wrap;
155 }
156 
157 /*
158  * Copy characters from 'inp' to 'com'. Try to keep comments from going over
159  * the maximum line length. To do that, remember where the last blank, tab, or
160  * newline was. When a line is filled, print up to the last blank and continue
161  * copying.
162  */
163 static void
164 copy_comment_wrap(int line_length, bool delim)
165 {
166 	ssize_t last_blank = -1;	/* index of the last blank in com.mem
167 					 */
168 
169 	for (;;) {
170 		switch (inp.st[0]) {
171 		case '\n':
172 			if (had_eof) {
173 				diag(1, "Unterminated comment");
174 				output_line();
175 				return;
176 			}
177 
178 			last_blank = -1;
179 			if (ps.next_col_1) {
180 				if (com.len == 0) {
181 					/* force empty line of output */
182 					com_add_char(' ');
183 				}
184 				if (com.len > 3) {
185 					output_line();
186 					com_add_delim();
187 				}
188 				output_line();
189 				com_add_delim();
190 
191 			} else {
192 				ps.next_col_1 = true;
193 				if (!(com.len > 0
194 				    && ch_isblank(com.mem[com.len - 1])))
195 					com_add_char(' ');
196 				last_blank = (int)com.len - 1;
197 			}
198 			++line_no;
199 
200 			bool skip_asterisk = true;
201 			do {	/* flush any blanks and/or tabs at start of
202 				 * next line */
203 				inp_skip();
204 				if (inp.st[0] == '*' && skip_asterisk) {
205 					skip_asterisk = false;
206 					inp.st++;
207 					if (inp.st[0] == '/')
208 						goto end_of_comment;
209 				}
210 			} while (ch_isblank(inp.st[0]));
211 
212 			break;	/* end of case for newline */
213 
214 		case '*':
215 			inp.st++;
216 			if (inp.st[0] == '/') {
217 		end_of_comment:
218 				inp.st++;
219 
220 				if (delim) {
221 					if (com.len > 3)
222 						output_line();
223 					else
224 						com.len = 0;
225 					com_add_char(' ');
226 				} else {
227 					size_t len = com.len;
228 					while (ch_isblank(com.mem[len - 1]))
229 						len--;
230 					int now_len = ind_add(
231 					    ps.com_ind, com.st, len);
232 					if (now_len + 3 > line_length)
233 						output_line();
234 				}
235 
236 				if (!(com.len > 0
237 				    && ch_isblank(com.mem[com.len - 1])))
238 					com_add_char(' ');
239 				com_add_char('*');
240 				com_add_char('/');
241 				return;
242 
243 			} else	/* handle isolated '*' */
244 				com_add_char('*');
245 			break;
246 
247 		default:
248 			;
249 			int now_len = ind_add(ps.com_ind, com.st, com.len);
250 			for (;;) {
251 				char ch = inp_next();
252 				if (ch_isblank(ch))
253 					last_blank = (ssize_t)com.len;
254 				com_add_char(ch);
255 				now_len++;
256 				if (memchr("*\n\r\b\t", inp.st[0], 6) != NULL)
257 					break;
258 				if (now_len >= line_length && last_blank != -1)
259 					break;
260 			}
261 
262 			ps.next_col_1 = false;
263 
264 			if (now_len <= line_length)
265 				break;
266 			if (ch_isspace(com.mem[com.len - 1]))
267 				break;
268 
269 			if (last_blank == -1) {
270 				/* only a single word in this line */
271 				output_line();
272 				com_add_delim();
273 				break;
274 			}
275 
276 			const char *last_word_s = com.mem + last_blank + 1;
277 			size_t last_word_len = com.len
278 			- (size_t)(last_blank + 1);
279 			com.len = (size_t)last_blank;
280 			output_line();
281 			com_add_delim();
282 
283 			/* Assume that output_line and com_add_delim don't
284 			 * invalidate the "unused" part of the buffer beyond
285 			 * com.mem + com.len. */
286 			memmove(com.mem + com.len, last_word_s, last_word_len);
287 			com.len += last_word_len;
288 			last_blank = -1;
289 		}
290 	}
291 }
292 
293 static void
294 copy_comment_nowrap(void)
295 {
296 	for (;;) {
297 		if (inp.st[0] == '\n') {
298 			if (token.mem[token.len - 1] == '/')
299 				return;
300 
301 			if (had_eof) {
302 				diag(1, "Unterminated comment");
303 				output_line();
304 				return;
305 			}
306 
307 			if (com.len == 0)
308 				com_add_char(' ');	/* force output of an
309 							 * empty line */
310 			output_line();
311 			++line_no;
312 			inp_skip();
313 			continue;
314 		}
315 
316 		com_add_char(*inp.st++);
317 		if (com.mem[com.len - 2] == '*' && com.mem[com.len - 1] == '/'
318 		    && token.mem[token.len - 1] == '*')
319 			return;
320 	}
321 }
322 
323 /*
324  * Scan, reformat and output a single comment, which is either a block comment
325  * starting with '/' '*' or an end-of-line comment starting with '//'.
326  */
327 void
328 process_comment(void)
329 {
330 	int line_length;
331 	bool may_wrap, delim;
332 
333 	analyze_comment(&may_wrap, &delim, &line_length);
334 	if (may_wrap)
335 		copy_comment_wrap(line_length, delim);
336 	else
337 		copy_comment_nowrap();
338 }
339