Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.206
      1 /*	$NetBSD: indent.h,v 1.206 2023/12/03 21:40:44 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 #define input in.f
    165 #define inp in.line
    166 #define inp_p in.p
    167 #define token_start_line_no in.token_start_line
    168 #define token_end_line_no in.token_end_line
    169 
    170 extern FILE *output;
    171 
    172 extern struct buffer token;	/* the current token to be processed, is
    173 				 * typically copied to the buffer 'code', or in
    174 				 * some cases to 'lab'. */
    175 
    176 extern struct buffer lab;	/* the label or preprocessor directive */
    177 extern struct buffer code;	/* the main part of the current line of code,
    178 				 * containing declarations or statements */
    179 extern struct buffer com;	/* the trailing comment of the line, or the
    180 				 * start or end of a multi-line comment, or
    181 				 * while in process_comment, a single line of a
    182 				 * multi-line comment */
    183 
    184 extern struct options {
    185 	bool blank_line_around_conditional_compilation;
    186 	bool blank_line_after_decl_at_top;	/* this is vaguely similar to
    187 						 * blank_line_after_decl except
    188 						 * that it only applies to the
    189 						 * first set of declarations in
    190 						 * a procedure (just after the
    191 						 * first '{') and it causes a
    192 						 * blank line to be generated
    193 						 * even if there are no
    194 						 * declarations */
    195 	bool blank_line_after_decl;
    196 	bool blank_line_after_proc;
    197 	bool blank_line_before_block_comment;
    198 	bool break_after_comma;	/* whether to add a line break after each
    199 				 * declarator */
    200 	bool brace_same_line;	/* whether a brace should be on same line as an
    201 				 * if, while, etc. */
    202 	bool blank_after_sizeof;
    203 	bool comment_delimiter_on_blank_line;
    204 	int decl_comment_column;	/* the column in which comments after
    205 					 * declarations should be put */
    206 	bool cuddle_else;	/* whether 'else' should cuddle up to '}' */
    207 	int continuation_indent;	/* the indentation between the edge of
    208 					 * code and continuation lines */
    209 	float case_indent;	/* the distance (measured in indentation
    210 				 * levels) to indent case labels from the
    211 				 * switch statement */
    212 	int comment_column;	/* the column in which comments to the right of
    213 				 * code should start */
    214 	int decl_indent;	/* indentation of identifier in declaration */
    215 	bool left_justify_decl;
    216 	int unindent_displace;	/* comments not to the right of code will be
    217 				 * placed this many indentation levels to the
    218 				 * left of code */
    219 	bool extra_expr_indent;	/* whether continuation lines from the
    220 				 * expression part of "if (e)", "while (e)",
    221 				 * "for (e; e; e)" should be indented an extra
    222 				 * tab stop so that they are not confused with
    223 				 * the code that follows */
    224 	bool else_if_in_same_line;
    225 	bool function_brace_split;	/* split function declaration and brace
    226 					 * onto separate lines */
    227 	bool format_col1_comments;	/* whether comments that start in
    228 					 * column 1 are to be reformatted (just
    229 					 * like comments that begin in later
    230 					 * columns) */
    231 	bool format_block_comments;	/* whether to reformat comments that
    232 					 * begin with '/ * \n' */
    233 	bool indent_parameters;
    234 	int indent_size;	/* the size of one indentation level */
    235 	int block_comment_max_line_length;
    236 	int local_decl_indent;	/* like decl_indent but for locals */
    237 	bool lineup_to_parens_always;	/* whether to not(?) attempt to keep
    238 					 * lined-up code within the margin */
    239 	bool lineup_to_parens;	/* whether continued code within parens will be
    240 				 * lined up to the open paren */
    241 	bool proc_calls_space;	/* whether function calls look like 'foo (bar)'
    242 				 * rather than 'foo(bar)' */
    243 	bool procnames_start_line;	/* whether the names of functions being
    244 					 * defined get placed in column 1 (i.e.
    245 					 * a newline is placed between the type
    246 					 * of the function and its name) */
    247 	bool space_after_cast;	/* "b = (int) a" vs. "b = (int)a" */
    248 	bool star_comment_cont;	/* whether comment continuation lines should
    249 				 * have stars at the beginning of each line */
    250 	bool swallow_optional_blank_lines;
    251 	bool auto_typedefs;	/* whether to recognize identifiers ending in
    252 				 * "_t" like typedefs */
    253 	int tabsize;		/* the size of a tab */
    254 	int max_line_length;
    255 	bool use_tabs;		/* set true to use tabs for spacing, false uses
    256 				 * all spaces */
    257 	bool verbose;		/* print configuration to stderr */
    258 } opt;
    259 
    260 extern bool found_err;
    261 extern bool had_eof;		/* whether input is exhausted */
    262 extern enum indent_enabled {
    263 	indent_on,
    264 	indent_off,
    265 	indent_last_off_line,
    266 } indent_enabled;
    267 
    268 /* Properties of each level of parentheses or brackets. */
    269 struct paren_level {
    270 	int indent;		/* indentation of the operand/argument,
    271 				 * relative to the enclosing statement; if
    272 				 * negative, reflected at -1 */
    273 	enum paren_level_cast {
    274 		cast_unknown,
    275 		cast_maybe,
    276 		cast_no,
    277 	} cast;			/* whether the parentheses form a type cast */
    278 };
    279 
    280 struct psym_stack {
    281 	parser_symbol *sym;
    282 	int *ind_level;
    283 	size_t len;		/* points to one behind the top of the stack; 1
    284 				 * at the top level of the file outside a
    285 				 * declaration or statement; 2 at the top level
    286 				 */
    287 	size_t cap;
    288 };
    289 
    290 /*
    291  * The parser state determines the layout of the formatted text.
    292  *
    293  * At each '#if', the parser state is copied so that the corresponding '#else'
    294  * lines start in the same state.
    295  *
    296  * In a function body, the number of block braces determines the indentation
    297  * of statements and declarations.
    298  *
    299  * In a statement, the number of parentheses or brackets determines the
    300  * indentation of follow-up lines.
    301  *
    302  * In an expression, the token type determine whether to put spaces around.
    303  *
    304  * In a source file, the types of line determine the vertical spacing, such as
    305  * around preprocessing directives or function bodies, or above block
    306  * comments.
    307  */
    308 extern struct parser_state {
    309 	lexer_symbol prev_lsym;	/* the previous token, but never comment,
    310 				 * newline or preprocessing line */
    311 
    312 	/* Token classification */
    313 
    314 	bool in_stmt_or_decl;	/* whether in a statement or a struct
    315 				 * declaration or a plain declaration */
    316 	bool in_decl;		/* XXX: double-check the exact meaning */
    317 	bool in_typedef_decl;
    318 	bool in_var_decl;	/* starts at a type name or a '){' from a
    319 				 * compound literal; ends at the '(' from a
    320 				 * function definition or a ';' outside '{}';
    321 				 * when active, '{}' form struct or union
    322 				 * declarations, ':' marks a bit-field, and '='
    323 				 * starts an initializer */
    324 	bool in_init;		/* whether inside an initializer */
    325 	int init_level;		/* the number of '{}' in an initializer */
    326 	bool line_has_func_def;	/* starts either at the 'name(' from a function
    327 				 * definition if it occurs at the beginning of
    328 				 * a line, or at the first '*' from inside a
    329 				 * declaration when the line starts with words
    330 				 * followed by a '(' */
    331 	bool in_func_def_params;	/* for old-style functions */
    332 	bool line_has_decl;	/* whether this line of code has part of a
    333 				 * declaration on it; used for indenting
    334 				 * comments */
    335 	parser_symbol lbrace_kind;	/* the kind of brace to be pushed to
    336 					 * the parser symbol stack next */
    337 	parser_symbol spaced_expr_psym;	/* the parser symbol to be shifted
    338 					 * after the parenthesized expression
    339 					 * from a 'for', 'if', 'switch' or
    340 					 * 'while'; or psym_0 */
    341 	bool seen_case;		/* whether there was a 'case' or 'default', to
    342 				 * properly space the following ':' */
    343 	bool prev_paren_was_cast;
    344 	int quest_level;	/* when this is positive, we have seen a '?'
    345 				 * without the matching ':' in a '?:'
    346 				 * expression */
    347 
    348 	/* Indentation of statements and declarations */
    349 
    350 	int ind_level;		/* the indentation level for the line that is
    351 				 * currently prepared for output */
    352 	int ind_level_follow;	/* the level to which ind_level should be set
    353 				 * after the current line is printed */
    354 	bool line_is_stmt_cont;	/* whether the current line should have an
    355 				 * extra indentation level because we are in
    356 				 * the middle of a statement */
    357 	int decl_level;		/* current nesting level for a structure
    358 				 * declaration or an initializer */
    359 	int di_stack[20];	/* a stack of structure indentation levels */
    360 	bool decl_indent_done;	/* whether the indentation for a declaration
    361 				 * has been added to the code buffer. */
    362 	int decl_ind;		/* current indentation for declarations */
    363 	bool tabs_to_var;	/* true if using tabs to indent to var name */
    364 
    365 	enum {
    366 		eei_no,
    367 		eei_maybe,
    368 		eei_last
    369 	} extra_expr_indent;
    370 
    371 	struct psym_stack psyms;
    372 
    373 	/* Spacing inside a statement or declaration */
    374 
    375 	bool next_unary;	/* whether the following operator should be
    376 				 * unary; is used in declarations for '*', as
    377 				 * well as in expressions */
    378 	bool want_blank;	/* whether the following token should be
    379 				 * prefixed by a blank. (Said prefixing is
    380 				 * ignored in some cases.) */
    381 	int ind_paren_level;	/* the number of parentheses or brackets that
    382 				 * is used for indenting a continuation line of
    383 				 * a declaration, initializer or statement */
    384 	struct paren_stack {
    385 		struct paren_level *item;
    386 		size_t len;
    387 		size_t cap;
    388 	} paren;		/* the parentheses or brackets that are
    389 				 * currently open; used to indent the remaining
    390 				 * lines of the statement, initializer or
    391 				 * declaration */
    392 
    393 	/* Indentation of comments */
    394 
    395 	int comment_ind;	/* total indentation of the current comment */
    396 	int comment_shift;	/* all but the first line of a boxed comment
    397 				 * are shifted this much to the right */
    398 	bool comment_cont;	/* after the first line of a comment */
    399 
    400 	/* Vertical spacing */
    401 
    402 	bool break_after_comma;	/* whether to add a newline after the next
    403 				 * comma; used in declarations but not in
    404 				 * initializer lists */
    405 	bool want_newline;	/* whether the next token should go to a new
    406 				 * line; used after 'if (expr)' and in similar
    407 				 * situations; tokens like '{' or ';' may
    408 				 * ignore this */
    409 
    410 	enum declaration {
    411 		decl_no,	/* no declaration anywhere nearby */
    412 		decl_begin,	/* collecting tokens of a declaration */
    413 		decl_end,	/* finished a declaration */
    414 	} declaration;
    415 	bool blank_line_after_decl;
    416 
    417 	enum {
    418 		badp_none,
    419 		badp_seen_lbrace,
    420 		badp_decl,	/* in an unfinished declaration in the first
    421 				 * block of declarations in a function body */
    422 		badp_seen_decl,	/* seen the semicolon of a declaration; the
    423 				 * next line is a candidate for inserting a
    424 				 * blank line above */
    425 		badp_yes,	/* this line is a candidate for inserting a
    426 				 * blank line above, unless the line turns out
    427 				 * to start a declaration */
    428 	} badp;			/* insert a blank line before the first
    429 				 * statement in a function body */
    430 } ps;
    431 
    432 extern struct output_state {
    433 	enum line_kind {
    434 		lk_other,
    435 		lk_blank,
    436 		lk_pre_if,	/* #if, #ifdef, #ifndef */
    437 		lk_pre_endif,	/* #endif */
    438 		lk_pre_other,	/* #else, #elif, #define, #undef */
    439 		lk_stmt_head,	/* the ')' of an incomplete statement such as
    440 				 * 'if (expr)' or 'for (expr; expr; expr)' */
    441 		lk_func_end,	/* the last '}' of a function body */
    442 		lk_block_comment,
    443 		lk_case_or_default,
    444 	} line_kind;		/* kind of the line that is being prepared for
    445 				 * output; is reset to lk_other each time after
    446 				 * trying to send a line to the output, even if
    447 				 * that line was a suppressed blank line; used
    448 				 * for inserting or removing blank lines */
    449 	enum line_kind prev_line_kind;	/* the kind of line that was actually
    450 					 * sent to the output */
    451 
    452 	struct buffer indent_off_text;	/* text from between 'INDENT OFF' and
    453 					 * 'INDENT ON', both inclusive */
    454 } out;
    455 
    456 
    457 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
    458 
    459 #ifdef debug
    460 void debug_printf(const char *, ...) __printflike(1, 2);
    461 void debug_println(const char *, ...) __printflike(1, 2);
    462 void debug_blank_line(void);
    463 void debug_vis_range(const char *, size_t);
    464 void debug_parser_state(void);
    465 void debug_psyms_stack(const char *);
    466 void debug_print_buf(const char *, const struct buffer *);
    467 void debug_buffers(void);
    468 void parser_state_back_up(struct parser_state *);
    469 void parser_state_free(struct parser_state *);
    470 extern const char *const lsym_name[];
    471 extern const char *const psym_name[];
    472 extern const char *const paren_level_cast_name[];
    473 extern const char *const line_kind_name[];
    474 #define static_unless_debug /* nothing */
    475 #else
    476 #define debug_noop() do { } while (false)
    477 #define	debug_printf(fmt, ...) debug_noop()
    478 #define	debug_println(fmt, ...) debug_noop()
    479 #define debug_blank_line() debug_noop()
    480 #define	debug_vis_range(s, len) debug_noop()
    481 #define	debug_parser_state() debug_noop()
    482 #define	debug_psyms_stack(situation) debug_noop()
    483 #define debug_print_buf(name, buf) debug_noop()
    484 #define	debug_buffers() debug_noop()
    485 #define static_unless_debug static
    486 #endif
    487 
    488 void register_typename(const char *);
    489 int compute_code_indent(void);
    490 int compute_label_indent(void);
    491 int ind_add(int, const char *, size_t);
    492 
    493 void inp_skip(void);
    494 char inp_next(void);
    495 void finish_output(void);
    496 
    497 lexer_symbol lexi(void);
    498 void diag(int, const char *, ...) __printflike(2, 3);
    499 void output_line(void);
    500 void inp_read_line(void);
    501 void parse(parser_symbol);
    502 void process_comment(void);
    503 void set_option(const char *, const char *);
    504 void load_profile_files(const char *);
    505 void ps_push(parser_symbol, bool);
    506 
    507 void *nonnull(void *);
    508 
    509 void buf_add_char(struct buffer *, char);
    510 void buf_add_chars(struct buffer *, const char *, size_t);
    511 
    512 static inline bool
    513 ch_isalnum(char ch)
    514 {
    515 	return isalnum((unsigned char)ch) != 0;
    516 }
    517 
    518 static inline bool
    519 ch_isalpha(char ch)
    520 {
    521 	return isalpha((unsigned char)ch) != 0;
    522 }
    523 
    524 static inline bool
    525 ch_isblank(char ch)
    526 {
    527 	return ch == ' ' || ch == '\t';
    528 }
    529 
    530 static inline bool
    531 ch_isdigit(char ch)
    532 {
    533 	return '0' <= ch && ch <= '9';
    534 }
    535 
    536 static inline bool
    537 ch_isspace(char ch)
    538 {
    539 	return isspace((unsigned char)ch) != 0;
    540 }
    541 
    542 static inline int
    543 next_tab(int ind)
    544 {
    545 	return ind - ind % opt.tabsize + opt.tabsize;
    546 }
    547 
    548 #ifdef debug
    549 void buf_terminate(struct buffer *);
    550 #else
    551 #define buf_terminate(buf) debug_noop()
    552 #endif
    553 
    554 static inline void
    555 buf_clear(struct buffer *buf)
    556 {
    557 	buf->len = 0;
    558 	buf_terminate(buf);
    559 }
    560