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