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