indent.c revision 1.311 1 /* $NetBSD: indent.c,v 1.311 2023/06/02 11:43:07 rillig Exp $ */
2
3 /*-
4 * SPDX-License-Identifier: BSD-4-Clause
5 *
6 * Copyright (c) 1985 Sun Microsystems, Inc.
7 * Copyright (c) 1976 Board of Trustees of the University of Illinois.
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40 #include <sys/cdefs.h>
41 __RCSID("$NetBSD: indent.c,v 1.311 2023/06/02 11:43:07 rillig Exp $");
42
43 #include <sys/param.h>
44 #include <err.h>
45 #include <fcntl.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51
52 #include "indent.h"
53
54 struct options opt = {
55 .brace_same_line = true,
56 .comment_delimiter_on_blankline = true,
57 .cuddle_else = true,
58 .comment_column = 33,
59 .decl_indent = 16,
60 .else_if = true,
61 .function_brace_split = true,
62 .format_col1_comments = true,
63 .format_block_comments = true,
64 .indent_parameters = true,
65 .indent_size = 8,
66 .local_decl_indent = -1,
67 .lineup_to_parens = true,
68 .procnames_start_line = true,
69 .star_comment_cont = true,
70 .tabsize = 8,
71 .max_line_length = 78,
72 .use_tabs = true,
73 };
74
75 struct parser_state ps;
76
77 struct buffer token;
78
79 struct buffer lab;
80 struct buffer code;
81 struct buffer com;
82
83 bool found_err;
84 float case_ind;
85 bool had_eof;
86 int line_no = 1;
87 enum indent_enabled indent_enabled;
88
89 static int ifdef_level;
90 static struct parser_state state_stack[5];
91
92 FILE *input;
93 FILE *output;
94
95 static const char *in_name = "Standard Input";
96 static const char *out_name = "Standard Output";
97 static const char *backup_suffix = ".BAK";
98 static char bakfile[MAXPATHLEN] = "";
99
100
101 void *
102 nonnull(void *p)
103 {
104 if (p == NULL)
105 err(EXIT_FAILURE, NULL);
106 return p;
107 }
108
109 static void
110 buf_expand(struct buffer *buf, size_t add_size)
111 {
112 buf->cap = buf->cap + add_size + 400;
113 buf->mem = nonnull(realloc(buf->mem, buf->cap));
114 buf->st = buf->mem;
115 }
116
117 void
118 buf_add_char(struct buffer *buf, char ch)
119 {
120 if (buf->len == buf->cap)
121 buf_expand(buf, 1);
122 buf->mem[buf->len++] = ch;
123 }
124
125 void
126 buf_add_chars(struct buffer *buf, const char *s, size_t len)
127 {
128 if (len == 0)
129 return;
130 if (len > buf->cap - buf->len)
131 buf_expand(buf, len);
132 memcpy(buf->mem + buf->len, s, len);
133 buf->len += len;
134 }
135
136 static void
137 buf_add_buf(struct buffer *buf, const struct buffer *add)
138 {
139 buf_add_chars(buf, add->st, add->len);
140 }
141
142 void
143 diag(int level, const char *msg, ...)
144 {
145 va_list ap;
146
147 if (level != 0)
148 found_err = true;
149
150 va_start(ap, msg);
151 fprintf(stderr, "%s: %s:%d: ",
152 level == 0 ? "warning" : "error", in_name, line_no);
153 vfprintf(stderr, msg, ap);
154 fprintf(stderr, "\n");
155 va_end(ap);
156 }
157
158 /*
159 * Compute the indentation from starting at 'ind' and adding the text starting
160 * at 's'.
161 */
162 int
163 ind_add(int ind, const char *s, size_t len)
164 {
165 for (const char *p = s; len > 0; p++, len--) {
166 if (*p == '\n')
167 ind = 0;
168 else if (*p == '\t')
169 ind = next_tab(ind);
170 else if (*p == '\b')
171 --ind;
172 else
173 ++ind;
174 }
175 return ind;
176 }
177
178 static void
179 init_globals(void)
180 {
181 ps.s_sym[0] = psym_stmt_list;
182 ps.prev_token = lsym_semicolon;
183 ps.next_col_1 = true;
184
185 const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
186 if (suffix != NULL)
187 backup_suffix = suffix;
188 }
189
190 /*
191 * Copy the input file to the backup file, then make the backup file the input
192 * and the original input file the output.
193 */
194 static void
195 bakcopy(void)
196 {
197 ssize_t n;
198 int bak_fd;
199 char buff[8 * 1024];
200
201 const char *last_slash = strrchr(in_name, '/');
202 snprintf(bakfile, sizeof(bakfile), "%s%s",
203 last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
204
205 /* copy in_name to backup file */
206 bak_fd = creat(bakfile, 0600);
207 if (bak_fd < 0)
208 err(1, "%s", bakfile);
209
210 while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
211 if (write(bak_fd, buff, (size_t)n) != n)
212 err(1, "%s", bakfile);
213 if (n < 0)
214 err(1, "%s", in_name);
215
216 close(bak_fd);
217 (void)fclose(input);
218
219 /* re-open backup file as the input file */
220 input = fopen(bakfile, "r");
221 if (input == NULL)
222 err(1, "%s", bakfile);
223 /* now the original input file will be the output */
224 output = fopen(in_name, "w");
225 if (output == NULL) {
226 unlink(bakfile);
227 err(1, "%s", in_name);
228 }
229 }
230
231 static void
232 load_profiles(int argc, char **argv)
233 {
234 const char *profile_name = NULL;
235
236 for (int i = 1; i < argc; ++i) {
237 const char *arg = argv[i];
238
239 if (strcmp(arg, "-npro") == 0)
240 return;
241 if (arg[0] == '-' && arg[1] == 'P' && arg[2] != '\0')
242 profile_name = arg + 2;
243 }
244
245 load_profile_files(profile_name);
246 }
247
248 static void
249 parse_command_line(int argc, char **argv)
250 {
251 for (int i = 1; i < argc; ++i) {
252 const char *arg = argv[i];
253
254 if (arg[0] == '-') {
255 set_option(arg, "Command line");
256
257 } else if (input == NULL) {
258 in_name = arg;
259 if ((input = fopen(in_name, "r")) == NULL)
260 err(1, "%s", in_name);
261
262 } else if (output == NULL) {
263 out_name = arg;
264 if (strcmp(in_name, out_name) == 0)
265 errx(1, "input and output files "
266 "must be different");
267 if ((output = fopen(out_name, "w")) == NULL)
268 err(1, "%s", out_name);
269
270 } else
271 errx(1, "too many arguments: %s", arg);
272 }
273
274 if (input == NULL) {
275 input = stdin;
276 output = stdout;
277 } else if (output == NULL) {
278 out_name = in_name;
279 bakcopy();
280 }
281
282 if (opt.comment_column <= 1)
283 opt.comment_column = 2; /* don't put normal comments in column
284 * 1, see opt.format_col1_comments */
285 if (opt.block_comment_max_line_length <= 0)
286 opt.block_comment_max_line_length = opt.max_line_length;
287 if (opt.local_decl_indent < 0)
288 opt.local_decl_indent = opt.decl_indent;
289 if (opt.decl_comment_column <= 0)
290 opt.decl_comment_column = opt.ljust_decl
291 ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
292 : opt.comment_column;
293 if (opt.continuation_indent == 0)
294 opt.continuation_indent = opt.indent_size;
295 }
296
297 static void
298 set_initial_indentation(void)
299 {
300 inp_read_line();
301
302 int ind = 0;
303 for (const char *p = inp.st;; p++) {
304 if (*p == ' ')
305 ind++;
306 else if (*p == '\t')
307 ind = next_tab(ind);
308 else
309 break;
310 }
311
312 ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
313 }
314
315 static void
316 code_add_decl_indent(int decl_ind, bool tabs_to_var)
317 {
318 int base = ps.ind_level * opt.indent_size;
319 int ind = base + (int)code.len;
320 int target = base + decl_ind;
321 size_t orig_code_len = code.len;
322
323 if (tabs_to_var)
324 for (int next; (next = next_tab(ind)) <= target; ind = next)
325 buf_add_char(&code, '\t');
326
327 for (; ind < target; ind++)
328 buf_add_char(&code, ' ');
329
330 if (code.len == orig_code_len && ps.want_blank) {
331 buf_add_char(&code, ' ');
332 ps.want_blank = false;
333 }
334 }
335
336 static void
337 update_ps_decl_ptr(lexer_symbol lsym)
338 {
339 switch (ps.decl_ptr) {
340 case dp_start:
341 if (lsym == lsym_storage_class)
342 ps.decl_ptr = dp_start;
343 else if (lsym == lsym_type_outside_parentheses)
344 ps.decl_ptr = dp_word;
345 else if (lsym == lsym_word)
346 ps.decl_ptr = dp_word;
347 else
348 ps.decl_ptr = dp_other;
349 break;
350 case dp_word:
351 if (lsym == lsym_unary_op && token.st[0] == '*')
352 ps.decl_ptr = dp_word_asterisk;
353 else
354 ps.decl_ptr = dp_other;
355 break;
356 case dp_word_asterisk:
357 if (lsym == lsym_unary_op && token.st[0] == '*')
358 ps.decl_ptr = dp_word_asterisk;
359 else
360 ps.decl_ptr = dp_other;
361 break;
362 case dp_other:
363 if (lsym == lsym_semicolon || lsym == lsym_rbrace)
364 ps.decl_ptr = dp_start;
365 if (lsym == lsym_lparen_or_lbracket
366 && ps.prev_token == lsym_for)
367 ps.decl_ptr = dp_start;
368 if (lsym == lsym_comma && ps.in_decl)
369 ps.decl_ptr = dp_start;
370 break;
371 }
372 }
373
374 static void
375 update_ps_in_enum(lexer_symbol lsym)
376 {
377 switch (ps.in_enum) {
378 case in_enum_no:
379 if (lsym == lsym_tag && token.st[0] == 'e')
380 ps.in_enum = in_enum_enum;
381 break;
382 case in_enum_enum:
383 if (lsym == lsym_type_outside_parentheses
384 || lsym == lsym_type_in_parentheses)
385 ps.in_enum = in_enum_type;
386 else if (lsym == lsym_lbrace)
387 ps.in_enum = in_enum_brace;
388 else
389 ps.in_enum = in_enum_no;
390 break;
391 case in_enum_type:
392 if (lsym == lsym_lbrace)
393 ps.in_enum = in_enum_brace;
394 else
395 ps.in_enum = in_enum_no;
396 break;
397 case in_enum_brace:
398 if (lsym == lsym_rbrace)
399 ps.in_enum = in_enum_no;
400 break;
401 }
402 }
403
404 static int
405 process_eof(void)
406 {
407 if (lab.len > 0 || code.len > 0 || com.len > 0)
408 output_line();
409 if (indent_enabled != indent_on) {
410 indent_enabled = indent_last_off_line;
411 output_line();
412 }
413
414 if (ps.tos > 1) /* check for balanced braces */
415 diag(1, "Stuff missing from end of file");
416
417 fflush(output);
418 return found_err ? EXIT_FAILURE : EXIT_SUCCESS;
419 }
420
421 static void
422 maybe_break_line(lexer_symbol lsym)
423 {
424 if (!ps.force_nl)
425 return;
426 if (lsym == lsym_semicolon)
427 return;
428 if (lsym == lsym_lbrace && opt.brace_same_line)
429 return;
430
431 if (opt.verbose)
432 diag(0, "Line broken");
433 output_line();
434 ps.force_nl = false;
435 }
436
437 static void
438 move_com_to_code(lexer_symbol lsym)
439 {
440 if (ps.want_blank)
441 buf_add_char(&code, ' ');
442 buf_add_buf(&code, &com);
443 if (lsym != lsym_rparen_or_rbracket)
444 buf_add_char(&code, ' ');
445 com.len = 0;
446 ps.want_blank = false;
447 }
448
449 static void
450 process_newline(void)
451 {
452 if (ps.prev_token == lsym_comma
453 && ps.nparen == 0 && !ps.block_init
454 && !opt.break_after_comma && ps.break_after_comma
455 && lab.len == 0 /* for preprocessing lines */
456 && com.len == 0)
457 goto stay_in_line;
458
459 output_line();
460
461 stay_in_line:
462 ++line_no;
463 }
464
465 static bool
466 is_function_pointer_declaration(void)
467 {
468 return token.st[0] == '('
469 && ps.in_decl
470 && !ps.block_init
471 && !ps.decl_indent_done
472 && !ps.is_function_definition
473 && ps.line_start_nparen == 0;
474 }
475
476 static bool
477 want_blank_before_lparen(void)
478 {
479 if (!ps.want_blank)
480 return false;
481 if (opt.proc_calls_space)
482 return true;
483 if (ps.prev_token == lsym_rparen_or_rbracket)
484 return false;
485 if (ps.prev_token == lsym_offsetof)
486 return false;
487 if (ps.prev_token == lsym_sizeof)
488 return opt.blank_after_sizeof;
489 if (ps.prev_token == lsym_word || ps.prev_token == lsym_funcname)
490 return false;
491 return true;
492 }
493
494 static bool
495 want_blank_before_lbracket(void)
496 {
497 if (code.len == 0)
498 return false;
499 if (ps.prev_token == lsym_comma)
500 return true;
501 if (ps.prev_token == lsym_binary_op)
502 return true;
503 return false;
504 }
505
506 static void
507 process_lparen_or_lbracket(void)
508 {
509 if (++ps.nparen == array_length(ps.paren)) {
510 diag(0, "Reached internal limit of %zu unclosed parentheses",
511 array_length(ps.paren));
512 ps.nparen--;
513 }
514
515 if (is_function_pointer_declaration()) {
516 code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
517 ps.decl_indent_done = true;
518 } else if (token.st[0] == '('
519 ? want_blank_before_lparen() : want_blank_before_lbracket())
520 buf_add_char(&code, ' ');
521 ps.want_blank = false;
522 buf_add_char(&code, token.st[0]);
523
524 int indent = ind_add(0, code.st, code.len);
525 enum paren_level_cast cast = cast_unknown;
526
527 if (opt.extra_expr_indent && !opt.lineup_to_parens
528 && ps.spaced_expr_psym != psym_0 && ps.nparen == 1
529 && opt.continuation_indent == opt.indent_size)
530 ps.extra_expr_indent = eei_yes;
531
532 if (opt.extra_expr_indent && ps.spaced_expr_psym != psym_0
533 && ps.nparen == 1 && indent < 2 * opt.indent_size)
534 indent = 2 * opt.indent_size;
535
536 if (ps.init_or_struct && *token.st == '(' && ps.tos <= 2) {
537 /* this is a kluge to make sure that declarations will be
538 * aligned right if proc decl has an explicit type on it, i.e.
539 * "int a(x) {..." */
540 parse(psym_0);
541 ps.init_or_struct = false;
542 }
543
544 if (ps.prev_token == lsym_offsetof || ps.prev_token == lsym_sizeof
545 || ps.is_function_definition)
546 cast = cast_no;
547
548 ps.paren[ps.nparen - 1].indent = indent;
549 ps.paren[ps.nparen - 1].cast = cast;
550 debug_println("paren_indents[%d] is now %s%d",
551 ps.nparen - 1, paren_level_cast_name[cast], indent);
552 }
553
554 static void
555 process_rparen_or_rbracket(void)
556 {
557 if (ps.nparen == 0) {
558 diag(0, "Extra '%c'", *token.st);
559 goto unbalanced;
560 }
561
562 enum paren_level_cast cast = ps.paren[--ps.nparen].cast;
563 if (ps.decl_on_line && !ps.block_init)
564 cast = cast_no;
565
566 if (cast == cast_maybe) {
567 ps.next_unary = true;
568 ps.want_blank = opt.space_after_cast;
569 } else
570 ps.want_blank = true;
571
572 if (code.len == 0) /* if the paren starts the line */
573 ps.line_start_nparen = ps.nparen; /* then indent it */
574
575 unbalanced:
576 buf_add_char(&code, token.st[0]);
577
578 if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
579 if (ps.extra_expr_indent == eei_yes)
580 ps.extra_expr_indent = eei_last;
581 ps.force_nl = true;
582 ps.next_unary = true;
583 ps.in_stmt_or_decl = false;
584 parse(ps.spaced_expr_psym);
585 ps.spaced_expr_psym = psym_0;
586 ps.want_blank = true;
587 out.line_kind = lk_stmt_head;
588 }
589 }
590
591 static bool
592 want_blank_before_unary_op(void)
593 {
594 if (ps.want_blank)
595 return true;
596 if (token.st[0] == '+' || token.st[0] == '-')
597 return code.len > 0 && code.mem[code.len - 1] == token.st[0];
598 return false;
599 }
600
601 static void
602 process_unary_op(void)
603 {
604 if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
605 !ps.is_function_definition && ps.line_start_nparen == 0) {
606 /* pointer declarations */
607 code_add_decl_indent(ps.decl_ind - (int)token.len,
608 ps.tabs_to_var);
609 ps.decl_indent_done = true;
610 } else if (want_blank_before_unary_op())
611 buf_add_char(&code, ' ');
612
613 buf_add_buf(&code, &token);
614 ps.want_blank = false;
615 }
616
617 static void
618 process_binary_op(void)
619 {
620 if (code.len > 0 && ps.want_blank)
621 buf_add_char(&code, ' ');
622 buf_add_buf(&code, &token);
623 ps.want_blank = true;
624 }
625
626 static void
627 process_postfix_op(void)
628 {
629 buf_add_buf(&code, &token);
630 ps.want_blank = true;
631 }
632
633 static void
634 process_question(void)
635 {
636 ps.quest_level++;
637 if (code.len == 0) {
638 ps.in_stmt_cont = true;
639 ps.in_stmt_or_decl = true;
640 ps.in_decl = false;
641 }
642 if (ps.want_blank)
643 buf_add_char(&code, ' ');
644 buf_add_char(&code, '?');
645 ps.want_blank = true;
646 }
647
648 static void
649 process_colon(void)
650 {
651 if (ps.quest_level > 0) { /* part of a '?:' operator */
652 ps.quest_level--;
653 if (code.len == 0) {
654 ps.in_stmt_cont = true;
655 ps.in_stmt_or_decl = true;
656 ps.in_decl = false;
657 }
658 if (ps.want_blank)
659 buf_add_char(&code, ' ');
660 buf_add_char(&code, ':');
661 ps.want_blank = true;
662 return;
663 }
664
665 if (ps.init_or_struct) { /* bit-field */
666 buf_add_char(&code, ':');
667 ps.want_blank = false;
668 return;
669 }
670
671 buf_add_buf(&lab, &code); /* 'case' or 'default' or named label
672 */
673 buf_add_char(&lab, ':');
674 code.len = 0;
675
676 ps.in_stmt_or_decl = false;
677 ps.is_case_label = ps.seen_case;
678 ps.force_nl = ps.seen_case;
679 ps.seen_case = false;
680 ps.want_blank = false;
681 }
682
683 static void
684 process_semicolon(void)
685 {
686 if (ps.decl_level == 0)
687 ps.init_or_struct = false;
688 ps.seen_case = false; /* only needs to be reset on error */
689 ps.quest_level = 0; /* only needs to be reset on error */
690 if (ps.prev_token == lsym_rparen_or_rbracket)
691 ps.in_func_def_params = false;
692 ps.block_init = false;
693 ps.block_init_level = 0;
694 ps.declaration = ps.declaration == decl_begin ? decl_end : decl_no;
695
696 if (ps.in_decl && code.len == 0 && !ps.block_init &&
697 !ps.decl_indent_done && ps.line_start_nparen == 0) {
698 /* indent stray semicolons in declarations */
699 code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
700 ps.decl_indent_done = true;
701 }
702
703 ps.in_decl = ps.decl_level > 0; /* if we were in a first level
704 * structure declaration before, we
705 * aren't anymore */
706
707 if (ps.nparen > 0 && ps.spaced_expr_psym != psym_for_exprs) {
708 /* There were unbalanced parentheses in the statement. It is a
709 * bit complicated, because the semicolon might be in a for
710 * statement. */
711 diag(1, "Unbalanced parentheses");
712 ps.nparen = 0;
713 if (ps.spaced_expr_psym != psym_0) {
714 parse(ps.spaced_expr_psym);
715 ps.spaced_expr_psym = psym_0;
716 }
717 }
718 buf_add_char(&code, ';');
719 ps.want_blank = true;
720 ps.in_stmt_or_decl = ps.nparen > 0;
721 ps.decl_ind = 0;
722
723 if (ps.spaced_expr_psym == psym_0) {
724 parse(psym_0); /* let parser know about end of stmt */
725 ps.force_nl = true;
726 }
727 }
728
729 static void
730 process_lbrace(void)
731 {
732 ps.in_stmt_or_decl = false; /* don't indent the {} */
733
734 if (!ps.block_init)
735 ps.force_nl = true;
736 else if (ps.block_init_level <= 0)
737 ps.block_init_level = 1;
738 else
739 ps.block_init_level++;
740
741 if (code.len > 0 && !ps.block_init) {
742 if (!opt.brace_same_line ||
743 (code.len > 0 && code.mem[code.len - 1] == '}'))
744 output_line();
745 else if (ps.in_func_def_params && !ps.init_or_struct) {
746 ps.ind_level_follow = 0;
747 if (opt.function_brace_split)
748 output_line();
749 else
750 ps.want_blank = true;
751 }
752 }
753
754 if (ps.nparen > 0) {
755 diag(1, "Unbalanced parentheses");
756 ps.nparen = 0;
757 if (ps.spaced_expr_psym != psym_0) {
758 parse(ps.spaced_expr_psym);
759 ps.spaced_expr_psym = psym_0;
760 ps.ind_level = ps.ind_level_follow;
761 }
762 }
763
764 if (code.len == 0)
765 ps.in_stmt_cont = false; /* don't indent the '{' itself
766 */
767 if (ps.in_decl && ps.init_or_struct) {
768 ps.di_stack[ps.decl_level] = ps.decl_ind;
769 if (++ps.decl_level == (int)array_length(ps.di_stack)) {
770 diag(0, "Reached internal limit of %d struct levels",
771 (int)array_length(ps.di_stack));
772 ps.decl_level--;
773 }
774 } else {
775 ps.decl_on_line = false; /* we can't be in the middle of
776 * a declaration, so don't do
777 * special indentation of
778 * comments */
779 ps.in_func_def_params = false;
780 ps.in_decl = false;
781 }
782
783 ps.decl_ind = 0;
784 parse(psym_lbrace);
785 if (ps.want_blank)
786 buf_add_char(&code, ' ');
787 ps.want_blank = false;
788 buf_add_char(&code, '{');
789 ps.declaration = decl_no;
790 }
791
792 static void
793 process_rbrace(void)
794 {
795 if (ps.nparen > 0) { /* check for unclosed if, for, else. */
796 diag(1, "Unbalanced parentheses");
797 ps.nparen = 0;
798 ps.spaced_expr_psym = psym_0;
799 }
800
801 ps.declaration = decl_no;
802 ps.block_init_level--;
803
804 if (code.len > 0 && !ps.block_init) {
805 if (opt.verbose)
806 diag(0, "Line broken");
807 output_line();
808 }
809
810 buf_add_char(&code, '}');
811 ps.want_blank = true;
812 ps.in_stmt_or_decl = false;
813 ps.in_stmt_cont = false;
814
815 if (ps.decl_level > 0) { /* multi-level structure declaration */
816 ps.decl_ind = ps.di_stack[--ps.decl_level];
817 if (ps.decl_level == 0 && !ps.in_func_def_params) {
818 ps.declaration = decl_begin;
819 ps.decl_ind = ps.ind_level == 0
820 ? opt.decl_indent : opt.local_decl_indent;
821 }
822 ps.in_decl = true;
823 }
824
825 if (ps.tos == 2)
826 out.line_kind = lk_func_end;
827
828 parse(psym_rbrace);
829 }
830
831 static void
832 process_do(void)
833 {
834 ps.in_stmt_or_decl = false;
835
836 if (code.len > 0) { /* make sure this starts a line */
837 if (opt.verbose)
838 diag(0, "Line broken");
839 output_line();
840 }
841
842 ps.force_nl = true;
843 parse(psym_do);
844 }
845
846 static void
847 process_else(void)
848 {
849 ps.in_stmt_or_decl = false;
850
851 if (code.len > 0
852 && !(opt.cuddle_else && code.mem[code.len - 1] == '}')) {
853 if (opt.verbose)
854 diag(0, "Line broken");
855 output_line();
856 }
857
858 ps.force_nl = true;
859 parse(psym_else);
860 }
861
862 static void
863 process_type(void)
864 {
865 parse(psym_decl); /* let the parser worry about indentation */
866
867 if (ps.prev_token == lsym_rparen_or_rbracket && ps.tos <= 1) {
868 if (code.len > 0)
869 output_line();
870 }
871
872 if (ps.in_func_def_params && opt.indent_parameters &&
873 ps.decl_level == 0) {
874 ps.ind_level = ps.ind_level_follow = 1;
875 ps.in_stmt_cont = false;
876 }
877
878 ps.init_or_struct = /* maybe */ true;
879 ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
880 if (ps.decl_level <= 0)
881 ps.declaration = decl_begin;
882
883 int len = (int)token.len + 1;
884 int ind = ps.ind_level == 0 || ps.decl_level > 0
885 ? opt.decl_indent /* global variable or local member */
886 : opt.local_decl_indent; /* local variable */
887 ps.decl_ind = ind > 0 ? ind : len;
888 ps.tabs_to_var = opt.use_tabs && ind > 0;
889 }
890
891 static void
892 process_ident(lexer_symbol lsym)
893 {
894 if (ps.in_decl) {
895 if (lsym == lsym_funcname) {
896 ps.in_decl = false;
897 if (opt.procnames_start_line && code.len > 0)
898 output_line();
899 else if (ps.want_blank)
900 buf_add_char(&code, ' ');
901 ps.want_blank = false;
902
903 } else if (!ps.block_init && !ps.decl_indent_done &&
904 ps.line_start_nparen == 0) {
905 if (opt.decl_indent == 0
906 && code.len > 0 && code.mem[code.len - 1] == '}')
907 ps.decl_ind =
908 ind_add(0, code.st, code.len) + 1;
909 code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
910 ps.decl_indent_done = true;
911 ps.want_blank = false;
912 }
913
914 } else if (ps.spaced_expr_psym != psym_0 && ps.nparen == 0) {
915 ps.force_nl = true;
916 ps.next_unary = true;
917 ps.in_stmt_or_decl = false;
918 parse(ps.spaced_expr_psym);
919 ps.spaced_expr_psym = psym_0;
920 }
921 }
922
923 static void
924 process_period(void)
925 {
926 if (code.len > 0 && code.mem[code.len - 1] == ',')
927 buf_add_char(&code, ' ');
928 buf_add_char(&code, '.');
929 ps.want_blank = false;
930 }
931
932 static void
933 process_comma(void)
934 {
935 ps.want_blank = code.len > 0; /* only put blank after comma if comma
936 * does not start the line */
937
938 if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
939 !ps.decl_indent_done && ps.line_start_nparen == 0) {
940 /* indent leading commas and not the actual identifiers */
941 code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
942 ps.decl_indent_done = true;
943 }
944
945 buf_add_char(&code, ',');
946
947 if (ps.nparen == 0) {
948 if (ps.block_init_level <= 0)
949 ps.block_init = false;
950 int typical_varname_length = 8;
951 if (ps.break_after_comma && (opt.break_after_comma ||
952 ind_add(compute_code_indent(), code.st, code.len)
953 >= opt.max_line_length - typical_varname_length))
954 ps.force_nl = true;
955 }
956 }
957
958 /* move the whole line to the 'label' buffer */
959 static void
960 read_preprocessing_line(void)
961 {
962 enum {
963 PLAIN, STR, CHR, COMM
964 } state = PLAIN;
965
966 buf_add_char(&lab, '#');
967
968 while (ch_isblank(inp.st[0]))
969 buf_add_char(&lab, *inp.st++);
970
971 while (inp.st[0] != '\n' || (state == COMM && !had_eof)) {
972 buf_add_char(&lab, inp_next());
973 switch (lab.mem[lab.len - 1]) {
974 case '\\':
975 if (state != COMM)
976 buf_add_char(&lab, inp_next());
977 break;
978 case '/':
979 if (inp.st[0] == '*' && state == PLAIN) {
980 state = COMM;
981 buf_add_char(&lab, *inp.st++);
982 }
983 break;
984 case '"':
985 if (state == STR)
986 state = PLAIN;
987 else if (state == PLAIN)
988 state = STR;
989 break;
990 case '\'':
991 if (state == CHR)
992 state = PLAIN;
993 else if (state == PLAIN)
994 state = CHR;
995 break;
996 case '*':
997 if (inp.st[0] == '/' && state == COMM) {
998 state = PLAIN;
999 buf_add_char(&lab, *inp.st++);
1000 }
1001 break;
1002 }
1003 }
1004
1005 while (lab.len > 0 && ch_isblank(lab.mem[lab.len - 1]))
1006 lab.len--;
1007 }
1008
1009 static void
1010 process_preprocessing(void)
1011 {
1012 if (lab.len > 0 || code.len > 0 || com.len > 0)
1013 output_line();
1014
1015 read_preprocessing_line();
1016
1017 ps.is_case_label = false;
1018
1019 const char *end = lab.mem + lab.len;
1020 const char *dir = lab.st + 1;
1021 while (dir < end && ch_isblank(*dir))
1022 dir++;
1023 size_t dir_len = 0;
1024 while (dir + dir_len < end && ch_isalpha(dir[dir_len]))
1025 dir_len++;
1026
1027 if (dir_len >= 2 && memcmp(dir, "if", 2) == 0) {
1028 if ((size_t)ifdef_level < array_length(state_stack))
1029 state_stack[ifdef_level++] = ps;
1030 else
1031 diag(1, "#if stack overflow");
1032 out.line_kind = lk_if;
1033
1034 } else if (dir_len >= 2 && memcmp(dir, "el", 2) == 0) {
1035 if (ifdef_level <= 0)
1036 diag(1, dir[2] == 'i'
1037 ? "Unmatched #elif" : "Unmatched #else");
1038 else
1039 ps = state_stack[ifdef_level - 1];
1040
1041 } else if (dir_len == 5 && memcmp(dir, "endif", 5) == 0) {
1042 if (ifdef_level <= 0)
1043 diag(1, "Unmatched #endif");
1044 else
1045 ifdef_level--;
1046 out.line_kind = lk_endif;
1047 }
1048
1049 /* subsequent processing of the newline character will cause the line
1050 * to be printed */
1051 }
1052
1053 static void
1054 process_lsym(lexer_symbol lsym)
1055 {
1056 switch (lsym) {
1057
1058 case lsym_newline:
1059 process_newline();
1060 break;
1061
1062 case lsym_lparen_or_lbracket:
1063 process_lparen_or_lbracket();
1064 break;
1065
1066 case lsym_rparen_or_rbracket:
1067 process_rparen_or_rbracket();
1068 break;
1069
1070 case lsym_unary_op:
1071 process_unary_op();
1072 break;
1073
1074 case lsym_binary_op:
1075 process_binary_op();
1076 break;
1077
1078 case lsym_postfix_op:
1079 process_postfix_op();
1080 break;
1081
1082 case lsym_question:
1083 process_question();
1084 break;
1085
1086 case lsym_case_label:
1087 ps.seen_case = true;
1088 goto copy_token;
1089
1090 case lsym_colon:
1091 process_colon();
1092 break;
1093
1094 case lsym_semicolon:
1095 process_semicolon();
1096 break;
1097
1098 case lsym_lbrace:
1099 process_lbrace();
1100 break;
1101
1102 case lsym_rbrace:
1103 process_rbrace();
1104 break;
1105
1106 case lsym_switch:
1107 ps.spaced_expr_psym = psym_switch_expr;
1108 goto copy_token;
1109
1110 case lsym_for:
1111 ps.spaced_expr_psym = psym_for_exprs;
1112 goto copy_token;
1113
1114 case lsym_if:
1115 ps.spaced_expr_psym = psym_if_expr;
1116 goto copy_token;
1117
1118 case lsym_while:
1119 ps.spaced_expr_psym = psym_while_expr;
1120 goto copy_token;
1121
1122 case lsym_do:
1123 process_do();
1124 goto copy_token;
1125
1126 case lsym_else:
1127 process_else();
1128 goto copy_token;
1129
1130 case lsym_typedef:
1131 case lsym_storage_class:
1132 goto copy_token;
1133
1134 case lsym_tag:
1135 if (ps.nparen > 0)
1136 goto copy_token;
1137 /* FALLTHROUGH */
1138 case lsym_type_outside_parentheses:
1139 process_type();
1140 goto copy_token;
1141
1142 case lsym_type_in_parentheses:
1143 case lsym_offsetof:
1144 case lsym_sizeof:
1145 case lsym_word:
1146 case lsym_funcname:
1147 case lsym_return:
1148 process_ident(lsym);
1149 copy_token:
1150 if (ps.want_blank)
1151 buf_add_char(&code, ' ');
1152 buf_add_buf(&code, &token);
1153 if (lsym != lsym_funcname)
1154 ps.want_blank = true;
1155 break;
1156
1157 case lsym_period:
1158 process_period();
1159 break;
1160
1161 case lsym_comma:
1162 process_comma();
1163 break;
1164
1165 case lsym_preprocessing:
1166 process_preprocessing();
1167 break;
1168
1169 case lsym_comment:
1170 process_comment();
1171 break;
1172
1173 default:
1174 break;
1175 }
1176 }
1177
1178 static int
1179 indent(void)
1180 {
1181 debug_parser_state();
1182
1183 for (;;) { /* loop until we reach eof */
1184 lexer_symbol lsym = lexi();
1185
1186 debug_blank_line();
1187 debug_printf("line %d: %s", line_no, lsym_name[lsym]);
1188 debug_buffers();
1189 debug_blank_line();
1190
1191 if (lsym == lsym_eof)
1192 return process_eof();
1193
1194 if (lsym == lsym_if && ps.prev_token == lsym_else
1195 && opt.else_if)
1196 ps.force_nl = false;
1197
1198 if (lsym == lsym_newline || lsym == lsym_preprocessing)
1199 ps.force_nl = false;
1200 else if (lsym == lsym_comment) {
1201 /* no special processing */
1202 } else {
1203 maybe_break_line(lsym);
1204 /*
1205 * Add an extra level of indentation; turned off again
1206 * by a ';' or '}'.
1207 */
1208 ps.in_stmt_or_decl = true;
1209 if (com.len > 0)
1210 move_com_to_code(lsym);
1211 update_ps_decl_ptr(lsym);
1212 update_ps_in_enum(lsym);
1213 }
1214
1215 process_lsym(lsym);
1216
1217 debug_parser_state();
1218
1219 if (lsym != lsym_comment && lsym != lsym_newline &&
1220 lsym != lsym_preprocessing)
1221 ps.prev_token = lsym;
1222 }
1223 }
1224
1225 int
1226 main(int argc, char **argv)
1227 {
1228 init_globals();
1229 load_profiles(argc, argv);
1230 parse_command_line(argc, argv);
1231 set_initial_indentation();
1232 return indent();
1233 }
1234