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