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