Home | History | Annotate | Line # | Download | only in indent
pr_comment.c revision 1.74
      1 /*	$NetBSD: pr_comment.c,v 1.74 2021/10/12 22:04:03 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.74 2021/10/12 22:04:03 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 box_com = false;	/* at first, assume that we are not in a boxed
    116 				 * comment or some other comment that should
    117 				 * not be touched */
    118     ps.stats.comments++;
    119 
    120     /* Figure where to align and how to treat the comment */
    121 
    122     if (ps.col_1 && !opt.format_col1_comments) { /* if the comment starts in
    123 				 * column 1, it should not be touched */
    124 	box_com = true;
    125 	break_delim = false;
    126 	ps.com_ind = 0;
    127 
    128     } else {
    129 	if (*inp.s == '-' || *inp.s == '*' || token.e[-1] == '/' ||
    130 	    (*inp.s == '\n' && !opt.format_block_comments)) {
    131 	    box_com = true;
    132 	    break_delim = false;
    133 	}
    134 
    135 	if (lab.s == lab.e && code.s == code.e) {
    136 	    ps.com_ind = (ps.ind_level - opt.unindent_displace) * opt.indent_size;
    137 	    adj_max_line_length = opt.block_comment_max_line_length;
    138 	    if (ps.com_ind <= 0)
    139 		ps.com_ind = opt.format_col1_comments ? 0 : 1;
    140 
    141 	} else {
    142 	    break_delim = false;
    143 
    144 	    int target_ind;
    145 	    if (code.s != code.e)
    146 		target_ind = indentation_after(compute_code_indent(), code.s);
    147 	    else if (lab.s != lab.e)
    148 		target_ind = indentation_after(compute_label_indent(), lab.s);
    149 	    else
    150 		target_ind = 0;
    151 
    152 	    ps.com_ind = ps.decl_on_line || ps.ind_level == 0
    153 		? opt.decl_comment_column - 1 : opt.comment_column - 1;
    154 	    if (ps.com_ind <= target_ind)
    155 		ps.com_ind = next_tab(target_ind);
    156 	    /* XXX: the '+ 1' smells like an off-by-one error */
    157 	    if (ps.com_ind + 1 + 24 > adj_max_line_length)
    158 		adj_max_line_length = ps.com_ind + 1 + 24;
    159 	}
    160     }
    161 
    162     if (box_com) {
    163 	/*
    164 	 * Find out how much indentation there was originally, because that
    165 	 * much will have to be ignored by dump_line(). This is a box comment,
    166 	 * so nothing changes -- not even indentation.
    167 	 *
    168 	 * The comment we're about to read usually comes from inp.buf,
    169 	 * unless it has been copied into save_com.
    170 	 */
    171 	const char *start;
    172 
    173 	/*
    174 	 * XXX: ordered comparison between pointers from different objects
    175 	 * invokes undefined behavior (C99 6.5.8).
    176 	 */
    177 	start = inp.s >= save_com && inp.s < save_com + sc_size ?
    178 	    sc_buf : inp.buf;
    179 	ps.n_comment_delta = -indentation_after_range(0, start, inp.s - 2);
    180     } else {
    181 	ps.n_comment_delta = 0;
    182 	while (is_hspace(*inp.s))
    183 	    inp.s++;
    184     }
    185 
    186     ps.comment_delta = 0;
    187     com_add_char('/');
    188     com_add_char(token.e[-1]);	/* either '*' or '/' */
    189     if (*inp.s != ' ' && !box_com)
    190 	com_add_char(' ');
    191 
    192     /* Don't put a break delimiter if this is a one-liner that won't wrap. */
    193     if (break_delim) {
    194 	for (const char *p = inp.s; *p != '\n'; p++) {
    195 	    assert(*p != '\0');
    196 	    assert(inp.e - p >= 2);
    197 	    if (!(p[0] == '*' && p[1] == '/'))
    198 		continue;
    199 
    200 	    int len = indentation_after_range(ps.com_ind + 3, inp.s, p) +
    201 		(is_hspace(p[-1]) ? 2 : 3);
    202 	    if (len <= adj_max_line_length)
    203 		break_delim = false;
    204 	    break;
    205 	}
    206     }
    207 
    208     if (break_delim) {
    209 	char *t = com.e;
    210 	com.e = com.s + 2;
    211 	*com.e = '\0';
    212 	if (opt.blanklines_before_block_comments && ps.last_token != lbrace)
    213 	    prefix_blankline_requested = true;
    214 	dump_line();
    215 	com.e = com.s = t;
    216 	if (!box_com)
    217 	    com_add_delim();
    218     }
    219 
    220     /* Start to copy the comment */
    221 
    222     for (;;) {			/* this loop will go until the comment is
    223 				 * copied */
    224 	switch (*inp.s) {	/* this checks for various special cases */
    225 	case '\f':
    226 	    if (!box_com) {	/* in a text comment, break the line here */
    227 		ps.use_ff = true;
    228 		dump_line();
    229 		last_blank = -1;
    230 		com_add_delim();
    231 		inp.s++;
    232 		while (is_hspace(*inp.s))
    233 		    inp.s++;
    234 	    } else {
    235 		inbuf_skip();
    236 		com_add_char('\f');
    237 	    }
    238 	    break;
    239 
    240 	case '\n':
    241 	    if (token.e[-1] == '/')
    242 		goto end_of_line_comment;
    243 
    244 	    if (had_eof) {
    245 		diag(1, "Unterminated comment");
    246 		dump_line();
    247 		return;
    248 	    }
    249 
    250 	    last_blank = -1;
    251 	    if (box_com || ps.last_nl) {	/* if this is a boxed comment,
    252 						 * we handle the newline */
    253 		if (com.s == com.e)
    254 		    com_add_char(' ');
    255 		if (!box_com && com.e - com.s > 3) {
    256 		    dump_line();
    257 		    com_add_delim();
    258 		}
    259 		dump_line();
    260 		if (!box_com)
    261 		    com_add_delim();
    262 
    263 	    } else {
    264 		ps.last_nl = true;
    265 		if (!is_hspace(com.e[-1]))
    266 		    com_add_char(' ');
    267 		last_blank = com.e - 1 - com.buf;
    268 	    }
    269 	    ++line_no;
    270 	    if (!box_com) {
    271 		int asterisks_to_skip = 1;
    272 		do {		/* flush any blanks and/or tabs at start of
    273 				 * next line */
    274 		    inbuf_skip();
    275 		    if (*inp.s == '*' && --asterisks_to_skip >= 0) {
    276 			inbuf_skip();
    277 			if (*inp.s == '/')
    278 			    goto end_of_comment;
    279 		    }
    280 		} while (is_hspace(*inp.s));
    281 	    } else
    282 		inbuf_skip();
    283 	    break;		/* end of case for newline */
    284 
    285 	case '*':
    286 	    inbuf_skip();
    287 	    if (*inp.s == '/') {
    288 	end_of_comment:
    289 		inbuf_skip();
    290 
    291 	end_of_line_comment:
    292 		if (break_delim) {
    293 		    if (com.e > com.s + 3)
    294 			dump_line();
    295 		    else
    296 			com.s = com.e;	/* XXX: why not e = s? */
    297 		    com_add_char(' ');
    298 		}
    299 
    300 		if (!is_hspace(com.e[-1]) && !box_com)
    301 		    com_add_char(' ');
    302 		if (token.e[-1] != '/') {
    303 		    com_add_char('*');
    304 		    com_add_char('/');
    305 		}
    306 		com_terminate();
    307 
    308 		ps.just_saw_decl = l_just_saw_decl;
    309 		return;
    310 
    311 	    } else		/* handle isolated '*' */
    312 		com_add_char('*');
    313 	    break;
    314 
    315 	default:		/* we have a random char */
    316 	    ;
    317 	    int now_len = indentation_after_range(ps.com_ind, com.s, com.e);
    318 	    for (;;) {
    319 		char ch = inbuf_next();
    320 		if (is_hspace(ch))
    321 		    last_blank = com.e - com.buf;
    322 		com_add_char(ch);
    323 		now_len++;
    324 		if (memchr("*\n\r\b\t", *inp.s, 6) != NULL)
    325 		    break;
    326 		if (now_len >= adj_max_line_length && last_blank != -1)
    327 		    break;
    328 	    }
    329 
    330 	    ps.last_nl = false;
    331 
    332 	    /* XXX: signed character comparison '>' does not work for UTF-8 */
    333 	    if (now_len > adj_max_line_length &&
    334 		    !box_com && com.e[-1] > ' ') {
    335 
    336 		/* the comment is too long, it must be broken up */
    337 		if (last_blank == -1) {
    338 		    dump_line();
    339 		    com_add_delim();
    340 		    break;
    341 		}
    342 
    343 		com_terminate();	/* mark the end of the last word */
    344 		com.e = com.buf + last_blank;
    345 		dump_line();
    346 
    347 		com_add_delim();
    348 
    349 		const char *p = com.buf + last_blank + 1;
    350 		while (is_hspace(*p))
    351 		    p++;
    352 		last_blank = -1;
    353 
    354 		/*
    355 		 * p still points to the last word from the previous line, in
    356 		 * the same buffer that it is copied to, but to the right of
    357 		 * the writing region [com.s, com.e). Calling dump_line only
    358 		 * moved com.e back to com.s, it did not clear the contents of
    359 		 * the buffer. This ensures that the buffer is already large
    360 		 * enough.
    361 		 */
    362 		while (*p != '\0') {
    363 		    assert(!is_hspace(*p));
    364 		    *com.e++ = *p++;
    365 		}
    366 	    }
    367 	    break;
    368 	}
    369     }
    370 }
    371