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