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