Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.208
      1 /*	$NetBSD: indent.h,v 1.208 2025/01/03 23:37:18 rillig Exp $	*/
      2 
      3 /*-
      4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
      5  *
      6  * Copyright (c) 2001 Jens Schweikhardt
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
     19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
     22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     28  * SUCH DAMAGE.
     29  */
     30 /*-
     31  * SPDX-License-Identifier: BSD-4-Clause
     32  *
     33  * Copyright (c) 1985 Sun Microsystems, Inc.
     34  * Copyright (c) 1980, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  * All rights reserved.
     37  *
     38  * Redistribution and use in source and binary forms, with or without
     39  * modification, are permitted provided that the following conditions
     40  * are met:
     41  * 1. Redistributions of source code must retain the above copyright
     42  *    notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *    notice, this list of conditions and the following disclaimer in the
     45  *    documentation and/or other materials provided with the distribution.
     46  * 3. All advertising materials mentioning features or use of this software
     47  *    must display the following acknowledgement:
     48  *	This product includes software developed by the University of
     49  *	California, Berkeley and its contributors.
     50  * 4. Neither the name of the University nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  */
     66 
     67 #include <ctype.h>
     68 #include <stdbool.h>
     69 #include <stdio.h>
     70 
     71 typedef enum lexer_symbol {
     72 	lsym_eof,
     73 	lsym_preprocessing,	/* the initial '#' of a preprocessing line */
     74 	lsym_newline,		/* outside block comments */
     75 	lsym_comment,		/* the initial '/ *' or '//' of a comment */
     76 
     77 	lsym_lparen,
     78 	lsym_rparen,
     79 	lsym_lbracket,
     80 	lsym_rbracket,
     81 	lsym_lbrace,
     82 	lsym_rbrace,
     83 
     84 	lsym_period,
     85 	lsym_unary_op,		/* e.g. '*', '&', '-' or leading '++' */
     86 	lsym_sizeof,
     87 	lsym_offsetof,
     88 	lsym_postfix_op,	/* trailing '++' or '--' */
     89 	lsym_binary_op,		/* e.g. '*', '&', '<<', '&&' or '/=' */
     90 	lsym_question,		/* the '?' from a '?:' expression */
     91 	lsym_question_colon,	/* the ':' from a '?:' expression */
     92 	lsym_comma,
     93 
     94 	lsym_typedef,
     95 	lsym_modifier,		/* modifiers for types, functions, variables */
     96 	lsym_tag,		/* 'struct', 'union' or 'enum' */
     97 	lsym_type,
     98 	lsym_word,		/* identifier, constant or string */
     99 	lsym_funcname,		/* name of a function being defined */
    100 	lsym_label_colon,	/* the ':' after a label */
    101 	lsym_other_colon,	/* bit-fields, generic-association (C11),
    102 				 * enum-type-specifier (C23),
    103 				 * attribute-prefixed-token (C23),
    104 				 * pp-prefixed-parameter (C23 6.10) */
    105 	lsym_semicolon,
    106 
    107 	lsym_case,
    108 	lsym_default,
    109 	lsym_do,
    110 	lsym_else,
    111 	lsym_for,
    112 	lsym_if,
    113 	lsym_switch,
    114 	lsym_while,
    115 	lsym_return,
    116 } lexer_symbol;
    117 
    118 /*
    119  * Structure of the source code, in terms of declarations, statements and
    120  * braces; used to determine the indentation level of these parts.
    121  */
    122 typedef enum parser_symbol {
    123 	psym_0,			/* a placeholder; not stored on the stack */
    124 	psym_lbrace_block,	/* '{' for a block of code */
    125 	psym_lbrace_struct,	/* '{' in 'struct ... { ... }' */
    126 	psym_lbrace_union,	/* '{' in 'union ... { ... }' */
    127 	psym_lbrace_enum,	/* '{' in 'enum ... { ... }' */
    128 	psym_rbrace,		/* not stored on the stack */
    129 	psym_decl,
    130 	psym_stmt,
    131 	psym_for_exprs,		/* 'for' '(' ... ')' */
    132 	psym_if_expr,		/* 'if' '(' expr ')' */
    133 	psym_if_expr_stmt,	/* 'if' '(' expr ')' stmt */
    134 	psym_if_expr_stmt_else,	/* 'if' '(' expr ')' stmt 'else' */
    135 	psym_else,		/* 'else'; not stored on the stack */
    136 	psym_switch_expr,	/* 'switch' '(' expr ')' */
    137 	psym_do,		/* 'do' */
    138 	psym_do_stmt,		/* 'do' stmt */
    139 	psym_while_expr,	/* 'while' '(' expr ')' */
    140 } parser_symbol;
    141 
    142 /* A range of characters, only null-terminated in debug mode. */
    143 struct buffer {
    144 	char *s;
    145 	size_t len;
    146 	size_t cap;
    147 };
    148 
    149 /*
    150  * The current input file, used by the lexer to generate tokens.
    151  * To read from the input, start at p and continue up to and including the
    152  * next '\n'. To read beyond the '\n', call inp_skip or inp_next, which will
    153  * make the next line available, invalidating any pointers into the previous
    154  * line.
    155  */
    156 extern struct input_state {
    157 	FILE *f;
    158 	struct buffer line;
    159 	const char *p;
    160 	int token_start_line;
    161 	int token_end_line;
    162 } in;
    163 
    164 extern FILE *output;
    165 
    166 extern struct buffer token;	/* the current token to be processed, is
    167 				 * typically copied to the buffer 'code', or in
    168 				 * some cases to 'lab'. */
    169 
    170 extern struct buffer lab;	/* the label or preprocessor directive */
    171 extern struct buffer code;	/* the main part of the current line of code,
    172 				 * containing declarations or statements */
    173 extern struct buffer com;	/* the trailing comment of the line, or the
    174 				 * start or end of a multi-line comment, or
    175 				 * while in process_comment, a single line of a
    176 				 * multi-line comment */
    177 
    178 extern struct options {
    179 	bool blank_line_around_conditional_compilation;
    180 	bool blank_line_after_decl_at_top;	/* this is vaguely similar to
    181 						 * blank_line_after_decl except
    182 						 * that it only applies to the
    183 						 * first set of declarations in
    184 						 * a procedure (just after the
    185 						 * first '{') and it causes a
    186 						 * blank line to be generated
    187 						 * even if there are no
    188 						 * declarations */
    189 	bool blank_line_after_decl;
    190 	bool blank_line_after_proc;
    191 	bool blank_line_before_block_comment;
    192 	bool break_after_comma;	/* whether to add a line break after each
    193 				 * declarator */
    194 	bool brace_same_line;	/* whether a brace should be on same line as an
    195 				 * if, while, etc. */
    196 	bool blank_after_sizeof;
    197 	bool comment_delimiter_on_blank_line;
    198 	int decl_comment_column;	/* the column in which comments after
    199 					 * declarations should be put */
    200 	bool cuddle_else;	/* whether 'else' should cuddle up to '}' */
    201 	int continuation_indent;	/* the indentation between the edge of
    202 					 * code and continuation lines */
    203 	float case_indent;	/* the distance (measured in indentation
    204 				 * levels) to indent case labels from the
    205 				 * switch statement */
    206 	int comment_column;	/* the column in which comments to the right of
    207 				 * code should start */
    208 	int decl_indent;	/* indentation of identifier in declaration */
    209 	bool left_justify_decl;
    210 	int unindent_displace;	/* comments not to the right of code will be
    211 				 * placed this many indentation levels to the
    212 				 * left of code */
    213 	bool extra_expr_indent;	/* whether continuation lines from the
    214 				 * expression part of "if (e)", "while (e)",
    215 				 * "for (e; e; e)" should be indented an extra
    216 				 * tab stop so that they are not confused with
    217 				 * the code that follows */
    218 	bool else_if_in_same_line;
    219 	bool function_brace_split;	/* split function declaration and brace
    220 					 * onto separate lines */
    221 	bool format_col1_comments;	/* whether comments that start in
    222 					 * column 1 are to be reformatted (just
    223 					 * like comments that begin in later
    224 					 * columns) */
    225 	bool format_block_comments;	/* whether to reformat comments that
    226 					 * begin with '/ * \n' */
    227 	bool indent_parameters;
    228 	int indent_size;	/* the size of one indentation level */
    229 	int block_comment_max_line_length;
    230 	int local_decl_indent;	/* like decl_indent but for locals */
    231 	bool lineup_to_parens_always;	/* whether to not(?) attempt to keep
    232 					 * lined-up code within the margin */
    233 	bool lineup_to_parens;	/* whether continued code within parens will be
    234 				 * lined up to the open paren */
    235 	bool proc_calls_space;	/* whether function calls look like 'foo (bar)'
    236 				 * rather than 'foo(bar)' */
    237 	bool procnames_start_line;	/* whether the names of functions being
    238 					 * defined get placed in column 1 (i.e.
    239 					 * a newline is placed between the type
    240 					 * of the function and its name) */
    241 	bool space_after_cast;	/* "b = (int) a" vs. "b = (int)a" */
    242 	bool star_comment_cont;	/* whether comment continuation lines should
    243 				 * have stars at the beginning of each line */
    244 	bool swallow_optional_blank_lines;
    245 	bool auto_typedefs;	/* whether to recognize identifiers ending in
    246 				 * "_t" like typedefs */
    247 	int tabsize;		/* the size of a tab */
    248 	int max_line_length;
    249 	bool use_tabs;		/* set true to use tabs for spacing, false uses
    250 				 * all spaces */
    251 	bool verbose;		/* print configuration to stderr */
    252 } opt;
    253 
    254 extern bool found_err;
    255 extern bool had_eof;		/* whether input is exhausted */
    256 extern enum indent_enabled {
    257 	indent_on,
    258 	indent_off,
    259 	indent_last_off_line,
    260 } indent_enabled;
    261 
    262 /* Properties of each level of parentheses or brackets. */
    263 struct paren_level {
    264 	int indent;		/* indentation of the operand/argument,
    265 				 * relative to the enclosing statement; if
    266 				 * negative, reflected at -1 */
    267 	enum paren_level_cast {
    268 		cast_unknown,
    269 		cast_maybe,
    270 		cast_no,
    271 	} cast;			/* whether the parentheses form a type cast */
    272 };
    273 
    274 struct psym_stack {
    275 	parser_symbol *sym;
    276 	int *ind_level;
    277 	size_t len;		/* points to one behind the top of the stack; 1
    278 				 * at the top level of the file outside a
    279 				 * declaration or statement; 2 at the top level
    280 				 */
    281 	size_t cap;
    282 };
    283 
    284 /*
    285  * The parser state determines the layout of the formatted text.
    286  *
    287  * At each '#if', the parser state is copied so that the corresponding '#else'
    288  * lines start in the same state.
    289  *
    290  * In a function body, the number of block braces determines the indentation
    291  * of statements and declarations.
    292  *
    293  * In a statement, the number of parentheses or brackets determines the
    294  * indentation of follow-up lines.
    295  *
    296  * In an expression, the token type determine whether to put spaces around.
    297  *
    298  * In a source file, the types of line determine the vertical spacing, such as
    299  * around preprocessing directives or function bodies, or above block
    300  * comments.
    301  */
    302 extern struct parser_state {
    303 	lexer_symbol prev_lsym;	/* the previous token, but never comment,
    304 				 * newline or preprocessing line */
    305 
    306 	/* Token classification */
    307 
    308 	bool in_stmt_or_decl;	/* whether in a statement or a struct
    309 				 * declaration or a plain declaration */
    310 	bool in_decl;		/* XXX: double-check the exact meaning */
    311 	bool in_typedef_decl;
    312 	bool in_var_decl;	/* starts at a type name or a '){' from a
    313 				 * compound literal; ends at the '(' from a
    314 				 * function definition or a ';' outside '{}';
    315 				 * when active, '{}' form struct or union
    316 				 * declarations, ':' marks a bit-field, and '='
    317 				 * starts an initializer */
    318 	bool in_init;		/* whether inside an initializer */
    319 	int init_level;		/* the number of '{}' in an initializer */
    320 	bool line_has_func_def;	/* starts either at the 'name(' from a function
    321 				 * definition if it occurs at the beginning of
    322 				 * a line, or at the first '*' from inside a
    323 				 * declaration when the line starts with words
    324 				 * followed by a '(' */
    325 	bool in_func_def_params;	/* for old-style functions */
    326 	bool line_has_decl;	/* whether this line of code has part of a
    327 				 * declaration on it; used for indenting
    328 				 * comments */
    329 	parser_symbol lbrace_kind;	/* the kind of brace to be pushed to
    330 					 * the parser symbol stack next */
    331 	parser_symbol spaced_expr_psym;	/* the parser symbol to be shifted
    332 					 * after the parenthesized expression
    333 					 * from a 'for', 'if', 'switch' or
    334 					 * 'while'; or psym_0 */
    335 	bool seen_case;		/* whether there was a 'case' or 'default', to
    336 				 * properly space the following ':' */
    337 	bool prev_paren_was_cast;
    338 	int quest_level;	/* when this is positive, we have seen a '?'
    339 				 * without the matching ':' in a '?:'
    340 				 * expression */
    341 
    342 	/* Indentation of statements and declarations */
    343 
    344 	int ind_level;		/* the indentation level for the line that is
    345 				 * currently prepared for output */
    346 	int ind_level_follow;	/* the level to which ind_level should be set
    347 				 * after the current line is printed */
    348 	bool line_is_stmt_cont;	/* whether the current line should have an
    349 				 * extra indentation level because we are in
    350 				 * the middle of a statement */
    351 	int decl_level;		/* current nesting level for a structure
    352 				 * declaration or an initializer */
    353 	int di_stack[20];	/* a stack of structure indentation levels */
    354 	bool decl_indent_done;	/* whether the indentation for a declaration
    355 				 * has been added to the code buffer. */
    356 	int decl_ind;		/* current indentation for declarations */
    357 	bool tabs_to_var;	/* true if using tabs to indent to var name */
    358 
    359 	enum {
    360 		eei_no,
    361 		eei_maybe,
    362 		eei_last
    363 	} extra_expr_indent;
    364 
    365 	struct psym_stack psyms;
    366 
    367 	/* Spacing inside a statement or declaration */
    368 
    369 	bool next_unary;	/* whether the following operator should be
    370 				 * unary; is used in declarations for '*', as
    371 				 * well as in expressions */
    372 	bool want_blank;	/* whether the following token should be
    373 				 * prefixed by a blank. (Said prefixing is
    374 				 * ignored in some cases.) */
    375 	int ind_paren_level;	/* the number of parentheses or brackets that
    376 				 * is used for indenting a continuation line of
    377 				 * a declaration, initializer or statement */
    378 	struct paren_stack {
    379 		struct paren_level *item;
    380 		size_t len;
    381 		size_t cap;
    382 	} paren;		/* the parentheses or brackets that are
    383 				 * currently open; used to indent the remaining
    384 				 * lines of the statement, initializer or
    385 				 * declaration */
    386 
    387 	/* Indentation of comments */
    388 
    389 	int comment_ind;	/* total indentation of the current comment */
    390 	int comment_shift;	/* all but the first line of a boxed comment
    391 				 * are shifted this much to the right */
    392 	bool comment_cont;	/* after the first line of a comment */
    393 
    394 	/* Vertical spacing */
    395 
    396 	bool break_after_comma;	/* whether to add a newline after the next
    397 				 * comma; used in declarations but not in
    398 				 * initializer lists */
    399 	enum {
    400 		nl_no,
    401 		nl_unless_if,
    402 		nl_unless_lbrace,
    403 		nl_unless_semicolon,
    404 		nl_yes,
    405 	} newline;		/* decides whether to insert a line break
    406 				 * before the next token */
    407 
    408 	enum {
    409 		decl_no,	/* no declaration anywhere nearby */
    410 		decl_begin,	/* collecting tokens of a declaration */
    411 		decl_end,	/* finished a declaration */
    412 	} declaration;
    413 	bool blank_line_after_decl;
    414 
    415 	enum {
    416 		badp_none,
    417 		badp_seen_lbrace,
    418 		badp_decl,	/* in an unfinished declaration in the first
    419 				 * block of declarations in a function body */
    420 		badp_seen_decl,	/* seen the semicolon of a declaration; the
    421 				 * next line is a candidate for inserting a
    422 				 * blank line above */
    423 		badp_yes,	/* this line is a candidate for inserting a
    424 				 * blank line above, unless the line turns out
    425 				 * to start a declaration */
    426 	} badp;			/* insert a blank line before the first
    427 				 * statement in a function body */
    428 } ps;
    429 
    430 extern struct output_state {
    431 	enum line_kind {
    432 		lk_other,
    433 		lk_blank,
    434 		lk_pre_if,	/* #if, #ifdef, #ifndef */
    435 		lk_pre_endif,	/* #endif */
    436 		lk_pre_other,	/* #else, #elif, #define, #undef */
    437 		lk_stmt_head,	/* the ')' of an incomplete statement such as
    438 				 * 'if (expr)' or 'for (expr; expr; expr)' */
    439 		lk_func_end,	/* the last '}' of a function body */
    440 		lk_block_comment,
    441 		lk_case_or_default,
    442 	} line_kind;		/* kind of the line that is being prepared for
    443 				 * output; is reset to lk_other each time after
    444 				 * trying to send a line to the output, even if
    445 				 * that line was a suppressed blank line; used
    446 				 * for inserting or removing blank lines */
    447 	enum line_kind prev_line_kind;	/* the kind of line that was actually
    448 					 * sent to the output */
    449 
    450 	struct buffer indent_off_text;	/* text from between 'INDENT OFF' and
    451 					 * 'INDENT ON', both inclusive */
    452 } out;
    453 
    454 
    455 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
    456 
    457 #ifdef debug
    458 void debug_printf(const char *, ...) __printflike(1, 2);
    459 void debug_println(const char *, ...) __printflike(1, 2);
    460 void debug_blank_line(void);
    461 void debug_vis_range(const char *, size_t);
    462 void debug_parser_state(void);
    463 void debug_psyms_stack(const char *);
    464 void debug_print_buf(const char *, const struct buffer *);
    465 void debug_buffers(void);
    466 void parser_state_back_up(struct parser_state *);
    467 void parser_state_free(struct parser_state *);
    468 extern const char *const lsym_name[];
    469 extern const char *const psym_name[];
    470 extern const char *const paren_level_cast_name[];
    471 extern const char *const line_kind_name[];
    472 #define static_unless_debug /* nothing */
    473 #else
    474 #define debug_noop() do { } while (false)
    475 #define	debug_printf(fmt, ...) debug_noop()
    476 #define	debug_println(fmt, ...) debug_noop()
    477 #define debug_blank_line() debug_noop()
    478 #define	debug_vis_range(s, len) debug_noop()
    479 #define	debug_parser_state() debug_noop()
    480 #define	debug_psyms_stack(situation) debug_noop()
    481 #define debug_print_buf(name, buf) debug_noop()
    482 #define	debug_buffers() debug_noop()
    483 #define static_unless_debug static
    484 #endif
    485 
    486 void register_typename(const char *);
    487 int compute_code_indent(void);
    488 int compute_label_indent(void);
    489 int ind_add(int, const char *, size_t);
    490 
    491 void inp_skip(void);
    492 char inp_next(void);
    493 void finish_output(void);
    494 
    495 lexer_symbol lexi(void);
    496 void diag(int, const char *, ...) __printflike(2, 3);
    497 void output_line(void);
    498 void inp_read_line(void);
    499 void parse(parser_symbol);
    500 void process_comment(void);
    501 void set_option(const char *, const char *);
    502 void load_profile_files(const char *);
    503 void ps_push(parser_symbol, bool);
    504 
    505 void *nonnull(void *);
    506 
    507 void buf_add_char(struct buffer *, char);
    508 void buf_add_chars(struct buffer *, const char *, size_t);
    509 
    510 static inline bool
    511 ch_isalnum(char ch)
    512 {
    513 	return isalnum((unsigned char)ch) != 0;
    514 }
    515 
    516 static inline bool
    517 ch_isalpha(char ch)
    518 {
    519 	return isalpha((unsigned char)ch) != 0;
    520 }
    521 
    522 static inline bool
    523 ch_isblank(char ch)
    524 {
    525 	return ch == ' ' || ch == '\t';
    526 }
    527 
    528 static inline bool
    529 ch_isdigit(char ch)
    530 {
    531 	return '0' <= ch && ch <= '9';
    532 }
    533 
    534 static inline bool
    535 ch_isspace(char ch)
    536 {
    537 	return isspace((unsigned char)ch) != 0;
    538 }
    539 
    540 static inline int
    541 next_tab(int ind)
    542 {
    543 	return ind - ind % opt.tabsize + opt.tabsize;
    544 }
    545 
    546 #ifdef debug
    547 void buf_terminate(struct buffer *);
    548 #else
    549 #define buf_terminate(buf) debug_noop()
    550 #endif
    551 
    552 static inline void
    553 buf_clear(struct buffer *buf)
    554 {
    555 	buf->len = 0;
    556 	buf_terminate(buf);
    557 }
    558