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