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