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