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