Home | History | Annotate | Line # | Download | only in indent
pr_comment.c revision 1.76
      1 /*	$NetBSD: pr_comment.c,v 1.76 2021/10/12 22:22:35 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[] = "@(#)pr_comment.c	8.1 (Berkeley) 6/6/93";
     42 #endif
     43 
     44 #include <sys/cdefs.h>
     45 #if defined(__NetBSD__)
     46 __RCSID("$NetBSD: pr_comment.c,v 1.76 2021/10/12 22:22:35 rillig Exp $");
     47 #elif defined(__FreeBSD__)
     48 __FBSDID("$FreeBSD: head/usr.bin/indent/pr_comment.c 334927 2018-06-10 16:44:18Z pstef $");
     49 #endif
     50 
     51 #include <assert.h>
     52 #include <stdio.h>
     53 #include <string.h>
     54 
     55 #include "indent.h"
     56 
     57 static void
     58 com_add_char(char ch)
     59 {
     60     if (com.e + 1 >= com.l)
     61 	buf_expand(&com, 1);
     62     *com.e++ = ch;
     63 }
     64 
     65 static void
     66 com_add_delim(void)
     67 {
     68     if (!opt.star_comment_cont)
     69 	return;
     70     size_t len = 3;
     71     if (com.e + len >= com.l)
     72 	buf_expand(&com, len);
     73     memcpy(com.e, " * ", len);
     74     com.e += len;
     75 }
     76 
     77 static void
     78 com_terminate(void)
     79 {
     80     if (com.e + 1 >= com.l)
     81 	buf_expand(&com, 1);
     82     *com.e = '\0';
     83 }
     84 
     85 /*
     86  * Scan, reformat and output a single comment, which is either a block comment
     87  * starting with '/' '*' or an end-of-line comment starting with '//'.
     88  *
     89  * Try to keep comments from going over the maximum line length.  If a line is
     90  * too long, move everything starting from the last blank to the next comment
     91  * line.  Blanks and tabs from the beginning of the input line are removed.
     92  *
     93  * ALGORITHM:
     94  *	1) Decide where the comment should be aligned, and if lines should
     95  *	   be broken.
     96  *	2) If lines should not be broken and filled, just copy up to end of
     97  *	   comment.
     98  *	3) If lines should be filled, then scan through the input buffer,
     99  *	   copying characters to com_buf.  Remember where the last blank,
    100  *	   tab, or newline was.  When line is filled, print up to last blank
    101  *	   and continue copying.
    102  */
    103 void
    104 process_comment(void)
    105 {
    106     int adj_max_line_length;	/* Adjusted max_line_length for comments that
    107 				 * spill over the right margin */
    108     ssize_t last_blank;		/* index of the last blank in com.buf */
    109     bool break_delim = opt.comment_delimiter_on_blankline;
    110     int l_just_saw_decl = ps.just_saw_decl;
    111 
    112     adj_max_line_length = opt.max_line_length;
    113     ps.just_saw_decl = 0;
    114     last_blank = -1;		/* no blanks found so far */
    115     bool may_wrap = true;
    116     ps.stats.comments++;
    117 
    118     /* Figure where to align and how to treat the comment */
    119 
    120     if (ps.col_1 && !opt.format_col1_comments) {
    121 	may_wrap = false;
    122 	break_delim = false;
    123 	ps.com_ind = 0;
    124 
    125     } else {
    126 	if (*inp.s == '-' || *inp.s == '*' || token.e[-1] == '/' ||
    127 	    (*inp.s == '\n' && !opt.format_block_comments)) {
    128 	    may_wrap = false;
    129 	    break_delim = false;
    130 	}
    131 
    132 	if (lab.s == lab.e && code.s == code.e) {
    133 	    ps.com_ind = (ps.ind_level - opt.unindent_displace) * opt.indent_size;
    134 	    adj_max_line_length = opt.block_comment_max_line_length;
    135 	    if (ps.com_ind <= 0)
    136 		ps.com_ind = opt.format_col1_comments ? 0 : 1;
    137 
    138 	} else {
    139 	    break_delim = false;
    140 
    141 	    int target_ind;
    142 	    if (code.s != code.e)
    143 		target_ind = indentation_after(compute_code_indent(), code.s);
    144 	    else if (lab.s != lab.e)
    145 		target_ind = indentation_after(compute_label_indent(), lab.s);
    146 	    else
    147 		target_ind = 0;
    148 
    149 	    ps.com_ind = ps.decl_on_line || ps.ind_level == 0
    150 		? opt.decl_comment_column - 1 : opt.comment_column - 1;
    151 	    if (ps.com_ind <= target_ind)
    152 		ps.com_ind = next_tab(target_ind);
    153 	    /* XXX: the '+ 1' smells like an off-by-one error */
    154 	    if (ps.com_ind + 1 + 24 > adj_max_line_length)
    155 		adj_max_line_length = ps.com_ind + 1 + 24;
    156 	}
    157     }
    158 
    159     if (!may_wrap) {
    160 	/*
    161 	 * Find out how much indentation there was originally, because that
    162 	 * much will have to be ignored by dump_line(). This is a box comment,
    163 	 * so nothing changes -- not even indentation.
    164 	 *
    165 	 * The comment we're about to read usually comes from inp.buf,
    166 	 * unless it has been copied into save_com.
    167 	 */
    168 	const char *start;
    169 
    170 	/*
    171 	 * XXX: ordered comparison between pointers from different objects
    172 	 * invokes undefined behavior (C99 6.5.8).
    173 	 */
    174 	start = inp.s >= save_com && inp.s < save_com + sc_size ?
    175 	    sc_buf : inp.buf;
    176 	ps.n_comment_delta = -indentation_after_range(0, start, inp.s - 2);
    177     } else {
    178 	ps.n_comment_delta = 0;
    179 	while (is_hspace(*inp.s))
    180 	    inp.s++;
    181     }
    182 
    183     ps.comment_delta = 0;
    184     com_add_char('/');
    185     com_add_char(token.e[-1]);	/* either '*' or '/' */
    186     if (*inp.s != ' ' && may_wrap)
    187 	com_add_char(' ');
    188 
    189     /* Don't put a break delimiter if this is a one-liner that won't wrap. */
    190     if (break_delim) {
    191 	for (const char *p = inp.s; *p != '\n'; p++) {
    192 	    assert(*p != '\0');
    193 	    assert(inp.e - p >= 2);
    194 	    if (!(p[0] == '*' && p[1] == '/'))
    195 		continue;
    196 
    197 	    int len = indentation_after_range(ps.com_ind + 3, inp.s, p) +
    198 		(is_hspace(p[-1]) ? 2 : 3);
    199 	    if (len <= adj_max_line_length)
    200 		break_delim = false;
    201 	    break;
    202 	}
    203     }
    204 
    205     if (break_delim) {
    206 	char *t = com.e;
    207 	com.e = com.s + 2;
    208 	*com.e = '\0';
    209 	if (opt.blanklines_before_block_comments && ps.last_token != lbrace)
    210 	    prefix_blankline_requested = true;
    211 	dump_line();
    212 	com.e = com.s = t;
    213 	com_add_delim();
    214     }
    215 
    216     /* Start to copy the comment */
    217 
    218     for (;;) {			/* this loop will go until the comment is
    219 				 * copied */
    220 	switch (*inp.s) {	/* this checks for various special cases */
    221 	case '\f':
    222 	    if (may_wrap) {	/* in a text comment, break the line here */
    223 		ps.use_ff = true;
    224 		dump_line();
    225 		last_blank = -1;
    226 		com_add_delim();
    227 		inp.s++;
    228 		while (is_hspace(*inp.s))
    229 		    inp.s++;
    230 	    } else {
    231 		inbuf_skip();
    232 		com_add_char('\f');
    233 	    }
    234 	    break;
    235 
    236 	case '\n':
    237 	    if (token.e[-1] == '/')
    238 		goto end_of_line_comment;
    239 
    240 	    if (had_eof) {
    241 		diag(1, "Unterminated comment");
    242 		dump_line();
    243 		return;
    244 	    }
    245 
    246 	    last_blank = -1;
    247 	    if (!may_wrap || ps.last_nl) {	/* if this is a boxed comment,
    248 						 * we handle the newline */
    249 		if (com.s == com.e)
    250 		    com_add_char(' ');
    251 		if (may_wrap && com.e - com.s > 3) {
    252 		    dump_line();
    253 		    com_add_delim();
    254 		}
    255 		dump_line();
    256 		if (may_wrap)
    257 		    com_add_delim();
    258 
    259 	    } else {
    260 		ps.last_nl = true;
    261 		if (!is_hspace(com.e[-1]))
    262 		    com_add_char(' ');
    263 		last_blank = com.e - 1 - com.buf;
    264 	    }
    265 	    ++line_no;
    266 	    if (may_wrap) {
    267 		bool skip_asterisk = true;
    268 		do {		/* flush any blanks and/or tabs at start of
    269 				 * next line */
    270 		    inbuf_skip();
    271 		    if (*inp.s == '*' && skip_asterisk) {
    272 			skip_asterisk = false;
    273 			inbuf_skip();
    274 			if (*inp.s == '/')
    275 			    goto end_of_comment;
    276 		    }
    277 		} while (is_hspace(*inp.s));
    278 	    } else
    279 		inbuf_skip();
    280 	    break;		/* end of case for newline */
    281 
    282 	case '*':
    283 	    inbuf_skip();
    284 	    if (*inp.s == '/') {
    285 	end_of_comment:
    286 		inbuf_skip();
    287 
    288 	end_of_line_comment:
    289 		if (break_delim) {
    290 		    if (com.e > com.s + 3)
    291 			dump_line();
    292 		    else
    293 			com.s = com.e;	/* XXX: why not e = s? */
    294 		    com_add_char(' ');
    295 		}
    296 
    297 		if (!is_hspace(com.e[-1]) && may_wrap)
    298 		    com_add_char(' ');
    299 		if (token.e[-1] != '/') {
    300 		    com_add_char('*');
    301 		    com_add_char('/');
    302 		}
    303 		com_terminate();
    304 
    305 		ps.just_saw_decl = l_just_saw_decl;
    306 		return;
    307 
    308 	    } else		/* handle isolated '*' */
    309 		com_add_char('*');
    310 	    break;
    311 
    312 	default:		/* we have a random char */
    313 	    ;
    314 	    int now_len = indentation_after_range(ps.com_ind, com.s, com.e);
    315 	    for (;;) {
    316 		char ch = inbuf_next();
    317 		if (is_hspace(ch))
    318 		    last_blank = com.e - com.buf;
    319 		com_add_char(ch);
    320 		now_len++;
    321 		if (memchr("*\n\r\b\t", *inp.s, 6) != NULL)
    322 		    break;
    323 		if (now_len >= adj_max_line_length && last_blank != -1)
    324 		    break;
    325 	    }
    326 
    327 	    ps.last_nl = false;
    328 
    329 	    /* XXX: signed character comparison '>' does not work for UTF-8 */
    330 	    if (now_len > adj_max_line_length &&
    331 		    may_wrap && com.e[-1] > ' ') {
    332 
    333 		/* the comment is too long, it must be broken up */
    334 		if (last_blank == -1) {
    335 		    dump_line();
    336 		    com_add_delim();
    337 		    break;
    338 		}
    339 
    340 		com_terminate();	/* mark the end of the last word */
    341 		com.e = com.buf + last_blank;
    342 		dump_line();
    343 
    344 		com_add_delim();
    345 
    346 		const char *p = com.buf + last_blank + 1;
    347 		while (is_hspace(*p))
    348 		    p++;
    349 		last_blank = -1;
    350 
    351 		/*
    352 		 * p still points to the last word from the previous line, in
    353 		 * the same buffer that it is copied to, but to the right of
    354 		 * the writing region [com.s, com.e). Calling dump_line only
    355 		 * moved com.e back to com.s, it did not clear the contents of
    356 		 * the buffer. This ensures that the buffer is already large
    357 		 * enough.
    358 		 */
    359 		while (*p != '\0') {
    360 		    assert(!is_hspace(*p));
    361 		    *com.e++ = *p++;
    362 		}
    363 	    }
    364 	    break;
    365 	}
    366     }
    367 }
    368