Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.152
      1 /*	$NetBSD: indent.h,v 1.152 2023/05/20 02:47:35 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,	/* '#' */
     74 	lsym_newline,
     75 	lsym_comment,		/* the initial '/ *' or '//' of a comment */
     76 	lsym_lparen_or_lbracket,
     77 	lsym_rparen_or_rbracket,
     78 	lsym_lbrace,
     79 	lsym_rbrace,
     80 	lsym_period,
     81 	lsym_unary_op,		/* e.g. '*', '&', '-' or leading '++' */
     82 	lsym_binary_op,		/* e.g. '*', '&', '<<', '&&' or '/=' */
     83 	lsym_postfix_op,	/* trailing '++' or '--' */
     84 	lsym_question,		/* the '?' from a '?:' expression */
     85 	lsym_colon,
     86 	lsym_comma,
     87 	lsym_semicolon,
     88 	lsym_typedef,
     89 	lsym_storage_class,
     90 	lsym_type_outside_parentheses,
     91 	lsym_type_in_parentheses,
     92 	lsym_tag,		/* 'struct', 'union' or 'enum' */
     93 	lsym_case_label,	/* 'case' or 'default' */
     94 	lsym_sizeof,
     95 	lsym_offsetof,
     96 	lsym_word,		/* identifier, constant or string */
     97 	lsym_funcname,		/* name of a function being defined */
     98 	lsym_do,
     99 	lsym_else,
    100 	lsym_for,
    101 	lsym_if,
    102 	lsym_switch,
    103 	lsym_while,
    104 	lsym_return
    105 } lexer_symbol;
    106 
    107 typedef enum parser_symbol {
    108 	psym_0,			/* a placeholder */
    109 	psym_lbrace,
    110 	psym_rbrace,
    111 	psym_decl,
    112 	psym_stmt,
    113 	psym_stmt_list,
    114 	psym_for_exprs,		/* 'for' '(' ... ')' */
    115 	psym_if_expr,		/* 'if' '(' expr ')' */
    116 	psym_if_expr_stmt,	/* 'if' '(' expr ')' stmt */
    117 	psym_if_expr_stmt_else,	/* 'if' '(' expr ')' stmt 'else' */
    118 	psym_else,		/* 'else'; not stored on the stack */
    119 	psym_switch_expr,	/* 'switch' '(' expr ')' */
    120 	psym_do,		/* 'do' */
    121 	psym_do_stmt,		/* 'do' stmt */
    122 	psym_while_expr,	/* 'while' '(' expr ')' */
    123 } parser_symbol;
    124 
    125 /* A range of characters, not null-terminated. */
    126 struct buffer {
    127 	const char *st;		/* start of the usable text */
    128 	char *mem;
    129 	size_t len;		/* length of the usable text, from 'mem' */
    130 	size_t cap;
    131 };
    132 
    133 extern FILE *input;
    134 extern FILE *output;
    135 
    136 /*
    137  * The current line from the input file, used by the lexer to generate tokens.
    138  * To read from the line, start at inp.st and continue up to and including the
    139  * next '\n'. To read beyond the '\n', call inp_skip or inp_next, which will
    140  * make the next line available, invalidating any pointers into the previous
    141  * line.
    142  */
    143 extern struct buffer inp;
    144 
    145 extern struct buffer token;	/* the current token to be processed, is
    146 				 * typically copied to the buffer 'code', or in
    147 				 * some cases to 'lab'. */
    148 
    149 extern struct buffer lab;	/* the label or preprocessor directive */
    150 extern struct buffer code;	/* the main part of the current line of code,
    151 				 * containing declarations or statements */
    152 extern struct buffer com;	/* the trailing comment of the line, or the
    153 				 * start or end of a multi-line comment, or
    154 				 * while in process_comment, a single line of a
    155 				 * multi-line comment */
    156 
    157 extern struct options {
    158 	bool blanklines_around_conditional_compilation;
    159 	bool blank_line_after_decl_at_top;	/* this is vaguely similar to
    160 						 * blank_line_after_decl except
    161 						 * that it only applies to the
    162 						 * first set of declarations in
    163 						 * a procedure (just after the
    164 						 * first '{') and it causes a
    165 						 * blank line to be generated
    166 						 * even if there are no
    167 						 * declarations */
    168 	bool blank_line_after_decl;
    169 	bool blanklines_after_procs;
    170 	bool blanklines_before_block_comments;
    171 	bool break_after_comma;	/* whether to add a line break after each
    172 				 * declarator */
    173 	bool brace_same_line;	/* whether brace should be on same line as if,
    174 				 * while, etc */
    175 	bool blank_after_sizeof;	/* whether a blank should always be
    176 					 * inserted after sizeof */
    177 	bool comment_delimiter_on_blankline;
    178 	int decl_comment_column;	/* the column in which comments after
    179 					 * declarations should be put */
    180 	bool cuddle_else;	/* whether 'else' should cuddle up to '}' */
    181 	int continuation_indent;	/* the indentation between the edge of
    182 					 * code and continuation lines */
    183 	float case_indent;	/* The distance (measured in indentation
    184 				 * levels) to indent case labels from the
    185 				 * switch statement */
    186 	int comment_column;	/* the column in which comments to the right of
    187 				 * code should start */
    188 	int decl_indent;	/* indentation of identifier in declaration */
    189 	bool ljust_decl;	/* true if declarations should be left
    190 				 * justified */
    191 	int unindent_displace;	/* comments not to the right of code will be
    192 				 * placed this many indentation levels to the
    193 				 * left of code */
    194 	bool extra_expr_indent;	/* whether continuation lines from the
    195 				 * expression part of "if (e)", "while (e)",
    196 				 * "for (e; e; e)" should be indented an extra
    197 				 * tab stop so that they don't conflict with
    198 				 * the code that follows */
    199 	bool else_if;		/* whether else-if pairs use the same line */
    200 	bool function_brace_split;	/* split function declaration and brace
    201 					 * onto separate lines */
    202 	bool format_col1_comments;	/* If comments which start in column 1
    203 					 * are to be reformatted (just like
    204 					 * comments that begin in later
    205 					 * columns) */
    206 	bool format_block_comments;	/* whether comments beginning with '/ *
    207 					 * \n' are to be reformatted */
    208 	bool indent_parameters;
    209 	int indent_size;	/* the size of one indentation level */
    210 	int block_comment_max_line_length;
    211 	int local_decl_indent;	/* like decl_indent but for locals */
    212 	bool lineup_to_parens_always;	/* whether to not(?) attempt to keep
    213 					 * lined-up code within the margin */
    214 	bool lineup_to_parens;	/* whether continued code within parens will be
    215 				 * lined up to the open paren */
    216 	bool proc_calls_space;	/* whether function calls look like: foo (bar)
    217 				 * rather than foo(bar) */
    218 	bool procnames_start_line;	/* whether the names of procedures
    219 					 * being defined get placed in column 1
    220 					 * (i.e. a newline is placed between
    221 					 * the type of the procedure and its
    222 					 * name) */
    223 	bool space_after_cast;	/* "b = (int) a" vs "b = (int)a" */
    224 	bool star_comment_cont;	/* whether comment continuation lines should
    225 				 * have stars at the beginning of each line */
    226 	bool swallow_optional_blanklines;
    227 	bool auto_typedefs;	/* whether to recognize identifiers ending in
    228 				 * "_t" like typedefs */
    229 	int tabsize;		/* the size of a tab */
    230 	int max_line_length;
    231 	bool use_tabs;		/* set true to use tabs for spacing, false uses
    232 				 * all spaces */
    233 	bool verbose;		/* whether non-essential error messages are
    234 				 * printed */
    235 } opt;
    236 
    237 extern bool found_err;
    238 extern bool break_comma;	/* when true and not in parentheses, break
    239 				 * after a comma */
    240 extern float case_ind;		/* indentation level to be used for a "case n:"
    241 				 */
    242 extern bool had_eof;		/* whether input is exhausted */
    243 extern int line_no;		/* the current line number. */
    244 extern enum indent_enabled {
    245 	indent_on,
    246 	indent_off,
    247 	indent_last_off_line,
    248 } indent_enabled;
    249 
    250 #define	STACKSIZE 256
    251 
    252 /* Properties of each level of parentheses or brackets. */
    253 typedef struct paren_level_props {
    254 	int indent;		/* indentation of the operand/argument,
    255 				 * relative to the enclosing statement; if
    256 				 * negative, reflected at -1 */
    257 	enum paren_level_cast {
    258 		cast_unknown,
    259 		cast_maybe,
    260 		cast_no,
    261 	} cast;			/* whether the parentheses form a type cast */
    262 } paren_level_props;
    263 
    264 /*
    265  * The parser state determines the layout of the formatted text.
    266  *
    267  * In a function body, the number of block braces determines the indentation
    268  * of statements and declarations.
    269  *
    270  * In a statement, the number of parentheses or brackets determines the
    271  * indentation of follow-up lines.
    272  *
    273  * In an expression, the token type determine whether to put spaces around.
    274  *
    275  * In a source file, the types of line determine the vertical spacing, such as
    276  * around preprocessing directives or function bodies, or above block
    277  * comments.
    278  */
    279 extern struct parser_state {
    280 	lexer_symbol prev_token;	/* the previous token, but never
    281 					 * comment, newline or preprocessing
    282 					 * line */
    283 
    284 	/* Token classification */
    285 
    286 	int quest_level;	/* when this is positive, we have seen a '?'
    287 				 * without the matching ':' in a '?:'
    288 				 * expression */
    289 	bool is_function_definition;	/* starts either at the 'name(' from a
    290 					 * function definition if it occurs at
    291 					 * the beginning of a line, or at the
    292 					 * first '*' from inside a declaration
    293 					 * when the line starts with words
    294 					 * followed by a '('; ends at the end
    295 					 * of that line */
    296 	bool block_init;	/* whether inside a block initialization */
    297 	int block_init_level;	/* the level of brace nesting in an
    298 				 * initialization */
    299 	bool init_or_struct;	/* whether there has been a type name and no
    300 				 * left parenthesis since the last semicolon.
    301 				 * When true, a '{' starts a structure
    302 				 * definition or an initialization list */
    303 	bool decl_on_line;	/* whether this line of code has part of a
    304 				 * declaration on it */
    305 	bool in_stmt_or_decl;	/* whether in a statement or a struct
    306 				 * declaration or a plain declaration */
    307 	bool in_decl;		/* whether we are in a declaration. The
    308 				 * processing of braces is then slightly
    309 				 * different */
    310 	bool in_func_def_params;
    311 	bool seen_case;		/* set to true when we see a 'case', so we know
    312 				 * what to do with the following colon */
    313 	bool is_case_label;	/* 'case' and 'default' labels are indented
    314 				 * differently from regular labels */
    315 	parser_symbol spaced_expr_psym;	/* the parser symbol to be shifted
    316 					 * after the parenthesized expression
    317 					 * from a 'for', 'if', 'switch' or
    318 					 * 'while'; or psym_0 */
    319 
    320 	/* Indentation of statements and declarations */
    321 
    322 	int ind_level;		/* the indentation level for the line that is
    323 				 * currently prepared for output */
    324 	int ind_level_follow;	/* the level to which ind_level should be set
    325 				 * after the current line is printed */
    326 	bool in_stmt_cont;	/* whether the current line should have an
    327 				 * extra indentation level because we are in
    328 				 * the middle of a statement */
    329 	int decl_level;		/* current nesting level for a structure
    330 				 * declaration or an initializer */
    331 	int di_stack[20];	/* a stack of structure indentation levels */
    332 	bool decl_indent_done;	/* whether the indentation for a declaration
    333 				 * has been added to the code buffer. */
    334 	int decl_ind;		/* current indentation for declarations */
    335 	bool tabs_to_var;	/* true if using tabs to indent to var name */
    336 
    337 	enum {
    338 		eei_no,
    339 		eei_yes,
    340 		eei_last
    341 	} extra_expr_indent;
    342 
    343 	enum {
    344 		in_enum_no,	/* outside any 'enum { ... }' */
    345 		in_enum_enum,	/* after keyword 'enum' */
    346 		in_enum_type,	/* after 'enum' or 'enum tag' */
    347 		in_enum_brace	/* between '{' and '}' */
    348 	} in_enum;		/* enum { . } */
    349 
    350 	int tos;		/* pointer to top of stack */
    351 	parser_symbol s_sym[STACKSIZE];
    352 	int s_ind_level[STACKSIZE];
    353 	float s_case_ind_level[STACKSIZE];
    354 
    355 	/* Spacing inside a statement or declaration */
    356 
    357 	bool next_unary;	/* whether the following operator should be
    358 				 * unary; is used in declarations for '*', as
    359 				 * well as in expressions */
    360 	bool want_blank;	/* whether the following token should be
    361 				 * prefixed by a blank. (Said prefixing is
    362 				 * ignored in some cases.) */
    363 	int line_start_nparen;	/* the number of parentheses or brackets that
    364 				 * were open at the beginning of the current
    365 				 * line; used to indent within statements,
    366 				 * initializers and declarations */
    367 	int nparen;		/* the number of parentheses or brackets that
    368 				 * are currently open; used to indent the
    369 				 * remaining lines of the statement,
    370 				 * initializer or declaration */
    371 	paren_level_props paren[20];
    372 
    373 	/* Horizontal spacing for comments */
    374 
    375 	int comment_delta;	/* used to set up indentation for all lines of
    376 				 * a boxed comment after the first one */
    377 	int n_comment_delta;	/* remembers how many columns there were before
    378 				 * the start of a box comment so that
    379 				 * forthcoming lines of the comment are
    380 				 * indented properly */
    381 	int com_ind;		/* indentation of the current comment */
    382 
    383 	/* Vertical spacing */
    384 
    385 	bool force_nl;		/* whether the next token is forced to go to a
    386 				 * new line; used after 'if (expr)' and in
    387 				 * similar situations; tokens like '{' may
    388 				 * ignore this */
    389 
    390 	enum declaration {
    391 		decl_no,	/* no declaration anywhere nearby */
    392 		decl_begin,	/* collecting tokens of a declaration */
    393 		decl_end,	/* finished a declaration */
    394 	} declaration;
    395 	bool blank_line_after_decl;
    396 
    397 	/* Comments */
    398 
    399 	bool curr_col_1;	/* whether the current token started in column
    400 				 * 1 of the original input */
    401 	bool next_col_1;
    402 } ps;
    403 
    404 
    405 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
    406 
    407 #ifdef debug
    408 void debug_printf(const char *, ...) __printflike(1, 2);
    409 void debug_println(const char *, ...) __printflike(1, 2);
    410 void debug_vis_range(const char *, const char *, size_t, const char *);
    411 void debug_parser_state(lexer_symbol);
    412 void debug_parse_stack(const char *);
    413 void debug_buffers(void);
    414 extern const char *const lsym_name[];
    415 extern const char *const psym_name[];
    416 extern const char *const paren_level_cast_name[];
    417 #else
    418 #define debug_noop() do { } while (false)
    419 #define	debug_printf(fmt, ...) debug_noop()
    420 #define	debug_println(fmt, ...) debug_noop()
    421 #define	debug_vis_range(prefix, s, e, suffix) debug_noop()
    422 #define	debug_parser_state(lsym) debug_noop()
    423 #define	debug_parse_stack(situation) debug_noop()
    424 #define	debug_buffers() debug_noop()
    425 #endif
    426 
    427 void register_typename(const char *);
    428 int compute_code_indent(void);
    429 int compute_label_indent(void);
    430 int ind_add(int, const char *, size_t);
    431 
    432 void inp_skip(void);
    433 char inp_next(void);
    434 void clear_indent_off_text(void);
    435 
    436 lexer_symbol lexi(void);
    437 void diag(int, const char *, ...) __printflike(2, 3);
    438 void output_line(void);
    439 void output_line_ff(void);
    440 void inp_read_line(void);
    441 void parse(parser_symbol);
    442 void process_comment(void);
    443 void set_option(const char *, const char *);
    444 void load_profile_files(const char *);
    445 
    446 void *nonnull(void *);
    447 
    448 void buf_add_char(struct buffer *, char);
    449 void buf_add_chars(struct buffer *, const char *, size_t);
    450 
    451 static inline bool
    452 ch_isalnum(char ch)
    453 {
    454 	return isalnum((unsigned char)ch) != 0;
    455 }
    456 
    457 static inline bool
    458 ch_isalpha(char ch)
    459 {
    460 	return isalpha((unsigned char)ch) != 0;
    461 }
    462 
    463 static inline bool
    464 ch_isblank(char ch)
    465 {
    466 	return ch == ' ' || ch == '\t';
    467 }
    468 
    469 static inline bool
    470 ch_isdigit(char ch)
    471 {
    472 	return '0' <= ch && ch <= '9';
    473 }
    474 
    475 static inline bool
    476 ch_isspace(char ch)
    477 {
    478 	return isspace((unsigned char)ch) != 0;
    479 }
    480 
    481 static inline int
    482 next_tab(int ind)
    483 {
    484 	return ind - ind % opt.tabsize + opt.tabsize;
    485 }
    486