indent.h revision 1.137 1 /* $NetBSD: indent.h,v 1.137 2023/05/15 10:13:40 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 #include <ctype.h>
68 #include <stdbool.h>
69 #include <stdio.h>
70
71 typedef enum lexer_symbol {
72 lsym_eof,
73 lsym_preprocessing, /* '#' */
74 lsym_newline,
75 lsym_form_feed,
76 lsym_comment, /* the initial '/ *' or '//' of a comment */
77 lsym_lparen_or_lbracket,
78 lsym_rparen_or_rbracket,
79 lsym_lbrace,
80 lsym_rbrace,
81 lsym_period,
82 lsym_unary_op, /* e.g. '*', '&', '-' or leading '++' */
83 lsym_binary_op, /* e.g. '*', '&', '<<', '&&' or '/=' */
84 lsym_postfix_op, /* trailing '++' or '--' */
85 lsym_question, /* the '?' from a '?:' expression */
86 lsym_colon,
87 lsym_comma,
88 lsym_semicolon,
89 lsym_typedef,
90 lsym_storage_class,
91 lsym_type_outside_parentheses,
92 lsym_type_in_parentheses,
93 lsym_tag, /* 'struct', 'union' or 'enum' */
94 lsym_case_label, /* 'case' or 'default' */
95 lsym_sizeof,
96 lsym_offsetof,
97 lsym_word, /* identifier, constant or string */
98 lsym_funcname,
99 lsym_do,
100 lsym_else,
101 lsym_for,
102 lsym_if,
103 lsym_switch,
104 lsym_while,
105 lsym_return
106 } lexer_symbol;
107
108 typedef enum parser_symbol {
109 psym_0, /* a placeholder */
110 psym_lbrace,
111 psym_rbrace,
112 psym_decl,
113 psym_stmt,
114 psym_stmt_list,
115 psym_for_exprs, /* 'for' '(' ... ')' */
116 psym_if_expr, /* 'if' '(' expr ')' */
117 psym_if_expr_stmt, /* 'if' '(' expr ')' stmt */
118 psym_if_expr_stmt_else, /* 'if' '(' expr ')' stmt 'else' */
119 psym_else, /* 'else'; not stored on the stack */
120 psym_switch_expr, /* 'switch' '(' expr ')' */
121 psym_do, /* 'do' */
122 psym_do_stmt, /* 'do' stmt */
123 psym_while_expr, /* 'while' '(' expr ')' */
124 } parser_symbol;
125
126 /* A range of characters, not null-terminated. */
127 struct buffer {
128 const char *st; /* start of the usable text */
129 char *mem;
130 size_t len; /* length of the usable text, from 'mem' */
131 size_t cap;
132 };
133
134 extern FILE *input;
135 extern FILE *output;
136
137 extern struct buffer token; /* the current token to be processed, is
138 * typically copied to the buffer 'code', or
139 * in some cases to 'lab'. */
140
141 extern struct buffer lab; /* the label or preprocessor directive */
142 extern struct buffer code; /* the main part of the current line of code */
143 extern struct buffer com; /* the trailing comment of the line, or the
144 * start or end of a multi-line comment, or
145 * while in process_comment, a single line of
146 * a multi-line comment */
147
148 extern struct options {
149 bool blanklines_around_conditional_compilation;
150 bool blank_line_after_decl_at_top; /* this is vaguely similar to
151 * blank_line_after_decl except that
152 * it only applies to the first set of
153 * declarations in a procedure (just
154 * after the first '{') and it causes
155 * a blank line to be generated even
156 * if there are no declarations */
157 bool blank_line_after_decl;
158 bool blanklines_after_procs;
159 bool blanklines_before_block_comments;
160 bool break_after_comma; /* whether to break declarations after commas */
161 bool brace_same_line; /* whether brace should be on same line as if,
162 * while, etc */
163 bool blank_after_sizeof; /* whether a blank should always be inserted
164 * after sizeof */
165 bool comment_delimiter_on_blankline;
166 int decl_comment_column; /* the column in which comments after
167 * declarations should be put */
168 bool cuddle_else; /* whether 'else' should cuddle up to '}' */
169 int continuation_indent; /* the indentation between the edge of code
170 * and continuation lines */
171 float case_indent; /* The distance (measured in indentation
172 * levels) to indent case labels from the
173 * switch statement */
174 int comment_column; /* the column in which comments to the right
175 * of code should start */
176 int decl_indent; /* indentation of identifier in declaration */
177 bool ljust_decl; /* true if declarations should be left
178 * justified */
179 int unindent_displace; /* comments not to the right of code will be
180 * placed this many indentation levels to the
181 * left of code */
182 bool extra_expr_indent; /* whether continuation lines from the
183 * expression part of "if (e)", "while (e)",
184 * "for (e; e; e)" should be indented an extra
185 * tab stop so that they don't conflict with
186 * the code that follows */
187 bool else_if; /* whether else-if pairs use the same line */
188 bool function_brace_split; /* split function declaration and brace onto
189 * separate lines */
190 bool format_col1_comments; /* If comments which start in column 1 are to
191 * be reformatted (just like comments that
192 * begin in later columns) */
193 bool format_block_comments; /* whether comments beginning with '/ * \n'
194 * 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 will
202 * be lined up to the open paren */
203 bool proc_calls_space; /* whether function calls look like: foo (bar)
204 * rather than foo(bar) */
205 bool procnames_start_line; /* whether the names of procedures being
206 * defined get placed in column 1 (i.e. a
207 * newline is placed between the type of the
208 * 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 should
211 * have stars at the beginning of each line. */
212 bool swallow_optional_blanklines;
213 bool auto_typedefs; /* whether to recognize identifiers ending in
214 * "_t" like typedefs */
215 int tabsize; /* the size of a tab */
216 int max_line_length;
217 bool use_tabs; /* set true to use tabs for spacing, false
218 * uses all spaces */
219 bool verbose; /* whether non-essential error messages are
220 * printed */
221 } opt;
222
223 extern bool found_err;
224 extern bool break_comma; /* when true and not in parentheses, break
225 * after a comma */
226 extern float case_ind; /* indentation level to be used for a "case
227 * n:" */
228 extern bool had_eof; /* whether input is exhausted */
229 extern int line_no; /* the current line number. */
230 extern bool inhibit_formatting; /* true if INDENT OFF is in effect */
231
232 #define STACKSIZE 256
233
234 /* Properties of each level of parentheses or brackets. */
235 typedef struct paren_level_props {
236 short indent; /* indentation of the operand/argument,
237 * relative to the enclosing statement; if
238 * negative, reflected at -1 */
239 bool maybe_cast; /* whether the parentheses may form a type
240 * cast */
241 bool no_cast; /* whether the parentheses definitely do not
242 * form a type cast */
243 } paren_level_props;
244
245 /*
246 * The parser state determines the layout of the formatted text.
247 *
248 * In a function body, the number of block braces determines the indentation
249 * of statements and declarations.
250 *
251 * In a statement, the number of parentheses or brackets determines the
252 * indentation of follow-up lines.
253 *
254 * In an expression, the token type determine whether to put spaces around.
255 *
256 * In a source file, the types of line determine the vertical spacing, such as
257 * around preprocessing directives or function bodies, or above block
258 * comments.
259 */
260 extern struct parser_state {
261 lexer_symbol prev_token; /* the previous token, but never comment,
262 * newline or preprocessing line */
263
264 /* Token classification */
265
266 int quest_level; /* when this is positive, we have seen a '?'
267 * without the matching ':' in a '?:'
268 * expression */
269 bool is_function_definition;
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 init_or_struct; /* whether there has been a type name and no
274 * left parenthesis since the last semicolon.
275 * When true, a '{' starts a structure
276 * definition or an initialization list */
277 bool decl_on_line; /* whether this line of code has part of a
278 * declaration on it */
279 bool in_stmt_or_decl; /* whether in a statement or a struct
280 * declaration or a plain declaration */
281 bool in_decl; /* whether we are in a declaration. The
282 * processing of braces is then slightly
283 * different */
284 bool in_func_def_params;
285 bool seen_case; /* set to true when we see a 'case', so we
286 * know what to do with the following colon */
287 bool is_case_label; /* 'case' and 'default' labels are indented
288 * differently from regular labels */
289 parser_symbol spaced_expr_psym; /* the parser symbol to be shifted
290 * after the parenthesized expression
291 * from a 'for', 'if', 'switch' or
292 * 'while'; or psym_0 */
293
294 /* Indentation of statements and declarations */
295
296 int ind_level; /* the indentation level for the line that is
297 * currently prepared for output */
298 int ind_level_follow; /* the level to which ind_level should be set
299 * after the current line is printed */
300 bool in_stmt_cont; /* whether the current line should have an
301 * extra indentation level because we are in
302 * the middle of a statement */
303 int decl_level; /* current nesting level for a structure
304 * declaration or an initializer */
305 bool decl_indent_done; /* whether the indentation for a declaration
306 * has been added to the code buffer. */
307 int decl_ind; /* current indentation for declarations */
308 int di_stack[20]; /* a stack of structure indentation levels */
309 bool tabs_to_var; /* true if using tabs to indent to var name */
310
311 enum {
312 in_enum_no, /* outside any 'enum { ... }' */
313 in_enum_enum, /* after keyword 'enum' */
314 in_enum_type, /* after 'enum' or 'enum tag' */
315 in_enum_brace /* between '{' and '}' */
316 } in_enum; /* enum { . } */
317
318 int tos; /* pointer to top of stack */
319 parser_symbol s_sym[STACKSIZE];
320 int s_ind_level[STACKSIZE];
321 float s_case_ind_level[STACKSIZE];
322
323 /* Spacing inside a statement or declaration */
324
325 bool next_unary; /* whether the following operator should be
326 * unary; is used in declarations for '*', as
327 * well as in expressions */
328 bool want_blank; /* whether the following token should be
329 * prefixed by a blank. (Said prefixing is
330 * ignored in some cases.) */
331 int line_start_nparen; /* the number of parentheses or brackets that
332 * were already open at the beginning of the
333 * current line; used to indent within
334 * statements, initializers and declarations */
335 int nparen; /* the number of parentheses or brackets that
336 * are currently open; used to indent the
337 * remaining lines of the statement,
338 * initializer or declaration */
339 paren_level_props paren[20];
340
341 /* Horizontal spacing for comments */
342
343 int comment_delta; /* used to set up indentation for all lines of
344 * a boxed comment after the first one */
345 int n_comment_delta; /* remembers how many columns there were
346 * before the start of a box comment so that
347 * forthcoming lines of the comment are
348 * indented properly */
349 int com_ind; /* indentation of the current comment */
350
351 /* Vertical spacing */
352
353 bool force_nl; /* whether the next token goes to a new
354 * line */
355
356 enum declaration {
357 decl_no, /* no declaration anywhere nearby */
358 decl_begin, /* collecting tokens of a declaration */
359 decl_end, /* finished a declaration */
360 } declaration;
361 bool blank_line_after_decl;
362
363 /* Comments */
364
365 bool curr_col_1; /* whether the current token started in column
366 * 1 of the original input */
367 bool next_col_1;
368 } ps;
369
370
371 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
372
373 #ifdef debug
374 void debug_printf(const char *, ...) __printflike(1, 2);
375 void debug_println(const char *, ...) __printflike(1, 2);
376 void debug_vis_range(const char *, const char *, size_t, const char *);
377 void debug_parser_state(lexer_symbol);
378 void debug_parse_stack(const char *);
379 void debug_buffers(void);
380 extern const char *const lsym_name[];
381 extern const char *const psym_name[];
382 #else
383 #define debug_noop() do { } while (false)
384 #define debug_printf(fmt, ...) debug_noop()
385 #define debug_println(fmt, ...) debug_noop()
386 #define debug_vis_range(prefix, s, e, suffix) debug_noop()
387 #define debug_parser_state(lsym) debug_noop()
388 #define debug_parse_stack(situation) debug_noop()
389 #define debug_buffers() debug_noop()
390 #endif
391
392 void register_typename(const char *);
393 int compute_code_indent(void);
394 int compute_label_indent(void);
395 int ind_add(int, const char *, size_t);
396
397 const char *inp_p(void);
398 const char *inp_line_start(void);
399 char inp_peek(void);
400 char inp_lookahead(size_t);
401 void inp_skip(void);
402 char inp_next(void);
403
404 lexer_symbol lexi(void);
405 void diag(int, const char *, ...) __printflike(2, 3);
406 void output_line(void);
407 void output_line_ff(void);
408 void inp_read_line(void);
409 void parse(parser_symbol);
410 void process_comment(void);
411 void set_option(const char *, const char *);
412 void load_profiles(const char *);
413
414 void *nonnull(void *);
415
416 void buf_add_char(struct buffer *, char);
417 void buf_add_chars(struct buffer *, const char *, size_t);
418
419 static inline bool
420 ch_isalnum(char ch)
421 {
422 return isalnum((unsigned char)ch) != 0;
423 }
424
425 static inline bool
426 ch_isalpha(char ch)
427 {
428 return isalpha((unsigned char)ch) != 0;
429 }
430
431 static inline bool
432 ch_isblank(char ch)
433 {
434 return ch == ' ' || ch == '\t';
435 }
436
437 static inline bool
438 ch_isdigit(char ch)
439 {
440 return '0' <= ch && ch <= '9';
441 }
442
443 static inline bool
444 ch_isspace(char ch)
445 {
446 return isspace((unsigned char)ch) != 0;
447 }
448
449 static inline int
450 next_tab(int ind)
451 {
452 return ind - ind % opt.tabsize + opt.tabsize;
453 }
454