Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.46
      1 /*	$NetBSD: indent.h,v 1.46 2021/10/24 22:28:06 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 token_type {
     74     end_of_file,
     75     newline,
     76     lparen_or_lbracket,
     77     rparen_or_rbracket,
     78     unary_op,			/* e.g. '+' or '&' */
     79     binary_op,			/* e.g. '<<' or '+' or '&&' or '/=' */
     80     postfix_op,			/* trailing '++' or '--' */
     81     question,			/* the '?' from a '?:' expression */
     82     case_label,
     83     colon,
     84     semicolon,
     85     lbrace,
     86     rbrace,
     87     ident,			/* identifier, constant or string */
     88     comma,
     89     comment,
     90     switch_expr,		/* 'switch' '(' <expr> ')' */
     91     preprocessing,		/* '#' */
     92     form_feed,
     93     decl,
     94     keyword_for_if_while,	/* 'for', 'if' or 'while' */
     95     tt_lex_do,
     96     tt_lex_else,
     97     if_expr,			/* 'if' '(' <expr> ')' */
     98     while_expr,			/* 'while' '(' <expr> ')' */
     99     for_exprs,			/* 'for' '(' ... ')' */
    100     stmt,
    101     stmt_list,
    102     tt_ps_else,
    103     tt_ps_do,
    104     do_stmt,			/* 'do' <stmt> */
    105     if_expr_stmt,		/* 'if' '(' <expr> ')' <stmt> */
    106     if_expr_stmt_else,		/* 'if' '(' <expr> ')' <stmt> 'else' */
    107     period,
    108     string_prefix,		/* 'L' */
    109     storage_class,
    110     funcname,
    111     type_def,
    112     keyword_struct_union_enum
    113 } token_type;
    114 
    115 #define sc_size 5000		/* size of save_com buffer */
    116 #define label_offset 2		/* number of levels a label is placed to left
    117 				 * of code */
    118 
    119 
    120 struct buffer {
    121     char *buf;			/* buffer */
    122     char *s;			/* start */
    123     char *e;			/* end */
    124     char *l;			/* limit */
    125 };
    126 
    127 extern FILE *input;
    128 extern FILE *output;
    129 
    130 extern struct buffer lab;	/* label or preprocessor directive */
    131 extern struct buffer code;	/* code */
    132 extern struct buffer com;	/* comment */
    133 extern struct buffer token;	/* the last token scanned */
    134 
    135 extern struct buffer inp;
    136 
    137 extern char sc_buf[sc_size];	/* input text is saved here when looking for
    138 				 * the brace after an if, while, etc */
    139 extern char *save_com;		/* start of the comment stored in sc_buf */
    140 
    141 extern char *saved_inp_s;	/* saved value of inp.s when taking input from
    142 				 * save_com */
    143 extern char *saved_inp_e;	/* similarly saved value of inp.e */
    144 
    145 
    146 extern struct options {
    147     bool blanklines_around_conditional_compilation;
    148     bool blanklines_after_decl_at_top;	/* this is vaguely similar to
    149 					 * blanklines_after_decl except that
    150 					 * it only applies to the first set of
    151 					 * declarations in a procedure (just
    152 					 * after the first '{') and it causes
    153 					 * a blank line to be generated even
    154 					 * if there are no declarations */
    155     bool blanklines_after_decl;
    156     bool blanklines_after_procs;
    157     bool blanklines_before_block_comments;
    158     bool break_after_comma;	/* whether to break declarations after commas */
    159     bool brace_same_line;	/* whether brace should be on same line as if,
    160 				 * while, etc */
    161     bool blank_after_sizeof;	/* whether a blank should always be inserted
    162 				 * after sizeof */
    163     bool comment_delimiter_on_blankline;
    164     int decl_comment_column;	/* the column in which comments after
    165 				 * declarations should be put */
    166     bool cuddle_else;		/* whether 'else' should cuddle up to '}' */
    167     int continuation_indent;	/* the indentation between the edge of code
    168 				 * and continuation lines */
    169     float case_indent;		/* The distance (measured in indentation
    170 				 * levels) to indent case labels from the
    171 				 * switch statement */
    172     int comment_column;		/* the column in which comments to the right
    173 				 * of code should start */
    174     int decl_indent;		/* indentation of identifier in declaration */
    175     bool ljust_decl;		/* true if declarations should be left
    176 				 * justified */
    177     int unindent_displace;	/* comments not to the right of code will be
    178 				 * placed this many indentation levels to the
    179 				 * left of code */
    180     bool extra_expr_indent;	/* whether continuation lines from the
    181 				 * expression part of "if(e)", "while(e)",
    182 				 * "for(e;e;e)" should be indented an extra
    183 				 * tab stop so that they don't conflict with
    184 				 * the code that follows */
    185     bool else_if;		/* whether else-if pairs should be handled
    186 				 * specially */
    187     bool function_brace_split;	/* split function declaration and brace onto
    188 				 * separate lines */
    189     bool format_col1_comments;	/* If comments which start in column 1 are to
    190 				 * be magically reformatted (just like
    191 				 * comments that begin in later columns) */
    192     bool format_block_comments;	/* whether comments beginning with '/ * \n'
    193 				 * are to be reformatted */
    194     bool indent_parameters;
    195     int indent_size;		/* the size of one indentation level */
    196     int block_comment_max_line_length;
    197     int local_decl_indent;	/* like decl_indent but for locals */
    198     bool lineup_to_parens_always;	/* whether to not(?) attempt to keep
    199 					 * lined-up code within the margin */
    200     bool lineup_to_parens;	/* whether continued code within parens will
    201 				 * be lined up to the open paren */
    202     bool proc_calls_space;	/* whether function calls look like: foo (bar)
    203 				 * rather than foo(bar) */
    204     bool procnames_start_line;	/* whether the names of procedures being
    205 				 * defined get placed in column 1 (i.e. a
    206 				 * newline is placed between the type of the
    207 				 * procedure and its name) */
    208     bool space_after_cast;	/* "b = (int) a" vs "b = (int)a" */
    209     bool star_comment_cont;	/* whether comment continuation lines should
    210 				 * have stars at the beginning of each line. */
    211     bool swallow_optional_blanklines;
    212     bool auto_typedefs;		/* whether to recognize identifiers ending in
    213 				 * "_t" like typedefs */
    214     int tabsize;		/* the size of a tab */
    215     int max_line_length;
    216     bool use_tabs;		/* set true to use tabs for spacing, false
    217 				 * uses all spaces */
    218     bool verbose;		/* whether non-essential error messages are
    219 				 * printed */
    220 }       opt;
    221 
    222 enum keyword_kind {
    223     kw_0,
    224     kw_offsetof,
    225     kw_sizeof,
    226     kw_struct_or_union_or_enum,
    227     kw_type,
    228     kw_for_or_if_or_while,
    229     kw_do,
    230     kw_else,
    231     kw_switch,
    232     kw_case_or_default,
    233     kw_jump,
    234     kw_storage_class,
    235     kw_typedef,
    236     kw_inline_or_restrict
    237 };
    238 
    239 
    240 extern bool found_err;
    241 extern int blank_lines_to_output;
    242 extern bool blank_line_before;
    243 extern bool blank_line_after;
    244 extern bool break_comma;	/* when true and not in parens, break after a
    245 				 * comma */
    246 extern float case_ind;		/* indentation level to be used for a "case
    247 				 * n:" */
    248 extern bool had_eof;		/* whether input is exhausted */
    249 extern int line_no;		/* the current line number. */
    250 extern bool inhibit_formatting;	/* true if INDENT OFF is in effect */
    251 
    252 #define	STACKSIZE 256
    253 
    254 /* TODO: group the members by purpose, don't sort them alphabetically */
    255 extern struct parser_state {
    256     token_type last_token;
    257 
    258     int tos;			/* pointer to top of stack */
    259     token_type s_ttype[STACKSIZE];
    260     int s_ind_level[STACKSIZE];
    261     float s_case_ind_level[STACKSIZE];
    262 
    263     int comment_delta;		/* used to set up indentation for all lines of
    264 				 * a boxed comment after the first one */
    265     int n_comment_delta;	/* remembers how many columns there were
    266 				 * before the start of a box comment so that
    267 				 * forthcoming lines of the comment are
    268 				 * indented properly */
    269     int cast_mask;		/* indicates which close parens potentially
    270 				 * close off casts */
    271     int not_cast_mask;		/* indicates which close parens definitely
    272 				 * close off something else than casts */
    273     bool block_init;		/* whether inside a block initialization */
    274     int block_init_level;	/* The level of brace nesting in an
    275 				 * initialization */
    276     bool last_nl;		/* whether the last thing scanned was a
    277 				 * newline */
    278     bool init_or_struct;	/* whether there has been a declarator (e.g.
    279 				 * int or char) and no left parenthesis since
    280 				 * the last semicolon. When true, a '{' is
    281 				 * starting a structure definition or an
    282 				 * initialization list */
    283     bool col_1;			/* whether the last token started in column 1 */
    284     int com_ind;		/* indentation of the current comment */
    285     int decl_nest;		/* current nesting level for structure or init */
    286     bool decl_on_line;		/* whether this line of code has part of a
    287 				 * declaration on it */
    288     int ind_level_follow;	/* the level to which ind_level should be set
    289 				 * after the current line is printed */
    290     bool in_decl;		/* whether we are in a declaration stmt. The
    291 				 * processing of braces is then slightly
    292 				 * different */
    293     bool in_stmt;
    294     int ind_level;		/* the current indentation level */
    295     bool ind_stmt;		/* whether the next line should have an extra
    296 				 * indentation level because we are in the
    297 				 * middle of a stmt */
    298     bool next_unary;		/* whether the following operator should be
    299 				 * unary */
    300     int p_l_follow;		/* used to remember how to indent the
    301 				 * following statement */
    302     int paren_level;		/* parenthesization level. used to indent
    303 				 * within statements */
    304     short paren_indents[20];	/* indentation of the operand/argument of each
    305 				 * level of parentheses or brackets, relative
    306 				 * to the enclosing statement */
    307     bool is_case_label;		/* 'case' and 'default' labels are indented
    308 				 * differently from regular labels */
    309     bool search_brace;		/* whether it is necessary to buffer up all
    310 				 * info up to the start of a stmt after an if,
    311 				 * while, etc */
    312     bool want_blank;		/* whether the following token should be
    313 				 * prefixed by a blank. (Said prefixing is
    314 				 * ignored in some cases.) */
    315     enum keyword_kind keyword;
    316     bool dumped_decl_indent;
    317     bool in_parameter_declaration;
    318     char procname[100];		/* The name of the current procedure */
    319     int just_saw_decl;
    320 
    321     struct {
    322 	int comments;
    323 	int lines;
    324 	int code_lines;
    325 	int comment_lines;
    326     }      stats;
    327 }            ps;
    328 
    329 
    330 #define array_length(array) (sizeof (array) / sizeof (array[0]))
    331 
    332 void add_typename(const char *);
    333 int compute_code_indent(void);
    334 int compute_label_indent(void);
    335 int indentation_after_range(int, const char *, const char *);
    336 int indentation_after(int, const char *);
    337 #ifdef debug
    338 void
    339 debug_vis_range(const char *, const char *, const char *,
    340     const char *);
    341 void debug_printf(const char *, ...)__printflike(1, 2);
    342 void debug_println(const char *, ...)__printflike(1, 2);
    343 const char *token_type_name(token_type);
    344 #else
    345 #define		debug_printf(fmt, ...) do { } while (false)
    346 #define		debug_println(fmt, ...) do { } while (false)
    347 #define		debug_vis_range(prefix, s, e, suffix) do { } while (false)
    348 #endif
    349 void inbuf_skip(void);
    350 char inbuf_next(void);
    351 token_type lexi(struct parser_state *);
    352 void diag(int, const char *, ...)__printflike(2, 3);
    353 void dump_line(void);
    354 void dump_line_ff(void);
    355 void inbuf_read_line(void);
    356 void parse(token_type);
    357 void process_comment(void);
    358 void set_option(const char *, const char *);
    359 void load_profiles(const char *);
    360 
    361 void *xmalloc(size_t);
    362 void *xrealloc(void *, size_t);
    363 char *xstrdup(const char *);
    364 
    365 void buf_expand(struct buffer *, size_t);
    366 
    367 static inline bool
    368 is_hspace(char ch)
    369 {
    370     return ch == ' ' || ch == '\t';
    371 }
    372 
    373 static inline int
    374 next_tab(int ind)
    375 {
    376     return ind - ind % opt.tabsize + opt.tabsize;
    377 }
    378