Home | History | Annotate | Line # | Download | only in indent
indent.h revision 1.31
      1 /*	$NetBSD: indent.h,v 1.31 2021/10/08 16:16:54 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 '[' */
     77     rparen,			/* ')' or ']' */
     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;		/* the fid for the input file */
    127 extern FILE       *output;		/* the output file */
    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
    141 				 * from 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_declarations_at_proctop; /* this is vaguely
    148 				 * similar to blanklines_after_declarations
    149 				 * except that it only applies to the first
    150 				 * set of declarations in a procedure (just
    151 				 * after the first '{') and it causes a blank
    152 				 * line to be generated even if there are no
    153 				 * declarations */
    154     bool	blanklines_after_declarations;
    155     bool	blanklines_after_procs;
    156     bool	blanklines_before_blockcomments;
    157     bool	break_after_comma; /* whether to break declarations after
    158 				 * commas */
    159     bool	brace_same_line;/* whether brace should be on same line
    160 				 * as if, while, etc */
    161     bool	blank_after_sizeof; /* whether a blank should always be
    162 				 * inserted 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
    168 				 * edge of code 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
    178 				 * will be placed this many
    179 				 * indentation levels to the left of
    180 				 * code */
    181     bool	extra_expression_indent; /* whether continuation lines from
    182 				 * the expression part of "if(e)",
    183 				 * "while(e)", "for(e;e;e)" should be
    184 				 * indented an extra tab stop so that they
    185 				 * don't conflict with the code that follows */
    186     bool	else_if;	/* whether else-if pairs should be handled
    187 				 * specially */
    188     bool	function_brace_split; /* split function declaration and
    189 				 * brace onto separate lines */
    190     bool	format_col1_comments; /* If comments which start in column 1
    191 				 * are to be magically reformatted (just
    192 				 * like comments that begin in later columns) */
    193     bool	format_block_comments; /* whether comments beginning with
    194 				 * '/ * \n' are to be reformatted */
    195     bool	indent_parameters;
    196     int         indent_size;	/* the size of one indentation level */
    197     int         block_comment_max_line_length;
    198     int         local_decl_indent; /* like decl_indent but for locals */
    199     bool	lineup_to_parens_always; /* whether to not(?) attempt to keep
    200 				 * lined-up code within the margin */
    201     bool	lineup_to_parens; /* whether continued code within parens
    202 				 * will be lined up to the open paren */
    203     bool	proc_calls_space; /* whether procedure calls look like:
    204 				 * foo (bar) rather than foo(bar) */
    205     bool	procnames_start_line; /* whether the names of procedures
    206 				 * being defined get placed in column 1 (i.e.
    207 				 * a newline is placed between the type of
    208 				 * the procedure and its name) */
    209     bool	space_after_cast; /* "b = (int) a" vs "b = (int)a" */
    210     bool	star_comment_cont; /* whether comment continuation lines
    211 				 * should have stars at the beginning of
    212 				 * each line. */
    213     bool	swallow_optional_blanklines;
    214     bool	auto_typedefs;	/* whether to recognize identifiers
    215 				 * ending in "_t" like typedefs */
    216     int         tabsize;	/* the size of a tab */
    217     int         max_line_length;
    218     bool	use_tabs;	/* set true to use tabs for spacing, false
    219 				 * uses all spaces */
    220     bool	verbose;	/* whether non-essential error messages
    221 				 * are printed */
    222 } opt;
    223 
    224 enum keyword_kind {
    225     kw_0,
    226     kw_offsetof,
    227     kw_sizeof,
    228     kw_struct_or_union_or_enum,
    229     kw_type,
    230     kw_for_or_if_or_while,
    231     kw_do_or_else,
    232     kw_switch,
    233     kw_case_or_default,
    234     kw_jump,
    235     kw_storage_class,
    236     kw_typedef,
    237     kw_inline_or_restrict
    238 };
    239 
    240 
    241 extern bool        found_err;
    242 extern int         next_blank_lines;
    243 extern bool        prefix_blankline_requested;
    244 extern bool        postfix_blankline_requested;
    245 extern bool        break_comma;	/* when true and not in parens, break after a
    246 				 * comma */
    247 extern float       case_ind;	/* indentation level to be used for a "case
    248 				 * n:" */
    249 extern bool        had_eof;		/* whether input is exhausted */
    250 extern int         line_no;		/* the current line number. */
    251 extern bool        inhibit_formatting;	/* true if INDENT OFF is in effect */
    252 
    253 #define	STACKSIZE 256
    254 
    255 extern struct parser_state {
    256     token_type  last_token;
    257     token_type	p_stack[STACKSIZE];	/* this is the parser's stack */
    258     int         il[STACKSIZE];	/* this stack stores indentation levels */
    259     float       cstk[STACKSIZE];/* used to store case stmt indentation levels */
    260     bool	box_com;	/* whether we are in a "boxed" comment. In
    261 				 * that case, the first non-blank char should
    262 				 * be lined up with the '/' in '/' + '*' */
    263     int         comment_delta;	/* used to set up indentation for all lines
    264 				 * of 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
    277 				 * a newline */
    278     bool	in_or_st;	/* true iff there has been a
    279 				 * declarator (e.g. int or char) and no left
    280 				 * paren since the last semicolon. When true,
    281 				 * a '{' is starting a structure definition or
    282 				 * an initialization list */
    283     bool	col_1;		/* whether the last token started in
    284 				 * column 1 */
    285     int         com_col;	/* this is the column in which the current
    286 				 * comment should start */
    287     int         decl_nest;	/* current nesting level for structure or init */
    288     bool	decl_on_line;	/* whether this line of code has part
    289 				 * of a declaration on it */
    290     int         ind_level_follow; /* the level to which ind_level should be set
    291 				 * after the current line is printed */
    292     bool	in_decl;	/* whether we are in a declaration stmt.
    293 				 * The processing of braces is then slightly
    294 				 * different */
    295     bool	in_stmt;
    296     int         ind_level;	/* the current indentation level */
    297     bool	ind_stmt;	/* whether the next line should have an extra
    298 				 * indentation level because we are in the
    299 				 * middle of a stmt */
    300     bool	last_u_d;	/* whether the following operator should be
    301 				 * unary */
    302     int         p_l_follow;	/* used to remember how to indent the
    303 				 * following statement */
    304     int         paren_level;	/* parenthesization level. used to indent
    305 				 * within statements */
    306     short       paren_indents[20]; /* indentation of the operand/argument of
    307 				 * each level of parentheses or brackets,
    308 				 * relative to the enclosing statement */
    309     bool	is_case_label;	/* 'case' and 'default' labels are indented
    310 				 * differently from regular labels */
    311     bool	search_brace;	/* whether it is necessary
    312 				 * to buffer up all info up to the start of a
    313 				 * stmt after an if, while, etc */
    314     bool	use_ff;		/* whether the current line should be
    315 				 * terminated with a form feed */
    316     bool	want_blank;	/* whether the following token should
    317 				 * be prefixed by a blank. (Said prefixing is
    318 				 * ignored in some cases.) */
    319     enum keyword_kind keyword;
    320     bool	dumped_decl_indent;
    321     bool	in_parameter_declaration;
    322     int         tos;		/* pointer to top of stack */
    323     char        procname[100];	/* The name of the current procedure */
    324     int         just_saw_decl;
    325 
    326     struct {
    327 	int	comments;
    328 	int	lines;
    329 	int	code_lines;
    330 	int	comment_lines;
    331     }		stats;
    332 }           ps;
    333 
    334 
    335 #ifndef nitems
    336 #define nitems(array) (sizeof (array) / sizeof (array[0]))
    337 #endif
    338 
    339 void		add_typename(const char *);
    340 int		compute_code_indent(void);
    341 int		compute_label_indent(void);
    342 int		indentation_after_range(int, const char *, const char *);
    343 int		indentation_after(int, const char *);
    344 #ifdef debug
    345 void		debug_vis_range(const char *, const char *, const char *,
    346 		    const char *);
    347 void		debug_printf(const char *, ...) __printflike(1, 2);
    348 void		debug_println(const char *, ...) __printflike(1, 2);
    349 const char *	token_type_name(token_type);
    350 #else
    351 #define		debug_printf(fmt, ...) do { } while (false)
    352 #define		debug_println(fmt, ...) do { } while (false)
    353 #define		debug_vis_range(prefix, s, e, suffix) do { } while (false)
    354 #endif
    355 void		inbuf_skip(void);
    356 char		inbuf_next(void);
    357 token_type	lexi(struct parser_state *);
    358 void		diag(int, const char *, ...) __printflike(2, 3);
    359 void		dump_line(void);
    360 void		fill_buffer(void);
    361 void		parse(token_type);
    362 void		process_comment(void);
    363 void		set_option(const char *, const char *);
    364 void		load_profiles(const char *);
    365 
    366 void		*xmalloc(size_t);
    367 void		*xrealloc(void *, size_t);
    368 char		*xstrdup(const char *);
    369 
    370 void		buf_expand(struct buffer *, size_t);
    371 
    372 static inline bool
    373 is_hspace(char ch)
    374 {
    375     return ch == ' ' || ch == '\t';
    376 }
    377