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