Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.62
      1 /*	$NetBSD: indent.h,v 1.62 2021/10/29 20:27:42 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 <stdbool.h>
     72 
     73 typedef enum lexer_symbol {
     74     lsym_eof,
     75     lsym_preprocessing,		/* '#' */
     76     lsym_newline,
     77     lsym_form_feed,
     78     lsym_comment,		/* the initial '/' '*' or '//' of a comment */
     79     lsym_lparen_or_lbracket,
     80     lsym_rparen_or_rbracket,
     81     lsym_lbrace,
     82     lsym_rbrace,
     83     lsym_period,
     84     lsym_unary_op,		/* e.g. '+' or '&' */
     85     lsym_binary_op,		/* e.g. '<<' or '+' or '&&' or '/=' */
     86     lsym_postfix_op,		/* trailing '++' or '--' */
     87     lsym_question,		/* the '?' from a '?:' expression */
     88     lsym_colon,
     89     lsym_comma,
     90     lsym_semicolon,
     91     lsym_typedef,
     92     lsym_storage_class,
     93     lsym_type,
     94     lsym_tag,			/* 'struct', 'union' or 'enum' */
     95     lsym_case_label,		/* 'case' or 'default' */
     96     lsym_string_prefix,		/* 'L' */
     97     lsym_ident,			/* identifier, constant or string */
     98     lsym_funcname,
     99     lsym_do,
    100     lsym_else,
    101     lsym_for,
    102     lsym_if,
    103     lsym_switch,
    104     lsym_while,
    105 } lexer_symbol;
    106 
    107 typedef enum parser_symbol {
    108     psym_semicolon,		/* rather a placeholder than a semicolon */
    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' */
    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 typedef enum stmt_head {
    126     hd_0,			/* placeholder for uninitialized */
    127     hd_for,
    128     hd_if,
    129     hd_switch,
    130     hd_while,
    131 } stmt_head;
    132 
    133 #define sc_size 5000		/* size of save_com buffer */
    134 #define label_offset 2		/* number of levels a label is placed to left
    135 				 * of code */
    136 
    137 
    138 /* A range of characters, in some cases null-terminated. */
    139 struct buffer {
    140     char *s;			/* start of the usable text */
    141     char *e;			/* end of the usable text */
    142     char *buf;			/* start of the allocated memory */
    143     char *l;			/* end of the allocated memory */
    144 };
    145 
    146 extern FILE *input;
    147 extern FILE *output;
    148 
    149 extern struct buffer inp;	/* one line of input, ready to be split into
    150 				 * tokens */
    151 
    152 extern struct buffer token;	/* the current token to be processed, is
    153 				 * typically copied to the buffer 'code',
    154 				 * or in some cases to 'lab'. */
    155 
    156 extern struct buffer lab;	/* the label or preprocessor directive */
    157 extern struct buffer code;	/* the main part of the current line of code */
    158 extern struct buffer com;	/* the trailing comment of the line, or the
    159 				 * start or end of a multi-line comment */
    160 
    161 extern char sc_buf[sc_size];	/* input text is saved here when looking for
    162 				 * the brace after an if, while, etc */
    163 extern char *save_com;		/* start of the comment stored in sc_buf */
    164 
    165 extern char *saved_inp_s;	/* saved value of inp.s when taking input from
    166 				 * save_com */
    167 extern char *saved_inp_e;	/* similarly saved value of inp.e */
    168 
    169 
    170 extern struct options {
    171     bool blanklines_around_conditional_compilation;
    172     bool blanklines_after_decl_at_top;	/* this is vaguely similar to
    173 					 * blanklines_after_decl except that
    174 					 * it only applies to the first set of
    175 					 * declarations in a procedure (just
    176 					 * after the first '{') and it causes
    177 					 * a blank line to be generated even
    178 					 * if there are no declarations */
    179     bool blanklines_after_decl;
    180     bool blanklines_after_procs;
    181     bool blanklines_before_block_comments;
    182     bool break_after_comma;	/* whether to break declarations after commas */
    183     bool brace_same_line;	/* whether brace should be on same line as if,
    184 				 * while, etc */
    185     bool blank_after_sizeof;	/* whether a blank should always be inserted
    186 				 * after sizeof */
    187     bool comment_delimiter_on_blankline;
    188     int decl_comment_column;	/* the column in which comments after
    189 				 * declarations should be put */
    190     bool cuddle_else;		/* whether 'else' should cuddle up to '}' */
    191     int continuation_indent;	/* the indentation between the edge of code
    192 				 * and continuation lines */
    193     float case_indent;		/* The distance (measured in indentation
    194 				 * levels) to indent case labels from the
    195 				 * switch statement */
    196     int comment_column;		/* the column in which comments to the right
    197 				 * of code should start */
    198     int decl_indent;		/* indentation of identifier in declaration */
    199     bool ljust_decl;		/* true if declarations should be left
    200 				 * justified */
    201     int unindent_displace;	/* comments not to the right of code will be
    202 				 * placed this many indentation levels to the
    203 				 * left of code */
    204     bool extra_expr_indent;	/* whether continuation lines from the
    205 				 * expression part of "if(e)", "while(e)",
    206 				 * "for(e;e;e)" should be indented an extra
    207 				 * tab stop so that they don't conflict with
    208 				 * the code that follows */
    209     bool else_if;		/* whether else-if pairs should be handled
    210 				 * specially */
    211     bool function_brace_split;	/* split function declaration and brace onto
    212 				 * separate lines */
    213     bool format_col1_comments;	/* If comments which start in column 1 are to
    214 				 * be magically reformatted (just like
    215 				 * comments that begin in later columns) */
    216     bool format_block_comments;	/* whether comments beginning with '/ * \n'
    217 				 * are to be reformatted */
    218     bool indent_parameters;
    219     int indent_size;		/* the size of one indentation level */
    220     int block_comment_max_line_length;
    221     int local_decl_indent;	/* like decl_indent but for locals */
    222     bool lineup_to_parens_always;	/* whether to not(?) attempt to keep
    223 					 * lined-up code within the margin */
    224     bool lineup_to_parens;	/* whether continued code within parens will
    225 				 * be lined up to the open paren */
    226     bool proc_calls_space;	/* whether function calls look like: foo (bar)
    227 				 * rather than foo(bar) */
    228     bool procnames_start_line;	/* whether the names of procedures being
    229 				 * defined get placed in column 1 (i.e. a
    230 				 * newline is placed between the type of the
    231 				 * procedure and its name) */
    232     bool space_after_cast;	/* "b = (int) a" vs "b = (int)a" */
    233     bool star_comment_cont;	/* whether comment continuation lines should
    234 				 * have stars at the beginning of each line. */
    235     bool swallow_optional_blanklines;
    236     bool auto_typedefs;		/* whether to recognize identifiers ending in
    237 				 * "_t" like typedefs */
    238     int tabsize;		/* the size of a tab */
    239     int max_line_length;
    240     bool use_tabs;		/* set true to use tabs for spacing, false
    241 				 * uses all spaces */
    242     bool verbose;		/* whether non-essential error messages are
    243 				 * printed */
    244 } opt;
    245 
    246 enum keyword_kind {
    247     kw_0,
    248     kw_offsetof,
    249     kw_sizeof,
    250     kw_struct_or_union_or_enum,
    251     kw_type,
    252     kw_for,
    253     kw_if,
    254     kw_while,
    255     kw_do,
    256     kw_else,
    257     kw_switch,
    258     kw_case_or_default,
    259     kw_jump,
    260     kw_storage_class,
    261     kw_typedef,
    262     kw_inline_or_restrict
    263 };
    264 
    265 
    266 extern bool found_err;
    267 extern int blank_lines_to_output;
    268 extern bool blank_line_before;
    269 extern bool blank_line_after;
    270 extern bool break_comma;	/* when true and not in parentheses, break
    271 				 * after a comma */
    272 extern float case_ind;		/* indentation level to be used for a "case
    273 				 * n:" */
    274 extern bool had_eof;		/* whether input is exhausted */
    275 extern int line_no;		/* the current line number. */
    276 extern bool inhibit_formatting;	/* true if INDENT OFF is in effect */
    277 
    278 #define	STACKSIZE 256
    279 
    280 extern struct parser_state {
    281     /*
    282      * TODO: Double-check that the word 'prev' in the following variables
    283      * means exactly the same thing.
    284      */
    285     lexer_symbol prev_token;
    286     bool prev_newline;		/* whether the last thing scanned was a
    287 				 * newline */
    288     bool prev_col_1;		/* whether the last token started in column 1 */
    289     enum keyword_kind prev_keyword;
    290     enum keyword_kind curr_keyword;
    291     bool next_unary;		/* whether the following operator should be
    292 				 * unary */
    293 
    294     char procname[100];		/* The name of the current procedure */
    295 
    296 
    297     bool want_blank;		/* whether the following token should be
    298 				 * prefixed by a blank. (Said prefixing is
    299 				 * ignored in some cases.) */
    300 
    301     int paren_level;		/* parenthesization level. used to indent
    302 				 * within statements */
    303     /* TODO: rename to next_line_paren_level */
    304     int p_l_follow;		/* how to indent the remaining lines of the
    305 				 * statement */
    306     short paren_indents[20];	/* indentation of the operand/argument of each
    307 				 * level of parentheses or brackets, relative
    308 				 * to the enclosing statement */
    309     int cast_mask;		/* indicates which close parentheses
    310 				 * potentially close off casts */
    311     int not_cast_mask;		/* indicates which close parentheses
    312 				 * definitely close off something else than
    313 				 * casts */
    314 
    315     int comment_delta;		/* used to set up indentation for all lines of
    316 				 * a boxed comment after the first one */
    317     int n_comment_delta;	/* remembers how many columns there were
    318 				 * before the start of a box comment so that
    319 				 * forthcoming lines of the comment are
    320 				 * indented properly */
    321     int com_ind;		/* indentation of the current comment */
    322 
    323     bool block_init;		/* whether inside a block initialization */
    324     int block_init_level;	/* The level of brace nesting in an
    325 				 * initialization */
    326     bool init_or_struct;	/* whether there has been a declarator (e.g.
    327 				 * int or char) and no left parenthesis since
    328 				 * the last semicolon. When true, a '{' is
    329 				 * starting a structure definition or an
    330 				 * initialization list */
    331 
    332     int ind_level;		/* the current indentation level */
    333     int ind_level_follow;	/* the level to which ind_level should be set
    334 				 * after the current line is printed */
    335 
    336     int decl_nest;		/* current nesting level for structure or init */
    337     bool decl_on_line;		/* whether this line of code has part of a
    338 				 * declaration on it */
    339     bool in_decl;		/* whether we are in a declaration stmt. The
    340 				 * processing of braces is then slightly
    341 				 * different */
    342     int just_saw_decl;
    343     bool in_parameter_declaration;
    344     bool decl_indent_done;	/* whether the indentation for a declaration
    345 				 * has been added to the code buffer. */
    346 
    347     bool in_stmt;
    348     bool ind_stmt;		/* whether the next line should have an extra
    349 				 * indentation level because we are in the
    350 				 * middle of a statement */
    351     bool is_case_label;		/* 'case' and 'default' labels are indented
    352 				 * differently from regular labels */
    353 
    354     bool search_stmt;		/* whether it is necessary to buffer up all
    355 				 * text up to the start of a statement after
    356 				 * an 'if', 'while', etc. */
    357 
    358     int tos;			/* pointer to top of stack */
    359     parser_symbol s_sym[STACKSIZE];
    360     int s_ind_level[STACKSIZE];
    361     float s_case_ind_level[STACKSIZE];
    362 
    363     struct {
    364 	int comments;
    365 	int lines;
    366 	int code_lines;
    367 	int comment_lines;
    368     }      stats;
    369 } ps;
    370 
    371 
    372 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
    373 
    374 void add_typename(const char *);
    375 int compute_code_indent(void);
    376 int compute_label_indent(void);
    377 int indentation_after_range(int, const char *, const char *);
    378 int indentation_after(int, const char *);
    379 #ifdef debug
    380 void
    381 debug_vis_range(const char *, const char *, const char *,
    382     const char *);
    383 void debug_printf(const char *, ...)__printflike(1, 2);
    384 void debug_println(const char *, ...)__printflike(1, 2);
    385 #else
    386 #define		debug_printf(fmt, ...) do { } while (false)
    387 #define		debug_println(fmt, ...) do { } while (false)
    388 #define		debug_vis_range(prefix, s, e, suffix) do { } while (false)
    389 #endif
    390 void inbuf_skip(void);
    391 char inbuf_next(void);
    392 lexer_symbol lexi(void);
    393 void diag(int, const char *, ...)__printflike(2, 3);
    394 void dump_line(void);
    395 void dump_line_ff(void);
    396 void inbuf_read_line(void);
    397 void parse(parser_symbol);
    398 void parse_stmt_head(stmt_head);
    399 void process_comment(void);
    400 void set_option(const char *, const char *);
    401 void load_profiles(const char *);
    402 
    403 void *xmalloc(size_t);
    404 void *xrealloc(void *, size_t);
    405 char *xstrdup(const char *);
    406 
    407 void buf_expand(struct buffer *, size_t);
    408 
    409 static inline bool
    410 ch_isblank(char ch)
    411 {
    412     return ch == ' ' || ch == '\t';
    413 }
    414 
    415 static inline int
    416 next_tab(int ind)
    417 {
    418     return ind - ind % opt.tabsize + opt.tabsize;
    419 }
    420