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