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