indent.c revision 1.251 1 /* $NetBSD: indent.c,v 1.251 2023/05/11 18:13:55 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.251 2023/05/11 18:13:55 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->buf = xmalloc(size);
116 buf->l = buf->buf + size - 5 /* safety margin */;
117 buf->s = buf->buf + 1; /* allow accessing buf->e[-1] */
118 buf->e = buf->s;
119 buf->buf[0] = ' ';
120 buf->buf[1] = '\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->l - buf->s) + 400 + add_size;
133 size_t len = buf_len(buf);
134 buf->buf = xrealloc(buf->buf, new_size);
135 buf->l = buf->buf + new_size - 5;
136 buf->s = buf->buf + 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->l - 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 if (opt.verbose) {
393 printf("There were %d output lines and %d comments\n",
394 ps.stats.lines, ps.stats.comments);
395 printf("(Lines with comments)/(Lines with code): %6.3f\n",
396 (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
397 }
398
399 fflush(output);
400 exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
401 }
402
403 static void
404 maybe_break_line(lexer_symbol lsym)
405 {
406 if (!ps.force_nl)
407 return;
408 if (lsym == lsym_semicolon)
409 return;
410 if (lsym == lsym_lbrace && opt.brace_same_line)
411 return;
412
413 if (opt.verbose)
414 diag(0, "Line broken");
415 output_line();
416 ps.want_blank = false;
417 ps.force_nl = false;
418 }
419
420 static void
421 move_com_to_code(void)
422 {
423 buf_add_char(&code, ' ');
424 buf_add_buf(&code, &com);
425 buf_add_char(&code, ' ');
426 buf_terminate(&code);
427 buf_reset(&com);
428 ps.want_blank = false;
429 }
430
431 static void
432 process_form_feed(void)
433 {
434 output_line_ff();
435 ps.want_blank = false;
436 }
437
438 static void
439 process_newline(void)
440 {
441 if (ps.prev_token == lsym_comma && ps.nparen == 0 && !ps.block_init &&
442 !opt.break_after_comma && break_comma &&
443 com.s == com.e)
444 goto stay_in_line;
445
446 output_line();
447 ps.want_blank = false;
448
449 stay_in_line:
450 ++line_no;
451 }
452
453 static bool
454 want_blank_before_lparen(void)
455 {
456 if (!ps.want_blank)
457 return false;
458 if (opt.proc_calls_space)
459 return true;
460 if (ps.prev_token == lsym_rparen_or_rbracket)
461 return false;
462 if (ps.prev_token == lsym_offsetof)
463 return false;
464 if (ps.prev_token == lsym_sizeof)
465 return opt.blank_after_sizeof;
466 if (ps.prev_token == lsym_word || ps.prev_token == lsym_funcname)
467 return false;
468 return true;
469 }
470
471 static void
472 process_lparen_or_lbracket(void)
473 {
474 if (++ps.nparen == array_length(ps.paren)) {
475 diag(0, "Reached internal limit of %zu unclosed parentheses",
476 array_length(ps.paren));
477 ps.nparen--;
478 }
479
480 if (token.s[0] == '(' && ps.in_decl
481 && !ps.block_init && !ps.decl_indent_done &&
482 !ps.is_function_definition && ps.line_start_nparen == 0) {
483 /* function pointer declarations */
484 code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
485 ps.decl_indent_done = true;
486 } else if (want_blank_before_lparen())
487 *code.e++ = ' ';
488 ps.want_blank = false;
489 *code.e++ = token.s[0];
490
491 ps.paren[ps.nparen - 1].indent = (short)ind_add(0, code.s, code.e);
492 debug_println("paren_indents[%d] is now %d",
493 ps.nparen - 1, ps.paren[ps.nparen - 1].indent);
494
495 if (ps.spaced_expr && ps.nparen == 1 && opt.extra_expr_indent
496 && ps.paren[0].indent < 2 * opt.indent_size) {
497 ps.paren[0].indent = (short)(2 * opt.indent_size);
498 debug_println("paren_indents[0] is now %d", ps.paren[0].indent);
499 }
500
501 if (ps.init_or_struct && *token.s == '(' && ps.tos <= 2) {
502 /*
503 * this is a kluge to make sure that declarations will be aligned
504 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
505 */
506 parse(psym_semicolon); /* I said this was a kluge... */
507 ps.init_or_struct = false;
508 }
509
510 /* parenthesized type following sizeof or offsetof is not a cast */
511 if (ps.prev_token == lsym_offsetof || ps.prev_token == lsym_sizeof)
512 ps.paren[ps.nparen - 1].no_cast = true;
513 }
514
515 static void
516 process_rparen_or_rbracket(void)
517 {
518 if (ps.paren[ps.nparen - 1].maybe_cast &&
519 !ps.paren[ps.nparen - 1].no_cast) {
520 ps.next_unary = true;
521 ps.paren[ps.nparen - 1].maybe_cast = false;
522 ps.want_blank = opt.space_after_cast;
523 } else
524 ps.want_blank = true;
525 ps.paren[ps.nparen - 1].no_cast = false;
526
527 if (ps.nparen > 0)
528 ps.nparen--;
529 else
530 diag(0, "Extra '%c'", *token.s);
531
532 if (code.e == code.s) /* if the paren starts the line */
533 ps.line_start_nparen = ps.nparen; /* then indent it */
534
535 *code.e++ = token.s[0];
536
537 if (ps.spaced_expr && ps.nparen == 0) {
538 ps.spaced_expr = false;
539 ps.force_nl = true;
540 ps.next_unary = true;
541 ps.in_stmt_or_decl = false; /* don't use stmt continuation
542 * indentation */
543
544 parse_stmt_head(ps.hd);
545 }
546 }
547
548 static bool
549 want_blank_before_unary_op(void)
550 {
551 if (ps.want_blank)
552 return true;
553 if (token.s[0] == '+' || token.s[0] == '-')
554 return code.e > code.s && code.e[-1] == token.s[0];
555 return false;
556 }
557
558 static void
559 process_unary_op(void)
560 {
561 if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
562 !ps.is_function_definition && ps.line_start_nparen == 0) {
563 /* pointer declarations */
564 code_add_decl_indent(ps.decl_ind - (int)buf_len(&token),
565 ps.tabs_to_var);
566 ps.decl_indent_done = true;
567 } else if (want_blank_before_unary_op())
568 *code.e++ = ' ';
569
570 buf_add_buf(&code, &token);
571 ps.want_blank = false;
572 }
573
574 static void
575 process_binary_op(void)
576 {
577 if (buf_len(&code) > 0)
578 buf_add_char(&code, ' ');
579 buf_add_buf(&code, &token);
580 ps.want_blank = true;
581 }
582
583 static void
584 process_postfix_op(void)
585 {
586 *code.e++ = token.s[0];
587 *code.e++ = token.s[1];
588 ps.want_blank = true;
589 }
590
591 static void
592 process_question(void)
593 {
594 ps.quest_level++;
595 if (ps.want_blank)
596 *code.e++ = ' ';
597 *code.e++ = '?';
598 ps.want_blank = true;
599 }
600
601 static void
602 process_colon(void)
603 {
604 if (ps.quest_level > 0) { /* part of a '?:' operator */
605 ps.quest_level--;
606 if (ps.want_blank)
607 *code.e++ = ' ';
608 *code.e++ = ':';
609 ps.want_blank = true;
610 return;
611 }
612
613 if (ps.init_or_struct) { /* bit-field */
614 *code.e++ = ':';
615 ps.want_blank = false;
616 return;
617 }
618
619 buf_add_buf(&lab, &code); /* 'case' or 'default' or named label */
620 buf_add_char(&lab, ':');
621 buf_terminate(&lab);
622 buf_reset(&code);
623
624 ps.in_stmt_or_decl = false;
625 ps.is_case_label = ps.seen_case;
626 ps.force_nl = ps.seen_case;
627 ps.seen_case = false;
628 ps.want_blank = false;
629 }
630
631 static void
632 process_semicolon(void)
633 {
634 if (ps.decl_level == 0)
635 ps.init_or_struct = false;
636 ps.seen_case = false; /* these will only need resetting in an error */
637 ps.quest_level = 0;
638 if (ps.prev_token == lsym_rparen_or_rbracket)
639 ps.in_func_def_params = false;
640 ps.block_init = false;
641 ps.block_init_level = 0;
642 ps.just_saw_decl--;
643
644 if (ps.in_decl && code.s == code.e && !ps.block_init &&
645 !ps.decl_indent_done && ps.line_start_nparen == 0) {
646 /* indent stray semicolons in declarations */
647 code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
648 ps.decl_indent_done = true;
649 }
650
651 ps.in_decl = ps.decl_level > 0; /* if we were in a first level
652 * structure declaration before, we
653 * aren't anymore */
654
655 if ((!ps.spaced_expr || ps.hd != hd_for) && ps.nparen > 0) {
656
657 /*
658 * There were unbalanced parentheses in the statement. It is a bit
659 * complicated, because the semicolon might be in a for statement.
660 */
661 diag(1, "Unbalanced parentheses");
662 ps.nparen = 0;
663 if (ps.spaced_expr) {
664 ps.spaced_expr = false;
665 parse_stmt_head(ps.hd);
666 }
667 }
668 *code.e++ = ';';
669 ps.want_blank = true;
670 ps.in_stmt_or_decl = ps.nparen > 0;
671
672 if (!ps.spaced_expr) {
673 parse(psym_semicolon); /* let parser know about end of stmt */
674 ps.force_nl = true;
675 }
676 }
677
678 static void
679 process_lbrace(void)
680 {
681 ps.in_stmt_or_decl = false; /* don't indent the {} */
682
683 if (!ps.block_init)
684 ps.force_nl = true;
685 else if (ps.block_init_level <= 0)
686 ps.block_init_level = 1;
687 else
688 ps.block_init_level++;
689
690 if (code.s != code.e && !ps.block_init) {
691 if (!opt.brace_same_line) {
692 output_line();
693 ps.want_blank = false;
694 } else if (ps.in_func_def_params && !ps.init_or_struct) {
695 ps.ind_level_follow = 0;
696 if (opt.function_brace_split) { /* dump the line prior to the
697 * brace ... */
698 output_line();
699 ps.want_blank = false;
700 } else /* add a space between the decl and brace */
701 ps.want_blank = true;
702 }
703 }
704
705 if (ps.nparen > 0) {
706 diag(1, "Unbalanced parentheses");
707 ps.nparen = 0;
708 if (ps.spaced_expr) {
709 ps.spaced_expr = false;
710 parse_stmt_head(ps.hd);
711 ps.ind_level = ps.ind_level_follow;
712 }
713 }
714
715 if (code.s == code.e)
716 ps.in_stmt_cont = false; /* don't indent the '{' itself */
717 if (ps.in_decl && ps.init_or_struct) {
718 ps.di_stack[ps.decl_level] = ps.decl_ind;
719 if (++ps.decl_level == (int)array_length(ps.di_stack)) {
720 diag(0, "Reached internal limit of %d struct levels",
721 (int)array_length(ps.di_stack));
722 ps.decl_level--;
723 }
724 } else {
725 ps.decl_on_line = false; /* we can't be in the middle of a
726 * declaration, so don't do special
727 * indentation of comments */
728 ps.in_func_def_params = false;
729 ps.in_decl = false;
730 }
731
732 ps.decl_ind = 0;
733 parse(psym_lbrace);
734 if (ps.want_blank)
735 *code.e++ = ' ';
736 ps.want_blank = false;
737 *code.e++ = '{';
738 ps.just_saw_decl = 0;
739 }
740
741 static void
742 process_rbrace(void)
743 {
744 if (ps.s_sym[ps.tos] == psym_decl && !ps.block_init) {
745 /* semicolons can be omitted in declarations */
746 parse(psym_semicolon);
747 }
748
749 if (ps.nparen > 0) { /* check for unclosed if, for, else. */
750 diag(1, "Unbalanced parentheses");
751 ps.nparen = 0;
752 ps.spaced_expr = false;
753 }
754
755 ps.just_saw_decl = 0;
756 ps.block_init_level--;
757
758 if (code.s != code.e && !ps.block_init) { /* '}' must be first on line */
759 if (opt.verbose)
760 diag(0, "Line broken");
761 output_line();
762 }
763
764 *code.e++ = '}';
765 ps.want_blank = true;
766 ps.in_stmt_or_decl = false;
767 ps.in_stmt_cont = false;
768
769 if (ps.decl_level > 0) { /* multi-level structure declaration */
770 ps.decl_ind = ps.di_stack[--ps.decl_level];
771 if (ps.decl_level == 0 && !ps.in_func_def_params) {
772 ps.just_saw_decl = 2;
773 ps.decl_ind = ps.ind_level == 0
774 ? opt.decl_indent : opt.local_decl_indent;
775 }
776 ps.in_decl = true;
777 }
778
779 parse(psym_rbrace);
780 }
781
782 static void
783 process_do(void)
784 {
785 ps.in_stmt_or_decl = false;
786
787 if (code.e != code.s) { /* make sure this starts a line */
788 if (opt.verbose)
789 diag(0, "Line broken");
790 output_line();
791 ps.want_blank = false;
792 }
793
794 ps.force_nl = true;
795 parse(psym_do);
796 }
797
798 static void
799 process_else(void)
800 {
801 ps.in_stmt_or_decl = false;
802
803 if (code.e > code.s && !(opt.cuddle_else && code.e[-1] == '}')) {
804 if (opt.verbose)
805 diag(0, "Line broken");
806 output_line(); /* make sure this starts a line */
807 ps.want_blank = false;
808 }
809
810 ps.force_nl = true;
811 parse(psym_else);
812 }
813
814 static void
815 process_type(void)
816 {
817 parse(psym_decl); /* let the parser worry about indentation */
818
819 if (ps.prev_token == lsym_rparen_or_rbracket && ps.tos <= 1) {
820 if (code.s != code.e) {
821 output_line();
822 ps.want_blank = false;
823 }
824 }
825
826 if (ps.in_func_def_params && opt.indent_parameters &&
827 ps.decl_level == 0) {
828 ps.ind_level = ps.ind_level_follow = 1;
829 ps.in_stmt_cont = false;
830 }
831
832 ps.init_or_struct = /* maybe */ true;
833 ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
834 if (ps.decl_level <= 0)
835 ps.just_saw_decl = 2;
836
837 int len = (int)buf_len(&token) + 1;
838 int ind = ps.ind_level == 0 || ps.decl_level > 0
839 ? opt.decl_indent /* global variable or local member */
840 : opt.local_decl_indent; /* local variable */
841 ps.decl_ind = ind > 0 ? ind : len;
842 ps.tabs_to_var = opt.use_tabs && ind > 0;
843 }
844
845 static void
846 process_ident(lexer_symbol lsym)
847 {
848 if (ps.in_decl) {
849 if (lsym == lsym_funcname) {
850 ps.in_decl = false;
851 if (opt.procnames_start_line && code.s != code.e) {
852 *code.e = '\0';
853 output_line();
854 } else if (ps.want_blank) {
855 *code.e++ = ' ';
856 }
857 ps.want_blank = false;
858
859 } else if (!ps.block_init && !ps.decl_indent_done &&
860 ps.line_start_nparen == 0) {
861 code_add_decl_indent(ps.decl_ind, ps.tabs_to_var);
862 ps.decl_indent_done = true;
863 ps.want_blank = false;
864 }
865
866 } else if (ps.spaced_expr && ps.nparen == 0) {
867 ps.spaced_expr = false;
868 ps.force_nl = true;
869 ps.next_unary = true;
870 ps.in_stmt_or_decl = false;
871 parse_stmt_head(ps.hd);
872 }
873 }
874
875 static void
876 copy_token(void)
877 {
878 if (ps.want_blank)
879 buf_add_char(&code, ' ');
880 buf_add_buf(&code, &token);
881 }
882
883 static void
884 process_period(void)
885 {
886 if (code.e > code.s && code.e[-1] == ',')
887 *code.e++ = ' ';
888 *code.e++ = '.';
889 ps.want_blank = false;
890 }
891
892 static void
893 process_comma(void)
894 {
895 ps.want_blank = code.s != code.e; /* only put blank after comma if comma
896 * does not start the line */
897
898 if (ps.in_decl && !ps.is_function_definition && !ps.block_init &&
899 !ps.decl_indent_done && ps.line_start_nparen == 0) {
900 /* indent leading commas and not the actual identifiers */
901 code_add_decl_indent(ps.decl_ind - 1, ps.tabs_to_var);
902 ps.decl_indent_done = true;
903 }
904
905 *code.e++ = ',';
906
907 if (ps.nparen == 0) {
908 if (ps.block_init_level <= 0)
909 ps.block_init = false;
910 int varname_len = 8; /* rough estimate for the length of a typical
911 * variable name */
912 if (break_comma && (opt.break_after_comma ||
913 ind_add(compute_code_indent(), code.s, code.e)
914 >= opt.max_line_length - varname_len))
915 ps.force_nl = true;
916 }
917 }
918
919 /* move the whole line to the 'label' buffer */
920 static void
921 read_preprocessing_line(void)
922 {
923 enum {
924 PLAIN, STR, CHR, COMM
925 } state;
926
927 buf_add_char(&lab, '#');
928
929 state = PLAIN;
930 int com_start = 0, com_end = 0;
931
932 while (ch_isblank(inp_peek()))
933 inp_skip();
934
935 while (inp_peek() != '\n' || (state == COMM && !had_eof)) {
936 buf_reserve(&lab, 2);
937 *lab.e++ = inp_next();
938 switch (lab.e[-1]) {
939 case '\\':
940 if (state != COMM)
941 *lab.e++ = inp_next();
942 break;
943 case '/':
944 if (inp_peek() == '*' && state == PLAIN) {
945 state = COMM;
946 *lab.e++ = inp_next();
947 com_start = (int)buf_len(&lab) - 2;
948 }
949 break;
950 case '"':
951 if (state == STR)
952 state = PLAIN;
953 else if (state == PLAIN)
954 state = STR;
955 break;
956 case '\'':
957 if (state == CHR)
958 state = PLAIN;
959 else if (state == PLAIN)
960 state = CHR;
961 break;
962 case '*':
963 if (inp_peek() == '/' && state == COMM) {
964 state = PLAIN;
965 *lab.e++ = inp_next();
966 com_end = (int)buf_len(&lab);
967 }
968 break;
969 }
970 }
971
972 while (lab.e > lab.s && ch_isblank(lab.e[-1]))
973 lab.e--;
974 if (lab.e - lab.s == com_end && !inp_comment_seen()) {
975 /* comment on preprocessor line */
976 inp_comment_init_preproc();
977 inp_comment_add_range(lab.s + com_start, lab.s + com_end);
978 lab.e = lab.s + com_start;
979 while (lab.e > lab.s && ch_isblank(lab.e[-1]))
980 lab.e--;
981 inp_comment_add_char(' '); /* add trailing blank, just in case */
982 inp_from_comment();
983 }
984 buf_terminate(&lab);
985 }
986
987 static void
988 process_preprocessing(void)
989 {
990 if (com.s != com.e || lab.s != lab.e || code.s != code.e)
991 output_line();
992
993 read_preprocessing_line();
994
995 ps.is_case_label = false;
996
997 if (strncmp(lab.s, "#if", 3) == 0) { /* 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 (strncmp(lab.s, "#el", 3) == 0) { /* else, elif */
1004 if (ifdef_level <= 0)
1005 diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1006 else
1007 ps = state_stack[ifdef_level - 1];
1008
1009 } else if (strncmp(lab.s, "#endif", 6) == 0) {
1010 if (ifdef_level <= 0)
1011 diag(1, "Unmatched #endif");
1012 else
1013 ifdef_level--;
1014
1015 } else {
1016 if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
1017 strncmp(lab.s + 1, "error", 5) != 0 &&
1018 strncmp(lab.s + 1, "line", 4) != 0 &&
1019 strncmp(lab.s + 1, "undef", 5) != 0 &&
1020 strncmp(lab.s + 1, "define", 6) != 0 &&
1021 strncmp(lab.s + 1, "include", 7) != 0) {
1022 diag(1, "Unrecognized cpp directive");
1023 return;
1024 }
1025 }
1026
1027 /*
1028 * subsequent processing of the newline character will cause the line to
1029 * be printed
1030 */
1031 }
1032
1033 __dead static void
1034 main_loop(void)
1035 {
1036
1037 ps.di_stack[ps.decl_level = 0] = 0;
1038
1039 for (;;) { /* loop until we reach eof */
1040 lexer_symbol lsym = lexi();
1041
1042 if (lsym == lsym_if && ps.prev_token == lsym_else && opt.else_if)
1043 ps.force_nl = false;
1044
1045 if (lsym == lsym_eof) {
1046 process_eof();
1047 /* NOTREACHED */
1048 }
1049
1050 if (lsym == lsym_newline || lsym == lsym_form_feed ||
1051 lsym == lsym_preprocessing)
1052 ps.force_nl = false;
1053 else if (lsym != lsym_comment) {
1054 maybe_break_line(lsym);
1055 ps.in_stmt_or_decl = true; /* add an extra level of indentation;
1056 * turned off again by a ';' or '}' */
1057 if (com.s != com.e)
1058 move_com_to_code();
1059 }
1060
1061 buf_reserve(&code, 3); /* space for 2 characters plus '\0' */
1062
1063 switch (lsym) {
1064
1065 case lsym_form_feed:
1066 process_form_feed();
1067 break;
1068
1069 case lsym_newline:
1070 process_newline();
1071 break;
1072
1073 case lsym_lparen_or_lbracket:
1074 process_lparen_or_lbracket();
1075 break;
1076
1077 case lsym_rparen_or_rbracket:
1078 process_rparen_or_rbracket();
1079 break;
1080
1081 case lsym_unary_op:
1082 process_unary_op();
1083 break;
1084
1085 case lsym_binary_op:
1086 process_binary_op();
1087 break;
1088
1089 case lsym_postfix_op:
1090 process_postfix_op();
1091 break;
1092
1093 case lsym_question:
1094 process_question();
1095 break;
1096
1097 case lsym_case_label:
1098 ps.seen_case = true;
1099 goto copy_token;
1100
1101 case lsym_colon:
1102 process_colon();
1103 break;
1104
1105 case lsym_semicolon:
1106 process_semicolon();
1107 break;
1108
1109 case lsym_lbrace:
1110 process_lbrace();
1111 break;
1112
1113 case lsym_rbrace:
1114 process_rbrace();
1115 break;
1116
1117 case lsym_switch:
1118 ps.spaced_expr = true;
1119 ps.hd = hd_switch;
1120 goto copy_token;
1121
1122 case lsym_for:
1123 ps.spaced_expr = true;
1124 ps.hd = hd_for;
1125 goto copy_token;
1126
1127 case lsym_if:
1128 ps.spaced_expr = true;
1129 ps.hd = hd_if;
1130 goto copy_token;
1131
1132 case lsym_while:
1133 ps.spaced_expr = true;
1134 ps.hd = hd_while;
1135 goto copy_token;
1136
1137 case lsym_do:
1138 process_do();
1139 goto copy_token;
1140
1141 case lsym_else:
1142 process_else();
1143 goto copy_token;
1144
1145 case lsym_typedef:
1146 case lsym_storage_class:
1147 goto copy_token;
1148
1149 case lsym_tag:
1150 if (ps.nparen > 0)
1151 goto copy_token;
1152 /* FALLTHROUGH */
1153 case lsym_type_outside_parentheses:
1154 process_type();
1155 goto copy_token;
1156
1157 case lsym_type_in_parentheses:
1158 case lsym_offsetof:
1159 case lsym_sizeof:
1160 case lsym_word:
1161 case lsym_funcname:
1162 case lsym_return:
1163 process_ident(lsym);
1164 copy_token:
1165 copy_token();
1166 if (lsym != lsym_funcname)
1167 ps.want_blank = true;
1168 break;
1169
1170 case lsym_period:
1171 process_period();
1172 break;
1173
1174 case lsym_comma:
1175 process_comma();
1176 break;
1177
1178 case lsym_preprocessing:
1179 process_preprocessing();
1180 break;
1181
1182 case lsym_comment:
1183 process_comment();
1184 break;
1185
1186 default:
1187 break;
1188 }
1189
1190 *code.e = '\0';
1191 if (lsym != lsym_comment && lsym != lsym_newline &&
1192 lsym != lsym_preprocessing)
1193 ps.prev_token = lsym;
1194 }
1195 }
1196
1197 int
1198 main(int argc, char **argv)
1199 {
1200 main_init_globals();
1201 main_load_profiles(argc, argv);
1202 main_parse_command_line(argc, argv);
1203 main_prepare_parsing();
1204 main_loop();
1205 }
1206
1207 #ifdef debug
1208 void
1209 debug_printf(const char *fmt, ...)
1210 {
1211 FILE *f = output == stdout ? stderr : stdout;
1212 va_list ap;
1213
1214 va_start(ap, fmt);
1215 vfprintf(f, fmt, ap);
1216 va_end(ap);
1217 }
1218
1219 void
1220 debug_println(const char *fmt, ...)
1221 {
1222 FILE *f = output == stdout ? stderr : stdout;
1223 va_list ap;
1224
1225 va_start(ap, fmt);
1226 vfprintf(f, fmt, ap);
1227 va_end(ap);
1228 fprintf(f, "\n");
1229 }
1230
1231 void
1232 debug_vis_range(const char *prefix, const char *s, const char *e,
1233 const char *suffix)
1234 {
1235 debug_printf("%s", prefix);
1236 for (const char *p = s; p < e; p++) {
1237 if (*p == '\\' || *p == '"')
1238 debug_printf("\\%c", *p);
1239 else if (isprint((unsigned char)*p))
1240 debug_printf("%c", *p);
1241 else if (*p == '\n')
1242 debug_printf("\\n");
1243 else if (*p == '\t')
1244 debug_printf("\\t");
1245 else
1246 debug_printf("\\x%02x", (unsigned char)*p);
1247 }
1248 debug_printf("%s", suffix);
1249 }
1250 #endif
1251
1252 static void *
1253 nonnull(void *p)
1254 {
1255 if (p == NULL)
1256 err(EXIT_FAILURE, NULL);
1257 return p;
1258 }
1259
1260 void *
1261 xmalloc(size_t size)
1262 {
1263 return nonnull(malloc(size));
1264 }
1265
1266 void *
1267 xrealloc(void *p, size_t new_size)
1268 {
1269 return nonnull(realloc(p, new_size));
1270 }
1271
1272 char *
1273 xstrdup(const char *s)
1274 {
1275 return nonnull(strdup(s));
1276 }
1277