Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.92
      1 /*	$NetBSD: indent.h,v 1.92 2021/11/19 17:42:45 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_outside_parentheses,
     95     lsym_type_in_parentheses,
     96     lsym_tag,			/* 'struct', 'union' or 'enum' */
     97     lsym_case_label,		/* 'case' or 'default' */
     98     lsym_string_prefix,		/* 'L' */
     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_semicolon,		/* rather a placeholder than a semicolon */
    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' */
    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 typedef enum stmt_head {
    131     hd_0,			/* placeholder for uninitialized */
    132     hd_for,
    133     hd_if,
    134     hd_switch,
    135     hd_while,
    136 } stmt_head;
    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 struct input_buffer {
    147     struct buffer inp;		/* one line of input, ready to be split into
    148 				 * tokens; occasionally this buffer switches
    149 				 * to save_com_buf */
    150     char save_com_buf[5000];	/* input text is saved here when looking for
    151 				 * the brace after an if, while, etc */
    152     char *save_com_s;		/* start of the comment in save_com_buf */
    153     char *save_com_e;		/* end of the comment in save_com_buf */
    154 
    155     char *saved_inp_s;		/* saved value of inp.s when taking input from
    156 				 * save_com */
    157     char *saved_inp_e;		/* similarly saved value of inp.e */
    158 } inbuf;
    159 
    160 extern FILE *input;
    161 extern FILE *output;
    162 
    163 extern struct buffer token;	/* the current token to be processed, is
    164 				 * typically copied to the buffer 'code',
    165 				 * or in some cases to 'lab'. */
    166 
    167 extern struct buffer lab;	/* the label or preprocessor directive */
    168 extern struct buffer code;	/* the main part of the current line of code */
    169 extern struct buffer com;	/* the trailing comment of the line, or the
    170 				 * start or end of a multi-line comment, or
    171 				 * while in process_comment, a single line of
    172 				 * a multi-line comment */
    173 
    174 extern struct options {
    175     bool blanklines_around_conditional_compilation;
    176     bool blanklines_after_decl_at_top;	/* this is vaguely similar to
    177 					 * blanklines_after_decl except that
    178 					 * it only applies to the first set of
    179 					 * declarations in a procedure (just
    180 					 * after the first '{') and it causes
    181 					 * a blank line to be generated even
    182 					 * if there are no declarations */
    183     bool blanklines_after_decl;
    184     bool blanklines_after_procs;
    185     bool blanklines_before_block_comments;
    186     bool break_after_comma;	/* whether to break declarations after commas */
    187     bool brace_same_line;	/* whether brace should be on same line as if,
    188 				 * while, etc */
    189     bool blank_after_sizeof;	/* whether a blank should always be inserted
    190 				 * after sizeof */
    191     bool comment_delimiter_on_blankline;
    192     int decl_comment_column;	/* the column in which comments after
    193 				 * declarations should be put */
    194     bool cuddle_else;		/* whether 'else' should cuddle up to '}' */
    195     int continuation_indent;	/* the indentation between the edge of code
    196 				 * and continuation lines */
    197     float case_indent;		/* The distance (measured in indentation
    198 				 * levels) to indent case labels from the
    199 				 * switch statement */
    200     int comment_column;		/* the column in which comments to the right
    201 				 * of code should start */
    202     int decl_indent;		/* indentation of identifier in declaration */
    203     bool ljust_decl;		/* true if declarations should be left
    204 				 * justified */
    205     int unindent_displace;	/* comments not to the right of code will be
    206 				 * placed this many indentation levels to the
    207 				 * left of code */
    208     bool extra_expr_indent;	/* whether continuation lines from the
    209 				 * expression part of "if(e)", "while(e)",
    210 				 * "for(e;e;e)" should be indented an extra
    211 				 * tab stop so that they don't conflict with
    212 				 * the code that follows */
    213     bool else_if;		/* whether else-if pairs should be handled
    214 				 * specially */
    215     bool function_brace_split;	/* split function declaration and brace onto
    216 				 * separate lines */
    217     bool format_col1_comments;	/* If comments which start in column 1 are to
    218 				 * be magically reformatted (just like
    219 				 * comments that begin in later columns) */
    220     bool format_block_comments;	/* whether comments beginning with '/ * \n'
    221 				 * are to be reformatted */
    222     bool indent_parameters;
    223     int indent_size;		/* the size of one indentation level */
    224     int block_comment_max_line_length;
    225     int local_decl_indent;	/* like decl_indent but for locals */
    226     bool lineup_to_parens_always;	/* whether to not(?) attempt to keep
    227 					 * lined-up code within the margin */
    228     bool lineup_to_parens;	/* whether continued code within parens will
    229 				 * be lined up to the open paren */
    230     bool proc_calls_space;	/* whether function calls look like: foo (bar)
    231 				 * rather than foo(bar) */
    232     bool procnames_start_line;	/* whether the names of procedures being
    233 				 * defined get placed in column 1 (i.e. a
    234 				 * newline is placed between the type of the
    235 				 * procedure and its name) */
    236     bool space_after_cast;	/* "b = (int) a" vs "b = (int)a" */
    237     bool star_comment_cont;	/* whether comment continuation lines should
    238 				 * have stars at the beginning of each line. */
    239     bool swallow_optional_blanklines;
    240     bool auto_typedefs;		/* whether to recognize identifiers ending in
    241 				 * "_t" like typedefs */
    242     int tabsize;		/* the size of a tab */
    243     int max_line_length;
    244     bool use_tabs;		/* set true to use tabs for spacing, false
    245 				 * uses all spaces */
    246     bool verbose;		/* whether non-essential error messages are
    247 				 * printed */
    248 } opt;
    249 
    250 extern bool found_err;
    251 extern int blank_lines_to_output;
    252 extern bool blank_line_before;
    253 extern bool blank_line_after;
    254 extern bool break_comma;	/* when true and not in parentheses, break
    255 				 * after a comma */
    256 extern float case_ind;		/* indentation level to be used for a "case
    257 				 * n:" */
    258 extern bool had_eof;		/* whether input is exhausted */
    259 extern int line_no;		/* the current line number. */
    260 extern bool inhibit_formatting;	/* true if INDENT OFF is in effect */
    261 
    262 #define	STACKSIZE 256
    263 
    264 extern struct parser_state {
    265     lexer_symbol prev_token;	/* the previous token, but never comment,
    266 				 * newline or preprocessing line */
    267     bool curr_col_1;		/* whether the current token started in column
    268 				 * 1 of the unformatted input */
    269     bool next_col_1;
    270     bool next_unary;		/* whether the following operator should be
    271 				 * unary */
    272 
    273     char procname[100];		/* The name of the current procedure; TODO:
    274 				 * document the difference between procname[0]
    275 				 * being '\0', ' ' and a real character */
    276 
    277 
    278     bool want_blank;		/* whether the following token should be
    279 				 * prefixed by a blank. (Said prefixing is
    280 				 * ignored in some cases.) */
    281 
    282     int paren_level;		/* parenthesization level. used to indent
    283 				 * within statements, initializers and
    284 				 * declarations */
    285     /* TODO: rename to next_line_paren_level */
    286     int p_l_follow;		/* how to indent the remaining lines of the
    287 				 * statement or initializer or declaration */
    288     short paren_indents[20];	/* indentation of the operand/argument of each
    289 				 * level of parentheses or brackets, relative
    290 				 * to the enclosing statement; if negative,
    291 				 * reflected at -1 */
    292     int cast_mask;		/* indicates which close parentheses
    293 				 * potentially close off casts */
    294     int not_cast_mask;		/* indicates which close parentheses
    295 				 * definitely close off something else than
    296 				 * casts */
    297 
    298     int comment_delta;		/* used to set up indentation for all lines of
    299 				 * a boxed comment after the first one */
    300     int n_comment_delta;	/* remembers how many columns there were
    301 				 * before the start of a box comment so that
    302 				 * forthcoming lines of the comment are
    303 				 * indented properly */
    304     int com_ind;		/* indentation of the current comment */
    305 
    306     bool block_init;		/* whether inside a block initialization */
    307     int block_init_level;	/* The level of brace nesting in an
    308 				 * initialization */
    309     bool init_or_struct;	/* whether there has been a declarator (e.g.
    310 				 * int or char) and no left parenthesis since
    311 				 * the last semicolon. When true, a '{' is
    312 				 * starting a structure definition or an
    313 				 * initialization list */
    314 
    315     int ind_level;		/* the indentation level for the line that is
    316 				 * currently prepared for output */
    317     int ind_level_follow;	/* the level to which ind_level should be set
    318 				 * after the current line is printed */
    319 
    320     int decl_level;		/* current nesting level for a structure
    321 				 * declaration or an initializer */
    322     bool decl_on_line;		/* whether this line of code has part of a
    323 				 * declaration on it */
    324     bool in_decl;		/* whether we are in a declaration stmt. The
    325 				 * processing of braces is then slightly
    326 				 * different */
    327     int just_saw_decl;
    328     bool in_parameter_declaration;
    329     bool decl_indent_done;	/* whether the indentation for a declaration
    330 				 * has been added to the code buffer. */
    331 
    332     bool in_stmt;		/* TODO: rename to something appropriate; this
    333 				 * is set to true in struct declarations as
    334 				 * well, so 'stmt' isn't accurate */
    335     bool ind_stmt;		/* whether the next line should have an extra
    336 				 * indentation level because we are in the
    337 				 * middle of a statement */
    338     bool is_case_label;		/* 'case' and 'default' labels are indented
    339 				 * differently from regular labels */
    340 
    341     bool search_stmt;		/* whether it is necessary to buffer up all
    342 				 * text up to the start of a statement after
    343 				 * an 'if (expr)', 'while (expr)', etc., to
    344 				 * move the comments after the opening brace
    345 				 * of the following statement */
    346 
    347     int tos;			/* pointer to top of stack */
    348     parser_symbol s_sym[STACKSIZE];
    349     int s_ind_level[STACKSIZE];
    350     float s_case_ind_level[STACKSIZE];
    351 
    352     struct {
    353 	int comments;
    354 	int lines;
    355 	int code_lines;
    356 	int comment_lines;
    357     }      stats;
    358 } ps;
    359 
    360 
    361 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
    362 
    363 #ifdef debug
    364 void
    365 debug_vis_range(const char *, const char *, const char *,
    366     const char *);
    367 void debug_printf(const char *, ...)__printflike(1, 2);
    368 void debug_println(const char *, ...)__printflike(1, 2);
    369 #else
    370 #define		debug_printf(fmt, ...) do { } while (false)
    371 #define		debug_println(fmt, ...) do { } while (false)
    372 #define		debug_vis_range(prefix, s, e, suffix) do { } while (false)
    373 #endif
    374 
    375 void register_typename(const char *);
    376 int compute_code_indent(void);
    377 int compute_label_indent(void);
    378 int ind_add(int, const char *, const char *);
    379 
    380 const char *inp_p(void);
    381 const char *inp_line_end(void);
    382 char inp_peek(void);
    383 char inp_lookahead(size_t);
    384 void inp_skip(void);
    385 char inp_next(void);
    386 
    387 void inp_comment_add_char(char);
    388 void inp_comment_add_range(const char *, const char *);
    389 
    390 void inp_from_comment(void);
    391 
    392 #ifdef debug
    393 void debug_inp(const char *);
    394 #else
    395 #define debug_inp(prefix) do { } while (false)
    396 #endif
    397 
    398 lexer_symbol lexi(void);
    399 void diag(int, const char *, ...)__printflike(2, 3);
    400 void dump_line(void);
    401 void dump_line_ff(void);
    402 void inp_read_line(void);
    403 void parse(parser_symbol);
    404 void parse_stmt_head(stmt_head);
    405 void process_comment(void);
    406 void set_option(const char *, const char *);
    407 void load_profiles(const char *);
    408 
    409 void *xmalloc(size_t);
    410 void *xrealloc(void *, size_t);
    411 char *xstrdup(const char *);
    412 
    413 void buf_expand(struct buffer *, size_t);
    414 
    415 static inline bool
    416 ch_isblank(char ch)
    417 {
    418     return ch == ' ' || ch == '\t';
    419 }
    420 
    421 static inline int
    422 next_tab(int ind)
    423 {
    424     return ind - ind % opt.tabsize + opt.tabsize;
    425 }
    426