Home | History | Annotate | Line # | Download | only in indent
pr_comment.c revision 1.118
      1 /*	$NetBSD: pr_comment.c,v 1.118 2021/11/19 15:32:13 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.118 2021/11/19 15:32:13 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 = inbuf.inp.s; *p != '\n'; p++) {
     90 	assert(*p != '\0');
     91 	assert(inbuf.inp.e - p >= 2);
     92 	if (!(p[0] == '*' && p[1] == '/'))
     93 	    continue;
     94 
     95 	int len = ind_add(ps.com_ind + 3, inbuf.inp.s, p);
     96 	len += ch_isblank(p[-1]) ? 2 : 3;
     97 	return len <= max_line_length;
     98     }
     99     return false;
    100 }
    101 
    102 static void
    103 analyze_comment(bool *p_may_wrap, bool *p_break_delim,
    104     int *p_adj_max_line_length)
    105 {
    106     int adj_max_line_length;	/* Adjusted max_line_length for comments that
    107 				 * spill over the right margin */
    108     bool break_delim = opt.comment_delimiter_on_blankline;
    109     int com_ind;
    110 
    111     adj_max_line_length = opt.max_line_length;
    112     bool may_wrap = true;
    113 
    114     if (ps.curr_col_1 && !opt.format_col1_comments) {
    115 	may_wrap = false;
    116 	break_delim = false;
    117 	com_ind = 0;
    118 
    119     } else {
    120 	if (*inbuf.inp.s == '-' || *inbuf.inp.s == '*' ||
    121 		token.e[-1] == '/' ||
    122 		(*inbuf.inp.s == '\n' && !opt.format_block_comments)) {
    123 	    may_wrap = false;
    124 	    break_delim = false;
    125 	}
    126 
    127 	if (lab.s == lab.e && code.s == code.e) {
    128 	    adj_max_line_length = opt.block_comment_max_line_length;
    129 	    com_ind = (ps.ind_level - opt.unindent_displace) * opt.indent_size;
    130 	    if (com_ind <= 0)
    131 		com_ind = opt.format_col1_comments ? 0 : 1;
    132 
    133 	} else {
    134 	    break_delim = false;
    135 
    136 	    int target_ind = code.s != code.e
    137 		? ind_add(compute_code_indent(), code.s, code.e)
    138 		: ind_add(compute_label_indent(), lab.s, lab.e);
    139 
    140 	    com_ind = ps.decl_on_line || ps.ind_level == 0
    141 		? opt.decl_comment_column - 1 : opt.comment_column - 1;
    142 	    if (com_ind <= target_ind)
    143 		com_ind = next_tab(target_ind);
    144 	    if (com_ind + 25 > adj_max_line_length)
    145 		adj_max_line_length = com_ind + 25;
    146 	}
    147     }
    148 
    149     ps.com_ind = com_ind;
    150 
    151     if (!may_wrap) {
    152 	/*
    153 	 * Find out how much indentation there was originally, because that
    154 	 * much will have to be ignored by dump_line().
    155 	 *
    156 	 * The comment we're about to read usually comes from inp.buf, unless
    157 	 * it has been copied into save_com.
    158 	 *
    159 	 * XXX: ordered comparison between pointers from different objects
    160 	 * invokes undefined behavior (C99 6.5.8).
    161 	 */
    162 	const char *start = inbuf.inp.s >= inbuf.save_com_buf &&
    163 		inbuf.inp.s <
    164 		    inbuf.save_com_buf + array_length(inbuf.save_com_buf)
    165 	    ? inbuf.save_com_buf : inbuf.inp.buf;
    166 	ps.n_comment_delta = -ind_add(0, start, inbuf.inp.s - 2);
    167     } else {
    168 	ps.n_comment_delta = 0;
    169 	while (ch_isblank(*inbuf.inp.s))
    170 	    inbuf.inp.s++;
    171     }
    172 
    173     ps.comment_delta = 0;
    174     com_add_char('/');
    175     com_add_char(token.e[-1]);	/* either '*' or '/' */
    176 
    177     /* TODO: Maybe preserve a single '\t' as well. */
    178     if (*inbuf.inp.s != ' ' && may_wrap)
    179 	com_add_char(' ');
    180 
    181     if (break_delim && fits_in_one_line(adj_max_line_length))
    182 	break_delim = false;
    183 
    184     if (break_delim) {
    185 	com.e = com.s + 2;
    186 	*com.e = '\0';
    187 	if (opt.blanklines_before_block_comments &&
    188 		ps.prev_token != lsym_lbrace)
    189 	    blank_line_before = true;
    190 	dump_line();
    191 	com_add_delim();
    192     }
    193 
    194     *p_adj_max_line_length = adj_max_line_length;
    195     *p_break_delim = break_delim;
    196     *p_may_wrap = may_wrap;
    197 }
    198 
    199 /*
    200  * Copy characters from 'inp' to 'com'. Try to keep comments from going over
    201  * the maximum line length. To do that, remember where the last blank, tab, or
    202  * newline was. When a line is filled, print up to the last blank and continue
    203  * copying.
    204  */
    205 static void
    206 copy_comment_wrap(int adj_max_line_length, bool break_delim)
    207 {
    208     ssize_t last_blank = -1;	/* index of the last blank in com.buf */
    209 
    210     for (;;) {
    211 	switch (*inbuf.inp.s) {
    212 	case '\f':
    213 	    dump_line_ff();
    214 	    last_blank = -1;
    215 	    com_add_delim();
    216 	    inbuf.inp.s++;
    217 	    while (ch_isblank(*inbuf.inp.s))
    218 		inbuf.inp.s++;
    219 	    break;
    220 
    221 	case '\n':
    222 	    if (had_eof) {
    223 		diag(1, "Unterminated comment");
    224 		dump_line();
    225 		return;
    226 	    }
    227 
    228 	    last_blank = -1;
    229 	    if (ps.next_col_1) {
    230 		if (com.s == com.e)
    231 		    com_add_char(' ');	/* force empty line of output */
    232 		if (com.e - com.s > 3) {
    233 		    dump_line();
    234 		    com_add_delim();
    235 		}
    236 		dump_line();
    237 		com_add_delim();
    238 
    239 	    } else {
    240 		ps.next_col_1 = true;
    241 		if (!(com.e > com.s && ch_isblank(com.e[-1])))
    242 		    com_add_char(' ');
    243 		last_blank = com.e - 1 - com.buf;
    244 	    }
    245 	    ++line_no;
    246 
    247 	    bool skip_asterisk = true;
    248 	    do {		/* flush any blanks and/or tabs at start of
    249 				 * next line */
    250 		inp_skip();
    251 		if (*inbuf.inp.s == '*' && skip_asterisk) {
    252 		    skip_asterisk = false;
    253 		    inp_skip();
    254 		    if (*inbuf.inp.s == '/')
    255 			goto end_of_comment;
    256 		}
    257 	    } while (ch_isblank(*inbuf.inp.s));
    258 
    259 	    break;		/* end of case for newline */
    260 
    261 	case '*':
    262 	    inp_skip();
    263 	    if (*inbuf.inp.s == '/') {
    264 	end_of_comment:
    265 		inp_skip();
    266 
    267 		if (break_delim) {
    268 		    if (com.e - com.s > 3)
    269 			dump_line();
    270 		    else
    271 			com.e = com.s;
    272 		    com_add_char(' ');
    273 		}
    274 
    275 		if (!(com.e > com.s && ch_isblank(com.e[-1])))
    276 		    com_add_char(' ');
    277 		com_add_char('*');
    278 		com_add_char('/');
    279 		com_terminate();
    280 		return;
    281 
    282 	    } else		/* handle isolated '*' */
    283 		com_add_char('*');
    284 	    break;
    285 
    286 	default:		/* we have a random char */
    287 	    ;
    288 	    int now_len = ind_add(ps.com_ind, com.s, com.e);
    289 	    for (;;) {
    290 		char ch = inp_next();
    291 		if (ch_isblank(ch))
    292 		    last_blank = com.e - com.buf;
    293 		com_add_char(ch);
    294 		now_len++;
    295 		if (memchr("*\n\r\b\t", *inbuf.inp.s, 6) != NULL)
    296 		    break;
    297 		if (now_len >= adj_max_line_length && last_blank != -1)
    298 		    break;
    299 	    }
    300 
    301 	    ps.next_col_1 = false;
    302 
    303 	    if (now_len <= adj_max_line_length)
    304 		break;
    305 	    if (isspace((unsigned char)com.e[-1]))
    306 		break;
    307 
    308 	    if (last_blank == -1) {	/* only a single word in this line */
    309 		dump_line();
    310 		com_add_delim();
    311 		break;
    312 	    }
    313 
    314 	    const char *last_word_s = com.buf + last_blank + 1;
    315 	    size_t last_word_len = (size_t)(com.e - last_word_s);
    316 	    com.e = com.buf + last_blank;
    317 	    dump_line();
    318 	    com_add_delim();
    319 
    320 	    memcpy(com.e, last_word_s, last_word_len);
    321 	    com.e += last_word_len;
    322 	    last_blank = -1;
    323 	}
    324     }
    325 }
    326 
    327 static void
    328 copy_comment_nowrap(void)
    329 {
    330     for (;;) {
    331 	if (*inbuf.inp.s == '\n') {
    332 	    if (token.e[-1] == '/')
    333 		goto finish;
    334 
    335 	    if (had_eof) {
    336 		diag(1, "Unterminated comment");
    337 		dump_line();
    338 		return;
    339 	    }
    340 
    341 	    if (com.s == com.e)
    342 		com_add_char(' ');	/* force output of an empty line */
    343 	    dump_line();
    344 	    ++line_no;
    345 	    inp_skip();
    346 	    continue;
    347 	}
    348 
    349 	com_add_char(inp_next());
    350 	if (com.e[-2] == '*' && com.e[-1] == '/' && token.e[-1] == '*')
    351 	    goto finish;
    352     }
    353 
    354 finish:
    355     com_terminate();
    356 }
    357 
    358 /*
    359  * Scan, reformat and output a single comment, which is either a block comment
    360  * starting with '/' '*' or an end-of-line comment starting with '//'.
    361  */
    362 void
    363 process_comment(void)
    364 {
    365     int adj_max_line_length;
    366     bool may_wrap, break_delim;
    367 
    368     ps.just_saw_decl = 0;
    369     ps.stats.comments++;
    370 
    371     int saved_just_saw_decl = ps.just_saw_decl;
    372     analyze_comment(&may_wrap, &break_delim, &adj_max_line_length);
    373     if (may_wrap)
    374 	copy_comment_wrap(adj_max_line_length, break_delim);
    375     else
    376 	copy_comment_nowrap();
    377     ps.just_saw_decl = saved_just_saw_decl;
    378 }
    379