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