indent.h revision 1.182 1 /* $NetBSD: indent.h,v 1.182 2023/06/09 16:23:43 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, /* the initial '#' of a preprocessing line */
74 lsym_newline,
75 lsym_comment, /* the initial '/ *' or '//' of a comment */
76
77 lsym_lparen,
78 lsym_rparen,
79 lsym_lbracket,
80 lsym_rbracket,
81 lsym_lbrace,
82 lsym_rbrace,
83
84 lsym_period,
85 lsym_unary_op, /* e.g. '*', '&', '-' or leading '++' */
86 lsym_sizeof,
87 lsym_offsetof,
88 lsym_postfix_op, /* trailing '++' or '--' */
89 lsym_binary_op, /* e.g. '*', '&', '<<', '&&' or '/=' */
90 lsym_question, /* the '?' from a '?:' expression */
91 lsym_colon_question, /* the ':' from a '?:' expression */
92 lsym_comma,
93
94 lsym_typedef,
95 lsym_modifier, /* modifiers for types, functions, variables */
96 lsym_tag, /* 'struct', 'union' or 'enum' */
97 lsym_type_outside_parentheses,
98 lsym_type_in_parentheses,
99 lsym_word, /* identifier, constant or string */
100 lsym_funcname, /* name of a function being defined */
101 lsym_colon_label, /* the ':' after a label */
102 lsym_colon_other, /* bit-fields, generic-association (C11),
103 * enum-type-specifier (C23),
104 * attribute-prefixed-token (C23),
105 * pp-prefixed-parameter (C23 6.10) */
106 lsym_semicolon,
107
108 lsym_case,
109 lsym_default,
110 lsym_do,
111 lsym_else,
112 lsym_for,
113 lsym_if,
114 lsym_switch,
115 lsym_while,
116 lsym_return,
117 } lexer_symbol;
118
119 /*
120 * Structure of the source code, in terms of declarations, statements and
121 * braces; used to determine the indentation level of these parts.
122 */
123 typedef enum parser_symbol {
124 psym_0, /* a placeholder; not stored on the stack */
125 psym_lbrace_block, /* '{' for a block of code */
126 psym_lbrace_struct, /* '{' in 'struct ... { ... }' */
127 psym_lbrace_union, /* '{' in 'union ... { ... }' */
128 psym_lbrace_enum, /* '{' in 'enum ... { ... }' */
129 psym_rbrace, /* not stored on the stack */
130 psym_decl,
131 psym_stmt,
132 psym_stmt_list,
133 psym_for_exprs, /* 'for' '(' ... ')' */
134 psym_if_expr, /* 'if' '(' expr ')' */
135 psym_if_expr_stmt, /* 'if' '(' expr ')' stmt */
136 psym_if_expr_stmt_else, /* 'if' '(' expr ')' stmt 'else' */
137 psym_else, /* 'else'; not stored on the stack */
138 psym_switch_expr, /* 'switch' '(' expr ')' */
139 psym_do, /* 'do' */
140 psym_do_stmt, /* 'do' stmt */
141 psym_while_expr, /* 'while' '(' expr ')' */
142 } parser_symbol;
143
144 /* A range of characters, not null-terminated. */
145 struct buffer {
146 char *s;
147 size_t len;
148 size_t cap;
149 };
150
151 extern FILE *input;
152 extern FILE *output;
153
154 /*
155 * The current line from the input file, used by the lexer to generate tokens.
156 * To read from the line, start at inp_p and continue up to and including the
157 * next '\n'. To read beyond the '\n', call inp_skip or inp_next, which will
158 * make the next line available, invalidating any pointers into the previous
159 * line.
160 */
161 extern struct buffer inp;
162 extern const char *inp_p;
163
164 extern struct buffer token; /* the current token to be processed, is
165 * typically copied to the buffer 'code', or in
166 * some cases to 'lab'. */
167
168 extern struct buffer lab; /* the label or preprocessor directive */
169 extern struct buffer code; /* the main part of the current line of code,
170 * containing declarations or statements */
171 extern struct buffer com; /* the trailing comment of the line, or the
172 * start or end of a multi-line comment, or
173 * while in process_comment, a single line of a
174 * multi-line comment */
175
176 extern struct options {
177 bool blanklines_around_conditional_compilation;
178 bool blank_line_after_decl_at_top; /* this is vaguely similar to
179 * blank_line_after_decl except
180 * that it only applies to the
181 * first set of declarations in
182 * a procedure (just after the
183 * first '{') and it causes a
184 * blank line to be generated
185 * even if there are no
186 * declarations */
187 bool blank_line_after_decl;
188 bool blanklines_after_procs;
189 bool blanklines_before_block_comments;
190 bool break_after_comma; /* whether to add a line break after each
191 * declarator */
192 bool brace_same_line; /* whether brace should be on same line as if,
193 * while, etc */
194 bool blank_after_sizeof; /* whether a blank should always be
195 * inserted after sizeof */
196 bool comment_delimiter_on_blankline;
197 int decl_comment_column; /* the column in which comments after
198 * declarations should be put */
199 bool cuddle_else; /* whether 'else' should cuddle up to '}' */
200 int continuation_indent; /* the indentation between the edge of
201 * code and continuation lines */
202 float case_indent; /* The distance (measured in indentation
203 * levels) to indent case labels from the
204 * switch statement */
205 int comment_column; /* the column in which comments to the right of
206 * code should start */
207 int decl_indent; /* indentation of identifier in declaration */
208 bool left_justify_decl;
209 int unindent_displace; /* comments not to the right of code will be
210 * placed this many indentation levels to the
211 * left of code */
212 bool extra_expr_indent; /* whether continuation lines from the
213 * expression part of "if (e)", "while (e)",
214 * "for (e; e; e)" should be indented an extra
215 * tab stop so that they are not confused with
216 * the code that follows */
217 bool else_if_in_same_line;
218 bool function_brace_split; /* split function declaration and brace
219 * onto separate lines */
220 bool format_col1_comments; /* If comments which start in column 1
221 * are to be reformatted (just like
222 * comments that begin in later
223 * columns) */
224 bool format_block_comments; /* whether comments beginning with '/ *
225 * \n' are to be reformatted */
226 bool indent_parameters;
227 int indent_size; /* the size of one indentation level */
228 int block_comment_max_line_length;
229 int local_decl_indent; /* like decl_indent but for locals */
230 bool lineup_to_parens_always; /* whether to not(?) attempt to keep
231 * lined-up code within the margin */
232 bool lineup_to_parens; /* whether continued code within parens will be
233 * lined up to the open paren */
234 bool proc_calls_space; /* whether function calls look like: foo (bar)
235 * rather than foo(bar) */
236 bool procnames_start_line; /* whether the names of functions being
237 * defined get placed in column 1 (i.e.
238 * a newline is placed between the type
239 * of the function and its name) */
240 bool space_after_cast; /* "b = (int) a" vs. "b = (int)a" */
241 bool star_comment_cont; /* whether comment continuation lines should
242 * have stars at the beginning of each line */
243 bool swallow_optional_blanklines;
244 bool auto_typedefs; /* whether to recognize identifiers ending in
245 * "_t" like typedefs */
246 int tabsize; /* the size of a tab */
247 int max_line_length;
248 bool use_tabs; /* set true to use tabs for spacing, false uses
249 * all spaces */
250 bool verbose; /* print configuration to stderr */
251 } opt;
252
253 extern bool found_err;
254 extern bool had_eof; /* whether input is exhausted */
255 extern int line_no; /* the current line number. */
256 extern enum indent_enabled {
257 indent_on,
258 indent_off,
259 indent_last_off_line,
260 } indent_enabled;
261
262 #define STACKSIZE 256
263
264 /* Properties of each level of parentheses or brackets. */
265 typedef struct paren_level_props {
266 int indent; /* indentation of the operand/argument,
267 * relative to the enclosing statement; if
268 * negative, reflected at -1 */
269 enum paren_level_cast {
270 cast_unknown,
271 cast_maybe,
272 cast_no,
273 } cast; /* whether the parentheses form a type cast */
274 } paren_level_props;
275
276 struct psym_stack {
277 int top; /* pointer to top of stack */
278 parser_symbol sym[STACKSIZE];
279 int ind_level[STACKSIZE];
280 };
281
282 /*
283 * The parser state determines the layout of the formatted text.
284 *
285 * At each '#if', the parser state is copied so that the corresponding '#else'
286 * lines start in the same state.
287 *
288 * In a function body, the number of block braces determines the indentation
289 * of statements and declarations.
290 *
291 * In a statement, the number of parentheses or brackets determines the
292 * indentation of follow-up lines.
293 *
294 * In an expression, the token type determine whether to put spaces around.
295 *
296 * In a source file, the types of line determine the vertical spacing, such as
297 * around preprocessing directives or function bodies, or above block
298 * comments.
299 */
300 extern struct parser_state {
301 lexer_symbol prev_lsym; /* the previous token, but never comment,
302 * newline or preprocessing line */
303
304 /* Token classification */
305
306 int quest_level; /* when this is positive, we have seen a '?'
307 * without the matching ':' in a '?:'
308 * expression */
309 bool is_function_definition; /* starts either at the 'name(' from a
310 * function definition if it occurs at
311 * the beginning of a line, or at the
312 * first '*' from inside a declaration
313 * when the line starts with words
314 * followed by a '('; ends at the end
315 * of that line */
316 bool block_init; /* whether inside a block initialization */
317 int block_init_level; /* the level of brace nesting in an
318 * initialization */
319 bool init_or_struct; /* whether there has been a type name and no
320 * left parenthesis since the last semicolon.
321 * When true, a '{' starts a structure
322 * definition or an initialization list */
323 bool decl_on_line; /* whether this line of code has part of a
324 * declaration on it; used for indenting
325 * comments */
326 bool in_stmt_or_decl; /* whether in a statement or a struct
327 * declaration or a plain declaration */
328 bool in_decl; /* XXX: double-check the exact meaning */
329 bool in_func_def_params;
330 bool seen_case; /* whether there was a 'case' or 'default', to
331 * properly space the following ':' */
332 parser_symbol spaced_expr_psym; /* the parser symbol to be shifted
333 * after the parenthesized expression
334 * from a 'for', 'if', 'switch' or
335 * 'while'; or psym_0 */
336 parser_symbol lbrace_kind; /* the kind of brace to be pushed to
337 * the parser symbol stack next */
338 bool prev_paren_was_cast;
339
340 /* Indentation of statements and declarations */
341
342 int ind_level; /* the indentation level for the line that is
343 * currently prepared for output */
344 int ind_level_follow; /* the level to which ind_level should be set
345 * after the current line is printed */
346 bool in_stmt_cont; /* whether the current line should have an
347 * extra indentation level because we are in
348 * the middle of a statement */
349 int decl_level; /* current nesting level for a structure
350 * declaration or an initializer */
351 int di_stack[20]; /* a stack of structure indentation levels */
352 bool decl_indent_done; /* whether the indentation for a declaration
353 * has been added to the code buffer. */
354 int decl_ind; /* current indentation for declarations */
355 bool tabs_to_var; /* true if using tabs to indent to var name */
356
357 enum {
358 eei_no,
359 eei_maybe,
360 eei_last
361 } extra_expr_indent;
362
363 struct psym_stack psyms;
364
365 /* Spacing inside a statement or declaration */
366
367 bool next_unary; /* whether the following operator should be
368 * unary; is used in declarations for '*', as
369 * well as in expressions */
370 bool want_blank; /* whether the following token should be
371 * prefixed by a blank. (Said prefixing is
372 * ignored in some cases.) */
373 int line_start_nparen; /* the number of parentheses or brackets that
374 * were open at the beginning of the current
375 * line; used to indent within statements,
376 * initializers and declarations */
377 int nparen; /* the number of parentheses or brackets that
378 * are currently open; used to indent the
379 * remaining lines of the statement,
380 * initializer or declaration */
381 paren_level_props paren[20];
382
383 /* Horizontal spacing for comments */
384
385 int comment_delta; /* used to set up indentation for all lines of
386 * a boxed comment after the first one */
387 int n_comment_delta; /* remembers how many columns there were before
388 * the start of a box comment so that
389 * forthcoming lines of the comment are
390 * indented properly */
391 int com_ind; /* indentation of the current comment */
392
393 /* Vertical spacing */
394
395 bool break_after_comma; /* whether to add a newline after the next
396 * comma; used in declarations but not in
397 * initializer lists */
398 bool force_nl; /* whether the next token is forced to go to a
399 * new line; used after 'if (expr)' and in
400 * similar situations; tokens like '{' may
401 * ignore this */
402
403 enum declaration {
404 decl_no, /* no declaration anywhere nearby */
405 decl_begin, /* collecting tokens of a declaration */
406 decl_end, /* finished a declaration */
407 } declaration;
408 bool blank_line_after_decl;
409
410 /* Comments */
411
412 bool curr_col_1; /* whether the current token started in column
413 * 1 of the original input */
414 bool next_col_1;
415 } ps;
416
417 extern struct output_state {
418 enum line_kind {
419 lk_other,
420 lk_blank,
421 lk_if, /* #if, #ifdef, #ifndef */
422 lk_endif, /* #endif */
423 lk_stmt_head, /* the ')' of an incomplete statement such as
424 * 'if (expr)' or 'for (expr; expr; expr)' */
425 lk_func_end, /* the last '}' of a function body */
426 lk_block_comment,
427 lk_case_or_default,
428 } line_kind; /* kind of the line that is being prepared for
429 * output; is reset to lk_other each time after
430 * trying to send a line to the output, even if
431 * that line was a suppressed blank line; used
432 * for inserting or removing blank lines */
433 enum line_kind prev_line_kind; /* the kind of line that was actually
434 * sent to the output */
435
436 struct buffer indent_off_text; /* text from between 'INDENT OFF' and
437 * 'INDENT ON', both inclusive */
438 } out;
439
440
441 #define array_length(array) (sizeof(array) / sizeof((array)[0]))
442
443 #ifdef debug
444 void debug_printf(const char *, ...) __printflike(1, 2);
445 void debug_println(const char *, ...) __printflike(1, 2);
446 void debug_blank_line(void);
447 void debug_vis_range(const char *, const char *, size_t, const char *);
448 void debug_parser_state(void);
449 void debug_parse_stack(const char *);
450 void debug_print_buf(const char *, const struct buffer *);
451 void debug_buffers(void);
452 extern const char *const lsym_name[];
453 extern const char *const psym_name[];
454 extern const char *const paren_level_cast_name[];
455 extern const char *const line_kind_name[];
456 #else
457 #define debug_noop() do { } while (false)
458 #define debug_printf(fmt, ...) debug_noop()
459 #define debug_println(fmt, ...) debug_noop()
460 #define debug_blank_line() debug_noop()
461 #define debug_vis_range(prefix, s, e, suffix) debug_noop()
462 #define debug_parser_state() debug_noop()
463 #define debug_parse_stack(situation) debug_noop()
464 #define debug_print_buf(name, buf) debug_noop()
465 #define debug_buffers() debug_noop()
466 #endif
467
468 void register_typename(const char *);
469 int compute_code_indent(void);
470 int compute_label_indent(void);
471 int ind_add(int, const char *, size_t);
472
473 void inp_skip(void);
474 char inp_next(void);
475
476 lexer_symbol lexi(void);
477 void diag(int, const char *, ...) __printflike(2, 3);
478 void output_line(void);
479 void inp_read_line(void);
480 void parse(parser_symbol);
481 void process_comment(void);
482 void set_option(const char *, const char *);
483 void load_profile_files(const char *);
484
485 void *nonnull(void *);
486
487 void buf_add_char(struct buffer *, char);
488 void buf_add_chars(struct buffer *, const char *, size_t);
489
490 static inline bool
491 ch_isalnum(char ch)
492 {
493 return isalnum((unsigned char)ch) != 0;
494 }
495
496 static inline bool
497 ch_isalpha(char ch)
498 {
499 return isalpha((unsigned char)ch) != 0;
500 }
501
502 static inline bool
503 ch_isblank(char ch)
504 {
505 return ch == ' ' || ch == '\t';
506 }
507
508 static inline bool
509 ch_isdigit(char ch)
510 {
511 return '0' <= ch && ch <= '9';
512 }
513
514 static inline bool
515 ch_isspace(char ch)
516 {
517 return isspace((unsigned char)ch) != 0;
518 }
519
520 static inline int
521 next_tab(int ind)
522 {
523 return ind - ind % opt.tabsize + opt.tabsize;
524 }
525