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