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