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