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