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