indent.c revision 1.97 1 /* $NetBSD: indent.c,v 1.97 2021/10/03 18:41:36 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.97 2021/10/03 18:41:36 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 #if HAVE_CAPSICUM
53 #include <sys/capsicum.h>
54 #include <capsicum_helpers.h>
55 #endif
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64
65 #include "indent.h"
66
67 struct options opt = {
68 .btype_2 = true,
69 .comment_delimiter_on_blankline = true,
70 .cuddle_else = true,
71 .comment_column = 33,
72 .decl_indent = 16,
73 .else_if = true,
74 .function_brace_split = true,
75 .format_col1_comments = true,
76 .format_block_comments = true,
77 .indent_parameters = true,
78 .indent_size = 8,
79 .local_decl_indent = -1,
80 .lineup_to_parens = true,
81 .procnames_start_line = true,
82 .star_comment_cont = true,
83 .tabsize = 8,
84 .max_line_length = 78,
85 .use_tabs = true,
86 };
87
88 struct parser_state ps;
89
90 struct buffer lab;
91 struct buffer code;
92 struct buffer com;
93 struct buffer token;
94
95 char *in_buffer;
96 char *in_buffer_limit;
97 char *buf_ptr;
98 char *buf_end;
99
100 char sc_buf[sc_size];
101 char *save_com;
102 static char *sc_end; /* pointer into save_com buffer */
103
104 char *bp_save;
105 char *be_save;
106
107 bool found_err;
108 int n_real_blanklines;
109 bool prefix_blankline_requested;
110 bool postfix_blankline_requested;
111 bool break_comma;
112 float case_ind;
113 bool had_eof;
114 int line_no;
115 bool inhibit_formatting;
116
117 static int ifdef_level;
118 static struct parser_state state_stack[5];
119
120 FILE *input;
121 FILE *output;
122
123 static void bakcopy(void);
124 static void indent_declaration(int, bool);
125
126 static const char *in_name = "Standard Input";
127 static const char *out_name = "Standard Output";
128 static const char *backup_suffix = ".BAK";
129 static char bakfile[MAXPATHLEN] = "";
130
131 static void
132 check_size_code(size_t desired_size)
133 {
134 if (code.e + desired_size >= code.l)
135 buf_expand(&code, desired_size);
136 }
137
138 static void
139 check_size_label(size_t desired_size)
140 {
141 if (lab.e + desired_size >= lab.l)
142 buf_expand(&lab, desired_size);
143 }
144
145 #if HAVE_CAPSICUM
146 static void
147 init_capsicum(void)
148 {
149 cap_rights_t rights;
150
151 /* Restrict input/output descriptors and enter Capsicum sandbox. */
152 cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
153 if (caph_rights_limit(fileno(output), &rights) < 0)
154 err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
155 cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
156 if (caph_rights_limit(fileno(input), &rights) < 0)
157 err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
158 if (caph_enter() < 0)
159 err(EXIT_FAILURE, "unable to enter capability mode");
160 }
161 #endif
162
163 static void
164 search_brace_newline(bool *inout_force_nl)
165 {
166 if (sc_end == NULL) {
167 save_com = sc_buf;
168 save_com[0] = save_com[1] = ' ';
169 sc_end = &save_com[2];
170 }
171 *sc_end++ = '\n';
172
173 /*
174 * We may have inherited a force_nl == true from the previous token (like
175 * a semicolon). But once we know that a newline has been scanned in this
176 * loop, force_nl should be false.
177 *
178 * However, the force_nl == true must be preserved if newline is never
179 * scanned in this loop, so this assignment cannot be done earlier.
180 */
181 *inout_force_nl = false;
182 }
183
184 static void
185 search_brace_comment(bool *inout_comment_buffered)
186 {
187 if (sc_end == NULL) {
188 /*
189 * Copy everything from the start of the line, because
190 * process_comment() will use that to calculate original indentation
191 * of a boxed comment.
192 */
193 memcpy(sc_buf, in_buffer, (size_t)(buf_ptr - in_buffer) - 4);
194 save_com = sc_buf + (buf_ptr - in_buffer - 4);
195 save_com[0] = save_com[1] = ' ';
196 sc_end = &save_com[2];
197 }
198 *inout_comment_buffered = true;
199 *sc_end++ = '/'; /* copy in start of comment */
200 *sc_end++ = '*';
201 for (;;) { /* loop until the end of the comment */
202 *sc_end = *buf_ptr++;
203 if (buf_ptr >= buf_end)
204 fill_buffer();
205 if (*sc_end++ == '*' && *buf_ptr == '/')
206 break; /* we are at end of comment */
207 if (sc_end >= &save_com[sc_size]) { /* check for temp buffer
208 * overflow */
209 diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
210 fflush(output);
211 exit(1);
212 }
213 }
214 *sc_end++ = '/'; /* add ending slash */
215 if (++buf_ptr >= buf_end) /* get past / in buffer */
216 fill_buffer();
217 }
218
219 static bool
220 search_brace_lbrace(void)
221 {
222 /*
223 * Put KNF-style lbraces before the buffered up tokens and jump out of
224 * this loop in order to avoid copying the token again under the default
225 * case of the switch below.
226 */
227 if (sc_end != NULL && opt.btype_2) {
228 save_com[0] = '{';
229 /*
230 * Originally the lbrace may have been alone on its own line, but it
231 * will be moved into "the else's line", so if there was a newline
232 * resulting from the "{" before, it must be scanned now and ignored.
233 */
234 while (isspace((unsigned char)*buf_ptr)) {
235 if (++buf_ptr >= buf_end)
236 fill_buffer();
237 if (*buf_ptr == '\n')
238 break;
239 }
240 return true;
241 }
242 return false;
243 }
244
245 static bool
246 search_brace_other(token_type ttype, bool *inout_force_nl,
247 bool comment_buffered, bool last_else)
248 {
249 bool remove_newlines;
250
251 remove_newlines =
252 /* "} else" */
253 (ttype == keyword_do_else && *token.s == 'e' &&
254 code.e != code.s && code.e[-1] == '}')
255 /* "else if" */
256 || (ttype == keyword_for_if_while &&
257 *token.s == 'i' && last_else && opt.else_if);
258 if (remove_newlines)
259 *inout_force_nl = false;
260 if (sc_end == NULL) { /* ignore buffering if comment wasn't saved
261 * up */
262 ps.search_brace = false;
263 return false;
264 }
265 while (sc_end > save_com && isblank((unsigned char)sc_end[-1])) {
266 sc_end--;
267 }
268 if (opt.swallow_optional_blanklines ||
269 (!comment_buffered && remove_newlines)) {
270 *inout_force_nl = !remove_newlines;
271 while (sc_end > save_com && sc_end[-1] == '\n') {
272 sc_end--;
273 }
274 }
275 if (*inout_force_nl) { /* if we should insert a nl here, put it into
276 * the buffer */
277 *inout_force_nl = false;
278 --line_no; /* this will be re-increased when the newline
279 * is read from the buffer */
280 *sc_end++ = '\n';
281 *sc_end++ = ' ';
282 if (opt.verbose) /* print error msg if the line was not already
283 * broken */
284 diag(0, "Line broken");
285 }
286 for (const char *t_ptr = token.s; *t_ptr != '\0'; ++t_ptr)
287 *sc_end++ = *t_ptr;
288 return true;
289 }
290
291 static void
292 switch_buffer(void)
293 {
294 ps.search_brace = false; /* stop looking for start of stmt */
295 bp_save = buf_ptr; /* save current input buffer */
296 be_save = buf_end;
297 buf_ptr = save_com; /* fix so that subsequent calls to lexi will
298 * take tokens out of save_com */
299 *sc_end++ = ' '; /* add trailing blank, just in case */
300 buf_end = sc_end;
301 sc_end = NULL;
302 debug_println("switched buf_ptr to save_com");
303 }
304
305 static void
306 search_brace_lookahead(token_type *inout_ttype)
307 {
308 /*
309 * We must make this check, just in case there was an unexpected EOF.
310 */
311 if (*inout_ttype != end_of_file) {
312 /*
313 * The only intended purpose of calling lexi() below is to categorize
314 * the next token in order to decide whether to continue buffering
315 * forthcoming tokens. Once the buffering is over, lexi() will be
316 * called again elsewhere on all of the tokens - this time for normal
317 * processing.
318 *
319 * Calling it for this purpose is a bug, because lexi() also changes
320 * the parser state and discards leading whitespace, which is needed
321 * mostly for comment-related considerations.
322 *
323 * Work around the former problem by giving lexi() a copy of the
324 * current parser state and discard it if the call turned out to be
325 * just a look ahead.
326 *
327 * Work around the latter problem by copying all whitespace characters
328 * into the buffer so that the later lexi() call will read them.
329 */
330 if (sc_end != NULL) {
331 while (*buf_ptr == ' ' || *buf_ptr == '\t') {
332 *sc_end++ = *buf_ptr++;
333 if (sc_end >= &save_com[sc_size]) {
334 errx(1, "input too long");
335 }
336 }
337 if (buf_ptr >= buf_end) {
338 fill_buffer();
339 }
340 }
341
342 struct parser_state transient_state;
343 transient_state = ps;
344 *inout_ttype = lexi(&transient_state); /* read another token */
345 if (*inout_ttype != newline && *inout_ttype != form_feed &&
346 *inout_ttype != comment && !transient_state.search_brace) {
347 ps = transient_state;
348 }
349 }
350 }
351
352 static void
353 search_brace(token_type *inout_ttype, bool *inout_force_nl,
354 bool *inout_comment_buffered, bool *inout_last_else)
355 {
356 while (ps.search_brace) {
357 switch (*inout_ttype) {
358 case newline:
359 search_brace_newline(inout_force_nl);
360 break;
361 case form_feed:
362 break;
363 case comment:
364 search_brace_comment(inout_comment_buffered);
365 break;
366 case lbrace:
367 if (search_brace_lbrace())
368 goto sw_buffer;
369 /* FALLTHROUGH */
370 default: /* it is the start of a normal statement */
371 if (!search_brace_other(*inout_ttype, inout_force_nl,
372 *inout_comment_buffered, *inout_last_else))
373 return;
374 sw_buffer:
375 switch_buffer();
376 }
377 search_brace_lookahead(inout_ttype);
378 }
379
380 *inout_last_else = false;
381 }
382
383 static void
384 buf_init(struct buffer *buf)
385 {
386 buf->buf = xmalloc(bufsize);
387 buf->buf[0] = ' '; /* allow accessing buf->e[-1] */
388 buf->buf[1] = '\0';
389 buf->s = buf->buf + 1;
390 buf->e = buf->s;
391 buf->l = buf->buf + bufsize - 5; /* safety margin, though unreliable */
392 }
393
394 void
395 buf_expand(struct buffer *buf, size_t desired_size)
396 {
397 size_t nsize = buf->l - buf->s + 400 + desired_size;
398 size_t code_len = buf->e - buf->s;
399 buf->buf = xrealloc(buf->buf, nsize);
400 buf->e = buf->buf + code_len + 1;
401 buf->l = buf->buf + nsize - 5;
402 buf->s = buf->buf + 1;
403 }
404
405 static void
406 main_init_globals(void)
407 {
408 found_err = false;
409
410 ps.p_stack[0] = stmt; /* this is the parser's stack */
411 ps.last_nl = true; /* this is true if the last thing scanned was
412 * a newline */
413 ps.last_token = semicolon;
414 buf_init(&com);
415 buf_init(&lab);
416 buf_init(&code);
417 buf_init(&token);
418 opt.else_if = true; /* XXX: redundant? */
419
420 in_buffer = xmalloc(10);
421 in_buffer_limit = in_buffer + 8;
422 buf_ptr = buf_end = in_buffer;
423 line_no = 1;
424 had_eof = ps.in_decl = ps.decl_on_line = (break_comma = false);
425 ps.in_or_st = false;
426 ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
427
428 ps.pcase = false;
429 sc_end = NULL;
430 bp_save = NULL;
431 be_save = NULL;
432
433 output = NULL;
434
435 const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
436 if (suffix != NULL)
437 backup_suffix = suffix;
438 }
439
440 static void
441 main_parse_command_line(int argc, char **argv)
442 {
443 int i;
444 const char *profile_name = NULL;
445
446 for (i = 1; i < argc; ++i)
447 if (strcmp(argv[i], "-npro") == 0)
448 break;
449 else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0')
450 profile_name = argv[i] + 2; /* non-empty -P (set profile) */
451 if (i >= argc)
452 set_profile(profile_name);
453
454 for (i = 1; i < argc; ++i) {
455 if (argv[i][0] == '-') {
456 set_option(argv[i]);
457
458 } else if (input == NULL) {
459 in_name = argv[i];
460 input = fopen(in_name, "r");
461 if (input == NULL)
462 err(1, "%s", in_name);
463
464 } else if (output == NULL) {
465 out_name = argv[i];
466 if (strcmp(in_name, out_name) == 0)
467 errx(1, "input and output files must be different");
468 output = fopen(out_name, "w");
469 if (output == NULL)
470 err(1, "%s", out_name);
471
472 } else
473 errx(1, "unknown parameter: %s", argv[i]);
474 }
475
476 if (input == NULL)
477 input = stdin;
478 if (output == NULL) {
479 if (input == stdin)
480 output = stdout;
481 else {
482 out_name = in_name;
483 bakcopy();
484 }
485 }
486
487 if (opt.comment_column <= 1)
488 opt.comment_column = 2; /* don't put normal comments before column 2 */
489 if (opt.block_comment_max_line_length <= 0)
490 opt.block_comment_max_line_length = opt.max_line_length;
491 if (opt.local_decl_indent < 0) /* if not specified by user, set this */
492 opt.local_decl_indent = opt.decl_indent;
493 if (opt.decl_comment_column <= 0) /* if not specified by user, set this */
494 opt.decl_comment_column = opt.ljust_decl
495 ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
496 : opt.comment_column;
497 if (opt.continuation_indent == 0)
498 opt.continuation_indent = opt.indent_size;
499 }
500
501 static void
502 main_prepare_parsing(void)
503 {
504 fill_buffer(); /* get first batch of stuff into input buffer */
505
506 parse(semicolon);
507
508 char *p = buf_ptr;
509 int col = 1;
510
511 for (;;) {
512 if (*p == ' ')
513 col++;
514 else if (*p == '\t')
515 col = opt.tabsize * (1 + (col - 1) / opt.tabsize) + 1;
516 else
517 break;
518 p++;
519 }
520 if (col > opt.indent_size)
521 ps.ind_level = ps.ind_level_follow = col / opt.indent_size;
522 }
523
524 static void __attribute__((__noreturn__))
525 process_end_of_file(void)
526 {
527 if (lab.s != lab.e || code.s != code.e || com.s != com.e)
528 dump_line();
529
530 if (ps.tos > 1) /* check for balanced braces */
531 diag(1, "Stuff missing from end of file");
532
533 if (opt.verbose) {
534 printf("There were %d output lines and %d comments\n",
535 ps.stats.lines, ps.stats.comments);
536 printf("(Lines with comments)/(Lines with code): %6.3f\n",
537 (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
538 }
539
540 fflush(output);
541 exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
542 }
543
544 static void
545 process_comment_in_code(token_type ttype, bool *inout_force_nl)
546 {
547 if (*inout_force_nl &&
548 ttype != semicolon &&
549 (ttype != lbrace || !opt.btype_2)) {
550
551 /* we should force a broken line here */
552 if (opt.verbose)
553 diag(0, "Line broken");
554 dump_line();
555 ps.want_blank = false; /* dont insert blank at line start */
556 *inout_force_nl = false;
557 }
558
559 ps.in_stmt = true; /* turn on flag which causes an extra level of
560 * indentation. this is turned off by a ';' or
561 * '}' */
562 if (com.s != com.e) { /* the turkey has embedded a comment in a
563 * line. fix it */
564 size_t len = com.e - com.s;
565
566 check_size_code(len + 3);
567 *code.e++ = ' ';
568 memcpy(code.e, com.s, len);
569 code.e += len;
570 *code.e++ = ' ';
571 *code.e = '\0';
572 ps.want_blank = false;
573 com.e = com.s;
574 }
575 }
576
577 static void
578 process_form_feed(void)
579 {
580 ps.use_ff = true; /* a form feed is treated much like a newline */
581 dump_line();
582 ps.want_blank = false;
583 }
584
585 static void
586 process_newline(void)
587 {
588 if (ps.last_token != comma || ps.p_l_follow > 0 || opt.break_after_comma
589 || ps.block_init || !break_comma || com.s != com.e) {
590 dump_line();
591 ps.want_blank = false;
592 }
593 ++line_no; /* keep track of input line number */
594 }
595
596 static bool
597 want_blank_before_lparen(void)
598 {
599 if (!ps.want_blank)
600 return false;
601 if (ps.last_token == rparen)
602 return false;
603 if (ps.last_token != ident && ps.last_token != funcname)
604 return true;
605 if (opt.proc_calls_space)
606 return true;
607 if (ps.keyword == kw_sizeof)
608 return opt.blank_after_sizeof;
609 return ps.keyword != kw_0 && ps.keyword != kw_offsetof;
610 }
611
612 static void
613 process_lparen_or_lbracket(int dec_ind, bool tabs_to_var, bool sp_sw)
614 {
615 /* count parens to make Healy happy */
616 if (++ps.p_l_follow == nitems(ps.paren_indents)) {
617 diag(0, "Reached internal limit of %zu unclosed parens",
618 nitems(ps.paren_indents));
619 ps.p_l_follow--;
620 }
621 if (token.s[0] == '(' && ps.in_decl
622 && !ps.block_init && !ps.dumped_decl_indent &&
623 ps.procname[0] == '\0' && ps.paren_level == 0) {
624 /* function pointer declarations */
625 indent_declaration(dec_ind, tabs_to_var);
626 ps.dumped_decl_indent = true;
627 } else if (want_blank_before_lparen())
628 *code.e++ = ' ';
629 ps.want_blank = false;
630 *code.e++ = token.s[0];
631
632 ps.paren_indents[ps.p_l_follow - 1] =
633 indentation_after_range(0, code.s, code.e);
634 debug_println("paren_indent[%d] is now %d",
635 ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
636
637 if (sp_sw && ps.p_l_follow == 1 && opt.extra_expression_indent
638 && ps.paren_indents[0] < 2 * opt.indent_size) {
639 ps.paren_indents[0] = 2 * opt.indent_size;
640 debug_println("paren_indent[0] is now %d", ps.paren_indents[0]);
641 }
642 if (ps.in_or_st && *token.s == '(' && ps.tos <= 2) {
643 /*
644 * this is a kluge to make sure that declarations will be aligned
645 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
646 */
647 parse(semicolon); /* I said this was a kluge... */
648 ps.in_or_st = false; /* turn off flag for structure decl or
649 * initialization */
650 }
651 /* parenthesized type following sizeof or offsetof is not a cast */
652 if (ps.keyword == kw_offsetof || ps.keyword == kw_sizeof)
653 ps.not_cast_mask |= 1 << ps.p_l_follow;
654 }
655
656 static void
657 process_rparen_or_rbracket(bool *inout_sp_sw, bool *inout_force_nl,
658 token_type hd_type)
659 {
660 if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
661 ps.last_u_d = true;
662 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
663 ps.want_blank = opt.space_after_cast;
664 } else
665 ps.want_blank = true;
666 ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
667
668 if (--ps.p_l_follow < 0) {
669 ps.p_l_follow = 0;
670 diag(0, "Extra %c", *token.s);
671 }
672
673 if (code.e == code.s) /* if the paren starts the line */
674 ps.paren_level = ps.p_l_follow; /* then indent it */
675
676 *code.e++ = token.s[0];
677
678 if (*inout_sp_sw && (ps.p_l_follow == 0)) { /* check for end of if (...),
679 * or some such */
680 *inout_sp_sw = false;
681 *inout_force_nl = true; /* must force newline after if */
682 ps.last_u_d = true; /* inform lexi that a following operator is
683 * unary */
684 ps.in_stmt = false; /* dont use stmt continuation indentation */
685
686 parse(hd_type); /* let parser worry about if, or whatever */
687 }
688 ps.search_brace = opt.btype_2; /* this should ensure that constructs
689 * such as main(){...} and int[]{...}
690 * have their braces put in the right
691 * place */
692 }
693
694 static void
695 process_unary_op(int dec_ind, bool tabs_to_var)
696 {
697 if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
698 ps.procname[0] == '\0' && ps.paren_level == 0) {
699 /* pointer declarations */
700 indent_declaration(dec_ind - (int)strlen(token.s), tabs_to_var);
701 ps.dumped_decl_indent = true;
702 } else if (ps.want_blank)
703 *code.e++ = ' ';
704
705 {
706 size_t len = token.e - token.s;
707
708 check_size_code(len);
709 memcpy(code.e, token.s, len);
710 code.e += len;
711 }
712 ps.want_blank = false;
713 }
714
715 static void
716 process_binary_op(void)
717 {
718 size_t len = token.e - token.s;
719
720 check_size_code(len + 1);
721 if (ps.want_blank)
722 *code.e++ = ' ';
723 memcpy(code.e, token.s, len);
724 code.e += len;
725
726 ps.want_blank = true;
727 }
728
729 static void
730 process_postfix_op(void)
731 {
732 *code.e++ = token.s[0];
733 *code.e++ = token.s[1];
734 ps.want_blank = true;
735 }
736
737 static void
738 process_question(int *inout_squest)
739 {
740 (*inout_squest)++; /* this will be used when a later colon
741 * appears so we can distinguish the
742 * <c>?<n>:<n> construct */
743 if (ps.want_blank)
744 *code.e++ = ' ';
745 *code.e++ = '?';
746 ps.want_blank = true;
747 }
748
749 static void
750 process_colon(int *inout_squest, bool *inout_force_nl, bool *inout_scase)
751 {
752 if (*inout_squest > 0) { /* it is part of the <c>?<n>: <n> construct */
753 --*inout_squest;
754 if (ps.want_blank)
755 *code.e++ = ' ';
756 *code.e++ = ':';
757 ps.want_blank = true;
758 return;
759 }
760 if (ps.in_or_st) {
761 *code.e++ = ':';
762 ps.want_blank = false;
763 return;
764 }
765 ps.in_stmt = false; /* seeing a label does not imply we are in a
766 * stmt */
767 /*
768 * turn everything so far into a label
769 */
770 {
771 size_t len = code.e - code.s;
772
773 check_size_label(len + 3);
774 memcpy(lab.e, code.s, len);
775 lab.e += len;
776 *lab.e++ = ':';
777 *lab.e = '\0';
778 code.e = code.s;
779 }
780 *inout_force_nl = ps.pcase = *inout_scase; /* ps.pcase will be used by
781 * dump_line to decide how to
782 * indent the label. force_nl
783 * will force a case n: to be
784 * on a line by itself */
785 *inout_scase = false;
786 ps.want_blank = false;
787 }
788
789 static void
790 process_semicolon(bool *inout_scase, int *inout_squest, int dec_ind,
791 bool tabs_to_var, bool *inout_sp_sw,
792 token_type hd_type,
793 bool *inout_force_nl)
794 {
795 if (ps.decl_nest == 0)
796 ps.in_or_st = false; /* we are not in an initialization or
797 * structure declaration */
798 *inout_scase = false; /* these will only need resetting in an error */
799 *inout_squest = 0;
800 if (ps.last_token == rparen)
801 ps.in_parameter_declaration = false;
802 ps.cast_mask = 0;
803 ps.not_cast_mask = 0;
804 ps.block_init = false;
805 ps.block_init_level = 0;
806 ps.just_saw_decl--;
807
808 if (ps.in_decl && code.s == code.e && !ps.block_init &&
809 !ps.dumped_decl_indent && ps.paren_level == 0) {
810 /* indent stray semicolons in declarations */
811 indent_declaration(dec_ind - 1, tabs_to_var);
812 ps.dumped_decl_indent = true;
813 }
814
815 ps.in_decl = (ps.decl_nest > 0); /* if we were in a first level
816 * structure declaration, we arent any
817 * more */
818
819 if ((!*inout_sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
820
821 /*
822 * This should be true iff there were unbalanced parens in the stmt.
823 * It is a bit complicated, because the semicolon might be in a for
824 * stmt
825 */
826 diag(1, "Unbalanced parens");
827 ps.p_l_follow = 0;
828 if (*inout_sp_sw) { /* this is a check for an if, while, etc. with
829 * unbalanced parens */
830 *inout_sp_sw = false;
831 parse(hd_type); /* dont lose the if, or whatever */
832 }
833 }
834 *code.e++ = ';';
835 ps.want_blank = true;
836 ps.in_stmt = (ps.p_l_follow > 0); /* we are no longer in the middle of a
837 * stmt */
838
839 if (!*inout_sp_sw) { /* if not if for (;;) */
840 parse(semicolon); /* let parser know about end of stmt */
841 *inout_force_nl = true; /* force newline after an end of stmt */
842 }
843 }
844
845 static void
846 process_lbrace(bool *inout_force_nl, bool *inout_sp_sw, token_type hd_type,
847 int *di_stack, int di_stack_cap, int *inout_dec_ind)
848 {
849 ps.in_stmt = false; /* dont indent the {} */
850 if (!ps.block_init)
851 *inout_force_nl = true; /* force other stuff on same line as '{' onto
852 * new line */
853 else if (ps.block_init_level <= 0)
854 ps.block_init_level = 1;
855 else
856 ps.block_init_level++;
857
858 if (code.s != code.e && !ps.block_init) {
859 if (!opt.btype_2) {
860 dump_line();
861 ps.want_blank = false;
862 } else if (ps.in_parameter_declaration && !ps.in_or_st) {
863 ps.ind_level_follow = 0;
864 if (opt.function_brace_split) { /* dump the line prior to the
865 * brace ... */
866 dump_line();
867 ps.want_blank = false;
868 } else /* add a space between the decl and brace */
869 ps.want_blank = true;
870 }
871 }
872 if (ps.in_parameter_declaration)
873 prefix_blankline_requested = false;
874
875 if (ps.p_l_follow > 0) { /* check for preceding unbalanced parens */
876 diag(1, "Unbalanced parens");
877 ps.p_l_follow = 0;
878 if (*inout_sp_sw) { /* check for unclosed if, for, etc. */
879 *inout_sp_sw = false;
880 parse(hd_type);
881 ps.ind_level = ps.ind_level_follow;
882 }
883 }
884 if (code.s == code.e)
885 ps.ind_stmt = false; /* dont put extra indentation on line
886 * with '{' */
887 if (ps.in_decl && ps.in_or_st) { /* this is either a structure
888 * declaration or an init */
889 di_stack[ps.decl_nest] = *inout_dec_ind;
890 if (++ps.decl_nest == di_stack_cap) {
891 diag(0, "Reached internal limit of %d struct levels",
892 di_stack_cap);
893 ps.decl_nest--;
894 }
895 /* ? dec_ind = 0; */
896 } else {
897 ps.decl_on_line = false; /* we can't be in the middle of a
898 * declaration, so don't do special
899 * indentation of comments */
900 if (opt.blanklines_after_declarations_at_proctop
901 && ps.in_parameter_declaration)
902 postfix_blankline_requested = true;
903 ps.in_parameter_declaration = false;
904 ps.in_decl = false;
905 }
906 *inout_dec_ind = 0;
907 parse(lbrace); /* let parser know about this */
908 if (ps.want_blank) /* put a blank before '{' if '{' is not at
909 * start of line */
910 *code.e++ = ' ';
911 ps.want_blank = false;
912 *code.e++ = '{';
913 ps.just_saw_decl = 0;
914 }
915
916 static void
917 process_rbrace(bool *inout_sp_sw, int *inout_dec_ind, const int *di_stack)
918 {
919 if (ps.p_stack[ps.tos] == decl && !ps.block_init) /* semicolons can be
920 * omitted in
921 * declarations */
922 parse(semicolon);
923 if (ps.p_l_follow != 0) { /* check for unclosed if, for, else. */
924 diag(1, "Unbalanced parens");
925 ps.p_l_follow = 0;
926 *inout_sp_sw = false;
927 }
928 ps.just_saw_decl = 0;
929 ps.block_init_level--;
930 if (code.s != code.e && !ps.block_init) { /* '}' must be first on line */
931 if (opt.verbose)
932 diag(0, "Line broken");
933 dump_line();
934 }
935 *code.e++ = '}';
936 ps.want_blank = true;
937 ps.in_stmt = ps.ind_stmt = false;
938 if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
939 *inout_dec_ind = di_stack[--ps.decl_nest];
940 if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
941 ps.just_saw_decl = 2;
942 ps.in_decl = true;
943 }
944 prefix_blankline_requested = false;
945 parse(rbrace); /* let parser know about this */
946 ps.search_brace = opt.cuddle_else
947 && ps.p_stack[ps.tos] == if_expr_stmt
948 && ps.il[ps.tos] >= ps.ind_level;
949 if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
950 postfix_blankline_requested = true;
951 }
952
953 static void
954 process_keyword_do_else(bool *inout_force_nl, bool *inout_last_else)
955 {
956 ps.in_stmt = false;
957 if (*token.s == 'e') {
958 if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
959 if (opt.verbose)
960 diag(0, "Line broken");
961 dump_line(); /* make sure this starts a line */
962 ps.want_blank = false;
963 }
964 *inout_force_nl = true;/* also, following stuff must go onto new line */
965 *inout_last_else = true;
966 parse(keyword_else);
967 } else {
968 if (code.e != code.s) { /* make sure this starts a line */
969 if (opt.verbose)
970 diag(0, "Line broken");
971 dump_line();
972 ps.want_blank = false;
973 }
974 *inout_force_nl = true;/* also, following stuff must go onto new line */
975 *inout_last_else = false;
976 parse(keyword_do);
977 }
978 }
979
980 static void
981 process_decl(int *out_dec_ind, bool *out_tabs_to_var)
982 {
983 parse(decl); /* let parser worry about indentation */
984 if (ps.last_token == rparen && ps.tos <= 1) {
985 if (code.s != code.e) {
986 dump_line();
987 ps.want_blank = false;
988 }
989 }
990 if (ps.in_parameter_declaration && opt.indent_parameters &&
991 ps.decl_nest == 0) {
992 ps.ind_level = ps.ind_level_follow = 1;
993 ps.ind_stmt = false;
994 }
995 ps.in_or_st = true; /* this might be a structure or initialization
996 * declaration */
997 ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
998 if ( /* !ps.in_or_st && */ ps.decl_nest <= 0)
999 ps.just_saw_decl = 2;
1000 prefix_blankline_requested = false;
1001
1002 int len = (int)strlen(token.s) + 1;
1003 int ind = ps.ind_level == 0 || ps.decl_nest > 0
1004 ? opt.decl_indent /* global variable or local member */
1005 : opt.local_decl_indent; /* local variable */
1006 *out_dec_ind = ind > 0 ? ind : len;
1007 *out_tabs_to_var = opt.use_tabs ? ind > 0 : false;
1008 }
1009
1010 static void
1011 process_ident(token_type ttype, int dec_ind, bool tabs_to_var,
1012 bool *inout_sp_sw, bool *inout_force_nl, token_type hd_type)
1013 {
1014 if (ps.in_decl) {
1015 if (ttype == funcname) {
1016 ps.in_decl = false;
1017 if (opt.procnames_start_line && code.s != code.e) {
1018 *code.e = '\0';
1019 dump_line();
1020 } else if (ps.want_blank) {
1021 *code.e++ = ' ';
1022 }
1023 ps.want_blank = false;
1024 } else if (!ps.block_init && !ps.dumped_decl_indent &&
1025 ps.paren_level == 0) { /* if we are in a declaration, we must
1026 * indent identifier */
1027 indent_declaration(dec_ind, tabs_to_var);
1028 ps.dumped_decl_indent = true;
1029 ps.want_blank = false;
1030 }
1031 } else if (*inout_sp_sw && ps.p_l_follow == 0) {
1032 *inout_sp_sw = false;
1033 *inout_force_nl = true;
1034 ps.last_u_d = true;
1035 ps.in_stmt = false;
1036 parse(hd_type);
1037 }
1038 }
1039
1040 static void
1041 copy_id(void)
1042 {
1043 size_t len = token.e - token.s;
1044
1045 check_size_code(len + 1);
1046 if (ps.want_blank)
1047 *code.e++ = ' ';
1048 memcpy(code.e, token.s, len);
1049 code.e += len;
1050 }
1051
1052 static void
1053 process_string_prefix(void)
1054 {
1055 size_t len = token.e - token.s;
1056
1057 check_size_code(len + 1);
1058 if (ps.want_blank)
1059 *code.e++ = ' ';
1060 memcpy(code.e, token.s, len);
1061 code.e += len;
1062
1063 ps.want_blank = false;
1064 }
1065
1066 static void
1067 process_period(void)
1068 {
1069 if (code.e[-1] == ',')
1070 *code.e++ = ' ';
1071 *code.e++ = '.'; /* move the period into line */
1072 ps.want_blank = false; /* dont put a blank after a period */
1073 }
1074
1075 static void
1076 process_comma(int dec_ind, bool tabs_to_var, bool *inout_force_nl)
1077 {
1078 ps.want_blank = (code.s != code.e); /* only put blank after comma if comma
1079 * does not start the line */
1080 if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
1081 !ps.dumped_decl_indent && ps.paren_level == 0) {
1082 /* indent leading commas and not the actual identifiers */
1083 indent_declaration(dec_ind - 1, tabs_to_var);
1084 ps.dumped_decl_indent = true;
1085 }
1086 *code.e++ = ',';
1087 if (ps.p_l_follow == 0) {
1088 if (ps.block_init_level <= 0)
1089 ps.block_init = false;
1090 if (break_comma && (opt.break_after_comma ||
1091 indentation_after_range(
1092 compute_code_indent(), code.s, code.e)
1093 >= opt.max_line_length - opt.tabsize))
1094 *inout_force_nl = true;
1095 }
1096 }
1097
1098 static void
1099 process_preprocessing(void)
1100 {
1101 if (com.s != com.e || lab.s != lab.e || code.s != code.e)
1102 dump_line();
1103 check_size_label(1);
1104 *lab.e++ = '#'; /* move whole line to 'label' buffer */
1105
1106 {
1107 bool in_comment = false;
1108 int com_start = 0;
1109 char quote = '\0';
1110 int com_end = 0;
1111
1112 while (*buf_ptr == ' ' || *buf_ptr == '\t') {
1113 buf_ptr++;
1114 if (buf_ptr >= buf_end)
1115 fill_buffer();
1116 }
1117 while (*buf_ptr != '\n' || (in_comment && !had_eof)) {
1118 check_size_label(2);
1119 *lab.e = *buf_ptr++;
1120 if (buf_ptr >= buf_end)
1121 fill_buffer();
1122 switch (*lab.e++) {
1123 case '\\':
1124 if (!in_comment) {
1125 *lab.e++ = *buf_ptr++;
1126 if (buf_ptr >= buf_end)
1127 fill_buffer();
1128 }
1129 break;
1130 case '/':
1131 if (*buf_ptr == '*' && !in_comment && quote == '\0') {
1132 in_comment = true;
1133 *lab.e++ = *buf_ptr++;
1134 com_start = (int)(lab.e - lab.s) - 2;
1135 }
1136 break;
1137 case '"':
1138 if (quote == '"')
1139 quote = '\0';
1140 else if (quote == '\0')
1141 quote = '"';
1142 break;
1143 case '\'':
1144 if (quote == '\'')
1145 quote = '\0';
1146 else if (quote == '\0')
1147 quote = '\'';
1148 break;
1149 case '*':
1150 if (*buf_ptr == '/' && in_comment) {
1151 in_comment = false;
1152 *lab.e++ = *buf_ptr++;
1153 com_end = (int)(lab.e - lab.s);
1154 }
1155 break;
1156 }
1157 }
1158
1159 while (lab.e > lab.s && (lab.e[-1] == ' ' || lab.e[-1] == '\t'))
1160 lab.e--;
1161 if (lab.e - lab.s == com_end && bp_save == NULL) {
1162 /* comment on preprocessor line */
1163 if (sc_end == NULL) { /* if this is the first comment, we
1164 * must set up the buffer */
1165 save_com = sc_buf;
1166 sc_end = &save_com[0];
1167 } else {
1168 *sc_end++ = '\n'; /* add newline between comments */
1169 *sc_end++ = ' ';
1170 --line_no;
1171 }
1172 if (sc_end - save_com + com_end - com_start > sc_size)
1173 errx(1, "input too long");
1174 memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
1175 sc_end += com_end - com_start;
1176 lab.e = lab.s + com_start;
1177 while (lab.e > lab.s && (lab.e[-1] == ' ' || lab.e[-1] == '\t'))
1178 lab.e--;
1179 bp_save = buf_ptr; /* save current input buffer */
1180 be_save = buf_end;
1181 buf_ptr = save_com; /* fix so that subsequent calls to lexi will
1182 * take tokens out of save_com */
1183 *sc_end++ = ' '; /* add trailing blank, just in case */
1184 buf_end = sc_end;
1185 sc_end = NULL;
1186 debug_println("switched buf_ptr to save_com");
1187 }
1188 check_size_label(1);
1189 *lab.e = '\0'; /* null terminate line */
1190 ps.pcase = false;
1191 }
1192
1193 if (strncmp(lab.s, "#if", 3) == 0) { /* also ifdef, ifndef */
1194 if ((size_t)ifdef_level < nitems(state_stack))
1195 state_stack[ifdef_level++] = ps;
1196 else
1197 diag(1, "#if stack overflow");
1198 } else if (strncmp(lab.s, "#el", 3) == 0) { /* else, elif */
1199 if (ifdef_level <= 0)
1200 diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1201 else
1202 ps = state_stack[ifdef_level - 1];
1203 } else if (strncmp(lab.s, "#endif", 6) == 0) {
1204 if (ifdef_level <= 0)
1205 diag(1, "Unmatched #endif");
1206 else
1207 ifdef_level--;
1208 } else {
1209 if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
1210 strncmp(lab.s + 1, "error", 5) != 0 &&
1211 strncmp(lab.s + 1, "line", 4) != 0 &&
1212 strncmp(lab.s + 1, "undef", 5) != 0 &&
1213 strncmp(lab.s + 1, "define", 6) != 0 &&
1214 strncmp(lab.s + 1, "include", 7) != 0) {
1215 diag(1, "Unrecognized cpp directive");
1216 return;
1217 }
1218 }
1219 if (opt.blanklines_around_conditional_compilation) {
1220 postfix_blankline_requested = true;
1221 n_real_blanklines = 0;
1222 } else {
1223 postfix_blankline_requested = false;
1224 prefix_blankline_requested = false;
1225 }
1226
1227 /*
1228 * subsequent processing of the newline character will cause the line to
1229 * be printed
1230 */
1231 }
1232
1233 static void __attribute__((__noreturn__))
1234 main_loop(void)
1235 {
1236 token_type ttype;
1237 bool force_nl; /* when true, code must be broken */
1238 bool last_else = false; /* true iff last keyword was an else */
1239 int dec_ind; /* current indentation for declarations */
1240 int di_stack[20]; /* a stack of structure indentation levels */
1241 bool tabs_to_var; /* true if using tabs to indent to var name */
1242 bool sp_sw; /* when true, we are in the expression of
1243 * if(...), while(...), etc. */
1244 token_type hd_type = end_of_file; /* used to store type of stmt for if
1245 * (...), for (...), etc */
1246 int squest; /* when this is positive, we have seen a '?'
1247 * without the matching ':' in a <c>?<s>:<s>
1248 * construct */
1249 bool scase; /* set to true when we see a 'case', so we
1250 * know what to do with the following colon */
1251
1252 sp_sw = force_nl = false;
1253 dec_ind = 0;
1254 di_stack[ps.decl_nest = 0] = 0;
1255 scase = false;
1256 squest = 0;
1257 tabs_to_var = false;
1258
1259 for (;;) { /* this is the main loop. it will go until we
1260 * reach eof */
1261 bool comment_buffered = false;
1262
1263 ttype = lexi(&ps); /* Read the next token. The actual characters
1264 * read are stored in "token". */
1265
1266 /*
1267 * The following code moves newlines and comments following an if (),
1268 * while (), else, etc. up to the start of the following stmt to a
1269 * buffer. This allows proper handling of both kinds of brace
1270 * placement (-br, -bl) and cuddling "else" (-ce).
1271 */
1272 search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
1273
1274 if (ttype == end_of_file) {
1275 process_end_of_file();
1276 /* NOTREACHED */
1277 }
1278
1279 if (
1280 ttype != comment &&
1281 ttype != newline &&
1282 ttype != preprocessing &&
1283 ttype != form_feed) {
1284 process_comment_in_code(ttype, &force_nl);
1285
1286 } else if (ttype != comment) /* preserve force_nl through a comment */
1287 force_nl = false; /* cancel forced newline after newline, form
1288 * feed, etc */
1289
1290
1291
1292 /*-----------------------------------------------------*\
1293 | do switch on type of token scanned |
1294 \*-----------------------------------------------------*/
1295 check_size_code(3); /* maximum number of increments of code.e
1296 * before the next check_size_code or
1297 * dump_line() is 2. After that there's the
1298 * final increment for the null character. */
1299 switch (ttype) {
1300
1301 case form_feed:
1302 process_form_feed();
1303 break;
1304
1305 case newline:
1306 process_newline();
1307 break;
1308
1309 case lparen: /* got a '(' or '[' */
1310 process_lparen_or_lbracket(dec_ind, tabs_to_var, sp_sw);
1311 break;
1312
1313 case rparen: /* got a ')' or ']' */
1314 process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
1315 break;
1316
1317 case unary_op: /* this could be any unary operation */
1318 process_unary_op(dec_ind, tabs_to_var);
1319 break;
1320
1321 case binary_op: /* any binary operation */
1322 process_binary_op();
1323 break;
1324
1325 case postfix_op: /* got a trailing ++ or -- */
1326 process_postfix_op();
1327 break;
1328
1329 case question: /* got a ? */
1330 process_question(&squest);
1331 break;
1332
1333 case case_label: /* got word 'case' or 'default' */
1334 scase = true; /* so we can process the later colon properly */
1335 goto copy_id;
1336
1337 case colon: /* got a ':' */
1338 process_colon(&squest, &force_nl, &scase);
1339 break;
1340
1341 case semicolon: /* got a ';' */
1342 process_semicolon(&scase, &squest, dec_ind, tabs_to_var, &sp_sw,
1343 hd_type, &force_nl);
1344 break;
1345
1346 case lbrace: /* got a '{' */
1347 process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
1348 (int)nitems(di_stack), &dec_ind);
1349 break;
1350
1351 case rbrace: /* got a '}' */
1352 process_rbrace(&sp_sw, &dec_ind, di_stack);
1353 break;
1354
1355 case switch_expr: /* got keyword "switch" */
1356 sp_sw = true;
1357 hd_type = switch_expr; /* keep this for when we have seen the
1358 * expression */
1359 goto copy_id; /* go move the token into buffer */
1360
1361 case keyword_for_if_while:
1362 sp_sw = true; /* the interesting stuff is done after the
1363 * expression is scanned */
1364 hd_type = (*token.s == 'i' ? if_expr :
1365 (*token.s == 'w' ? while_expr : for_exprs));
1366
1367 /* remember the type of header for later use by parser */
1368 goto copy_id; /* copy the token into line */
1369
1370 case keyword_do_else:
1371 process_keyword_do_else(&force_nl, &last_else);
1372 goto copy_id; /* move the token into line */
1373
1374 case type_def:
1375 case storage_class:
1376 prefix_blankline_requested = false;
1377 goto copy_id;
1378
1379 case keyword_struct_union_enum:
1380 if (ps.p_l_follow > 0)
1381 goto copy_id;
1382 /* FALLTHROUGH */
1383 case decl: /* we have a declaration type (int, etc.) */
1384 process_decl(&dec_ind, &tabs_to_var);
1385 goto copy_id;
1386
1387 case funcname:
1388 case ident: /* got an identifier or constant */
1389 process_ident(ttype, dec_ind, tabs_to_var, &sp_sw, &force_nl,
1390 hd_type);
1391 copy_id:
1392 copy_id();
1393 if (ttype != funcname)
1394 ps.want_blank = true;
1395 break;
1396
1397 case string_prefix:
1398 process_string_prefix();
1399 break;
1400
1401 case period:
1402 process_period();
1403 break;
1404
1405 case comma:
1406 process_comma(dec_ind, tabs_to_var, &force_nl);
1407 break;
1408
1409 case preprocessing: /* '#' */
1410 process_preprocessing();
1411 break;
1412 case comment: /* the initial '/' '*' or '//' of a comment */
1413 process_comment();
1414 break;
1415
1416 default:
1417 break;
1418 }
1419
1420 *code.e = '\0';
1421 if (ttype != comment &&
1422 ttype != newline &&
1423 ttype != preprocessing)
1424 ps.last_token = ttype;
1425 }
1426 }
1427
1428 int
1429 main(int argc, char **argv)
1430 {
1431 main_init_globals();
1432 main_parse_command_line(argc, argv);
1433 #if HAVE_CAPSICUM
1434 init_capsicum();
1435 #endif
1436 main_prepare_parsing();
1437 main_loop();
1438 }
1439
1440 /*
1441 * copy input file to backup file if in_name is /blah/blah/blah/file, then
1442 * backup file will be ".Bfile" then make the backup file the input and
1443 * original input file the output
1444 */
1445 static void
1446 bakcopy(void)
1447 {
1448 ssize_t n;
1449 int bakchn;
1450 char buff[8 * 1024];
1451 const char *p;
1452
1453 /* construct file name .Bfile */
1454 for (p = in_name; *p != '\0'; p++); /* skip to end of string */
1455 while (p > in_name && *p != '/') /* find last '/' */
1456 p--;
1457 if (*p == '/')
1458 p++;
1459 sprintf(bakfile, "%s%s", p, backup_suffix);
1460
1461 /* copy in_name to backup file */
1462 bakchn = creat(bakfile, 0600);
1463 if (bakchn < 0)
1464 err(1, "%s", bakfile);
1465 while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
1466 if (write(bakchn, buff, (size_t)n) != n)
1467 err(1, "%s", bakfile);
1468 if (n < 0)
1469 err(1, "%s", in_name);
1470 close(bakchn);
1471 fclose(input);
1472
1473 /* re-open backup file as the input file */
1474 input = fopen(bakfile, "r");
1475 if (input == NULL)
1476 err(1, "%s", bakfile);
1477 /* now the original input file will be the output */
1478 output = fopen(in_name, "w");
1479 if (output == NULL) {
1480 unlink(bakfile);
1481 err(1, "%s", in_name);
1482 }
1483 }
1484
1485 static void
1486 indent_declaration(int cur_dec_ind, bool tabs_to_var)
1487 {
1488 int pos = (int)(code.e - code.s);
1489 char *startpos = code.e;
1490
1491 /*
1492 * get the tab math right for indentations that are not multiples of
1493 * tabsize
1494 */
1495 if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
1496 pos += (ps.ind_level * opt.indent_size) % opt.tabsize;
1497 cur_dec_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
1498 }
1499 if (tabs_to_var) {
1500 int tpos;
1501
1502 check_size_code((size_t)(cur_dec_ind / opt.tabsize));
1503 while ((tpos = opt.tabsize * (1 + pos / opt.tabsize)) <= cur_dec_ind) {
1504 *code.e++ = '\t';
1505 pos = tpos;
1506 }
1507 }
1508 check_size_code((size_t)(cur_dec_ind - pos + 1));
1509 while (pos < cur_dec_ind) {
1510 *code.e++ = ' ';
1511 pos++;
1512 }
1513 if (code.e == startpos && ps.want_blank) {
1514 *code.e++ = ' ';
1515 ps.want_blank = false;
1516 }
1517 }
1518
1519 #ifdef debug
1520 void
1521 debug_printf(const char *fmt, ...)
1522 {
1523 FILE *f = output == stdout ? stderr : stdout;
1524 va_list ap;
1525
1526 va_start(ap, fmt);
1527 vfprintf(f, fmt, ap);
1528 va_end(ap);
1529 }
1530
1531 void
1532 debug_println(const char *fmt, ...)
1533 {
1534 FILE *f = output == stdout ? stderr : stdout;
1535 va_list ap;
1536
1537 va_start(ap, fmt);
1538 vfprintf(f, fmt, ap);
1539 va_end(ap);
1540 fprintf(f, "\n");
1541 }
1542
1543 void
1544 debug_vis_range(const char *prefix, const char *s, const char *e,
1545 const char *suffix)
1546 {
1547 debug_printf("%s", prefix);
1548 for (const char *p = s; p < e; p++) {
1549 if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
1550 debug_printf("%c", *p);
1551 else if (*p == '\n')
1552 debug_printf("\\n");
1553 else if (*p == '\t')
1554 debug_printf("\\t");
1555 else
1556 debug_printf("\\x%02x", *p);
1557 }
1558 debug_printf("%s", suffix);
1559 }
1560 #endif
1561
1562 static void *
1563 nonnull(void *p)
1564 {
1565 if (p == NULL)
1566 err(EXIT_FAILURE, NULL);
1567 return p;
1568 }
1569
1570 void *
1571 xmalloc(size_t size)
1572 {
1573 return nonnull(malloc(size));
1574 }
1575
1576 void *
1577 xrealloc(void *p, size_t new_size)
1578 {
1579 return nonnull(realloc(p, new_size));
1580 }
1581
1582 char *
1583 xstrdup(const char *s)
1584 {
1585 return nonnull(strdup(s));
1586 }
1587