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