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