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