2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1985 Sun Microsystems, Inc.
5 * Copyright (c) 1976 Board of Trustees of the University of Illinois.
6 * Copyright (c) 1980, 1993
7 * The Regents of the University of California. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 static char sccsid[] = "@(#)indent.c 5.17 (Berkeley) 6/7/93";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
47 #include <sys/param.h>
48 #include <sys/capsicum.h>
49 #include <capsicum_helpers.h>
58 #include "indent_globs.h"
59 #include "indent_codes.h"
62 static void bakcopy(void);
63 static void indent_declaration(int, int);
65 const char *in_name = "Standard Input"; /* will always point to name of input
67 const char *out_name = "Standard Output"; /* will always point to name
69 const char *simple_backup_suffix = ".BAK"; /* Suffix to use for backup
71 char bakfile[MAXPATHLEN] = "";
74 main(int argc, char **argv)
78 int dec_ind; /* current indentation for declarations */
79 int di_stack[20]; /* a stack of structure indentation levels */
80 int force_nl; /* when true, code must be broken */
81 int hd_type = 0; /* used to store type of stmt for if (...),
83 int i; /* local loop counter */
84 int scase; /* set to true when we see a case, so we will
85 * know what to do with the following colon */
86 int sp_sw; /* when true, we are in the expression of
87 * if(...), while(...), etc. */
88 int squest; /* when this is positive, we have seen a ?
89 * without the matching : in a <c>?<s>:<s>
91 const char *t_ptr; /* used for copying tokens */
92 int tabs_to_var; /* true if using tabs to indent to var name */
93 int type_code; /* the type of token, returned by lexi */
95 int last_else = 0; /* true iff last keyword was an else */
96 const char *profile_name = NULL;
97 const char *envval = NULL;
98 struct parser_state transient_state; /* a copy for lookup */
100 /*-----------------------------------------------*\
102 \*-----------------------------------------------*/
106 ps.p_stack[0] = stmt; /* this is the parser's stack */
107 ps.last_nl = true; /* this is true if the last thing scanned was
109 ps.last_token = semicolon;
110 combuf = (char *) malloc(bufsize);
113 labbuf = (char *) malloc(bufsize);
116 codebuf = (char *) malloc(bufsize);
119 tokenbuf = (char *) malloc(bufsize);
120 if (tokenbuf == NULL)
123 l_com = combuf + bufsize - 5;
124 l_lab = labbuf + bufsize - 5;
125 l_code = codebuf + bufsize - 5;
126 l_token = tokenbuf + bufsize - 5;
127 combuf[0] = codebuf[0] = labbuf[0] = ' '; /* set up code, label, and
129 combuf[1] = codebuf[1] = labbuf[1] = '\0';
130 opt.else_if = 1; /* Default else-if special processing to on */
131 s_lab = e_lab = labbuf + 1;
132 s_code = e_code = codebuf + 1;
133 s_com = e_com = combuf + 1;
134 s_token = e_token = tokenbuf + 1;
136 in_buffer = (char *) malloc(10);
137 if (in_buffer == NULL)
139 in_buffer_limit = in_buffer + 8;
140 buf_ptr = buf_end = in_buffer;
142 had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
143 sp_sw = force_nl = false;
147 di_stack[ps.dec_nest = 0] = 0;
148 ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
150 scase = ps.pcase = false;
159 envval = getenv("SIMPLE_BACKUP_SUFFIX");
161 simple_backup_suffix = envval;
163 /*--------------------------------------------------*\
164 | COMMAND LINE SCAN |
165 \*--------------------------------------------------*/
168 max_col = 78; /* -l78 */
169 lineup_to_parens = 1; /* -lp */
170 lineup_to_parens_always = 0; /* -nlpl */
171 ps.ljust_decl = 0; /* -ndj */
172 ps.com_ind = 33; /* -c33 */
173 star_comment_cont = 1; /* -sc */
174 ps.ind_size = 8; /* -i8 */
176 ps.decl_indent = 16; /* -di16 */
177 ps.local_decl_indent = -1; /* if this is not set to some nonnegative value
178 * by an arg, we will set this equal to
180 ps.indent_parameters = 1; /* -ip */
181 ps.decl_com_ind = 0; /* if this is not set to some positive value
182 * by an arg, we will set this equal to
184 btype_2 = 1; /* -br */
185 cuddle_else = 1; /* -ce */
186 ps.unindent_displace = 0; /* -d0 */
187 ps.case_indent = 0; /* -cli0 */
188 format_block_comments = 1; /* -fcb */
189 format_col1_comments = 1; /* -fc1 */
190 procnames_start_line = 1; /* -psl */
191 proc_calls_space = 0; /* -npcs */
192 comment_delimiter_on_blankline = 1; /* -cdb */
193 ps.leave_comma = 1; /* -nbc */
196 for (i = 1; i < argc; ++i)
197 if (strcmp(argv[i], "-npro") == 0)
199 else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0')
200 profile_name = argv[i]; /* non-empty -P (set profile) */
203 set_profile(profile_name);
205 for (i = 1; i < argc; ++i) {
208 * look thru args (if any) for changes to defaults
210 if (argv[i][0] != '-') {/* no flag on parameter */
211 if (input == NULL) { /* we must have the input file */
212 in_name = argv[i]; /* remember name of input file */
213 input = fopen(in_name, "r");
214 if (input == NULL) /* check for open error */
215 err(1, "%s", in_name);
218 else if (output == NULL) { /* we have the output file */
219 out_name = argv[i]; /* remember name of output file */
220 if (strcmp(in_name, out_name) == 0) { /* attempt to overwrite
222 errx(1, "input and output files must be different");
224 output = fopen(out_name, "w");
225 if (output == NULL) /* check for create error */
226 err(1, "%s", out_name);
229 errx(1, "unknown parameter: %s", argv[i]);
236 if (output == NULL) {
245 /* Restrict input/output descriptors and enter Capsicum sandbox. */
246 cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
247 if (cap_rights_limit(fileno(output), &rights) < 0 && errno != ENOSYS)
248 err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
249 cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
250 if (cap_rights_limit(fileno(input), &rights) < 0 && errno != ENOSYS)
251 err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
252 if (caph_enter() < 0)
253 err(EXIT_FAILURE, "unable to enter capability mode");
255 if (opt.com_ind <= 1)
256 opt.com_ind = 2; /* don't put normal comments before column 2 */
257 if (opt.block_comment_max_col <= 0)
258 opt.block_comment_max_col = opt.max_col;
259 if (opt.local_decl_indent < 0) /* if not specified by user, set this */
260 opt.local_decl_indent = opt.decl_indent;
261 if (opt.decl_com_ind <= 0) /* if not specified by user, set this */
262 opt.decl_com_ind = opt.ljust_decl ? (opt.com_ind <= 10 ? 2 : opt.com_ind - 8) : opt.com_ind;
263 if (opt.continuation_indent == 0)
264 opt.continuation_indent = opt.ind_size;
265 fill_buffer(); /* get first batch of stuff into input buffer */
276 col = opt.tabsize * (1 + (col - 1) / opt.tabsize) + 1;
281 if (col > opt.ind_size)
282 ps.ind_level = ps.i_l_follow = col / opt.ind_size;
289 while (1) { /* this is the main loop. it will go until we
291 int comment_buffered = false;
293 type_code = lexi(&ps); /* lexi reads one token. The actual
294 * characters read are stored in "token". lexi
295 * returns a code indicating the type of token */
298 * The following code moves newlines and comments following an if (),
299 * while (), else, etc. up to the start of the following stmt to
300 * a buffer. This allows proper handling of both kinds of brace
301 * placement (-br, -bl) and cuddling "else" (-ce).
304 while (ps.search_brace) {
307 if (sc_end == NULL) {
309 save_com[0] = save_com[1] = ' ';
310 sc_end = &save_com[2];
314 * We may have inherited a force_nl == true from the previous
315 * token (like a semicolon). But once we know that a newline
316 * has been scanned in this loop, force_nl should be false.
318 * However, the force_nl == true must be preserved if newline
319 * is never scanned in this loop, so this assignment cannot be
326 if (sc_end == NULL) {
328 * Copy everything from the start of the line, because
329 * pr_comment() will use that to calculate original
330 * indentation of a boxed comment.
332 memcpy(sc_buf, in_buffer, buf_ptr - in_buffer - 4);
333 save_com = sc_buf + (buf_ptr - in_buffer - 4);
334 save_com[0] = save_com[1] = ' ';
335 sc_end = &save_com[2];
337 comment_buffered = true;
338 *sc_end++ = '/'; /* copy in start of comment */
340 for (;;) { /* loop until we get to the end of the comment */
341 *sc_end = *buf_ptr++;
342 if (buf_ptr >= buf_end)
344 if (*sc_end++ == '*' && *buf_ptr == '/')
345 break; /* we are at end of comment */
346 if (sc_end >= &save_com[sc_size]) { /* check for temp buffer
348 diag2(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
353 *sc_end++ = '/'; /* add ending slash */
354 if (++buf_ptr >= buf_end) /* get past / in buffer */
359 * Put KNF-style lbraces before the buffered up tokens and
360 * jump out of this loop in order to avoid copying the token
361 * again under the default case of the switch below.
363 if (sc_end != NULL && opt.btype_2) {
366 * Originally the lbrace may have been alone on its own
367 * line, but it will be moved into "the else's line", so
368 * if there was a newline resulting from the "{" before,
369 * it must be scanned now and ignored.
371 while (isspace((unsigned char)*buf_ptr)) {
372 if (++buf_ptr >= buf_end)
374 if (*buf_ptr == '\n')
380 default: /* it is the start of a normal statement */
386 (type_code == sp_nparen && *token == 'e' &&
387 e_code != s_code && e_code[-1] == '}')
389 || (type_code == sp_paren && *token == 'i' &&
390 last_else && opt.else_if);
393 if (sc_end == NULL) { /* ignore buffering if
394 * comment wasn't saved up */
395 ps.search_brace = false;
398 while (sc_end > save_com && isblank((unsigned char)sc_end[-1])) {
401 if (opt.swallow_optional_blanklines ||
402 (!comment_buffered && remove_newlines)) {
403 force_nl = !remove_newlines;
404 while (sc_end > save_com && sc_end[-1] == '\n') {
408 if (force_nl) { /* if we should insert a nl here, put
409 * it into the buffer */
411 --line_no; /* this will be re-increased when the
412 * newline is read from the buffer */
415 if (opt.verbose) /* print error msg if the line was
416 * not already broken */
417 diag2(0, "Line broken");
419 for (t_ptr = token; *t_ptr; ++t_ptr)
423 ps.search_brace = false; /* stop looking for start of
425 bp_save = buf_ptr; /* save current input buffer */
427 buf_ptr = save_com; /* fix so that subsequent calls to
428 * lexi will take tokens out of
430 *sc_end++ = ' ';/* add trailing blank, just in case */
435 } /* end of switch */
437 * We must make this check, just in case there was an unexpected
440 if (type_code != 0) {
442 * The only intended purpose of calling lexi() below is to
443 * categorize the next token in order to decide whether to
444 * continue buffering forthcoming tokens. Once the buffering
445 * is over, lexi() will be called again elsewhere on all of
446 * the tokens - this time for normal processing.
448 * Calling it for this purpose is a bug, because lexi() also
449 * changes the parser state and discards leading whitespace,
450 * which is needed mostly for comment-related considerations.
452 * Work around the former problem by giving lexi() a copy of
453 * the current parser state and discard it if the call turned
454 * out to be just a look ahead.
456 * Work around the latter problem by copying all whitespace
457 * characters into the buffer so that the later lexi() call
460 if (sc_end != NULL) {
461 while (*buf_ptr == ' ' || *buf_ptr == '\t') {
462 *sc_end++ = *buf_ptr++;
463 if (sc_end >= &save_com[sc_size]) {
464 errx(1, "input too long");
467 if (buf_ptr >= buf_end) {
471 transient_state = ps;
472 type_code = lexi(&transient_state); /* read another token */
473 if (type_code != newline && type_code != form_feed &&
474 type_code != comment && !transient_state.search_brace) {
475 ps = transient_state;
478 } /* end of while (search_brace) */
481 if (type_code == 0) { /* we got eof */
482 if (s_lab != e_lab || s_code != e_code
483 || s_com != e_com) /* must dump end of line */
485 if (ps.tos > 1) /* check for balanced braces */
486 diag2(1, "Stuff missing from end of file");
489 printf("There were %d output lines and %d comments\n",
490 ps.out_lines, ps.out_coms);
491 printf("(Lines with comments)/(Lines with code): %6.3f\n",
492 (1.0 * ps.com_lines) / code_lines);
498 (type_code != comment) &&
499 (type_code != newline) &&
500 (type_code != preesc) &&
501 (type_code != form_feed)) {
503 (type_code != semicolon) &&
504 (type_code != lbrace || !opt.btype_2)) {
505 /* we should force a broken line here */
507 diag2(0, "Line broken");
509 ps.want_blank = false; /* dont insert blank at line start */
512 ps.in_stmt = true; /* turn on flag which causes an extra level of
513 * indentation. this is turned off by a ; or
515 if (s_com != e_com) { /* the turkey has embedded a comment
516 * in a line. fix it */
517 int len = e_com - s_com;
519 CHECK_SIZE_CODE(len + 3);
521 memcpy(e_code, s_com, len);
524 *e_code = '\0'; /* null terminate code sect */
525 ps.want_blank = false;
529 else if (type_code != comment) /* preserve force_nl thru a comment */
530 force_nl = false; /* cancel forced newline after newline, form
535 /*-----------------------------------------------------*\
536 | do switch on type of token scanned |
537 \*-----------------------------------------------------*/
538 CHECK_SIZE_CODE(3); /* maximum number of increments of e_code
539 * before the next CHECK_SIZE_CODE or
540 * dump_line() is 2. After that there's the
541 * final increment for the null character. */
542 switch (type_code) { /* now, decide what to do with the token */
544 case form_feed: /* found a form feed in line */
545 ps.use_ff = true; /* a form feed is treated much like a newline */
547 ps.want_blank = false;
551 if (ps.last_token != comma || ps.p_l_follow > 0
552 || !opt.leave_comma || ps.block_init || !break_comma || s_com != e_com) {
554 ps.want_blank = false;
556 ++line_no; /* keep track of input line number */
559 case lparen: /* got a '(' or '[' */
560 /* count parens to make Healy happy */
561 if (++ps.p_l_follow == nitems(ps.paren_indents)) {
562 diag3(0, "Reached internal limit of %d unclosed parens",
563 nitems(ps.paren_indents));
567 /* not a function pointer declaration or a function call */;
568 else if (ps.in_decl && !ps.block_init && !ps.dumped_decl_indent &&
569 ps.procname[0] == '\0' && ps.paren_level == 0) {
570 /* function pointer declarations */
571 indent_declaration(dec_ind, tabs_to_var);
572 ps.dumped_decl_indent = true;
574 else if (ps.want_blank &&
575 ((ps.last_token != ident && ps.last_token != funcname) ||
576 opt.proc_calls_space ||
577 /* offsetof (1) is never allowed a space; sizeof (2) gets
578 * one iff -bs; all other keywords (>2) always get a space
580 ps.keyword + opt.Bill_Shannon > 2))
582 ps.want_blank = false;
583 *e_code++ = token[0];
584 ps.paren_indents[ps.p_l_follow - 1] = count_spaces_until(1, s_code, e_code) - 1;
585 if (sp_sw && ps.p_l_follow == 1 && opt.extra_expression_indent
586 && ps.paren_indents[0] < 2 * opt.ind_size)
587 ps.paren_indents[0] = 2 * opt.ind_size;
588 if (ps.in_or_st && *token == '(' && ps.tos <= 2) {
590 * this is a kluge to make sure that declarations will be
591 * aligned right if proc decl has an explicit type on it, i.e.
594 parse(semicolon); /* I said this was a kluge... */
595 ps.in_or_st = false; /* turn off flag for structure decl or
598 /* parenthesized type following sizeof or offsetof is not a cast */
599 if (ps.keyword == 1 || ps.keyword == 2)
600 ps.not_cast_mask |= 1 << ps.p_l_follow;
603 case rparen: /* got a ')' or ']' */
604 if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) {
606 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
607 ps.want_blank = opt.space_after_cast;
609 ps.want_blank = true;
610 ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
611 if (--ps.p_l_follow < 0) {
613 diag3(0, "Extra %c", *token);
615 if (e_code == s_code) /* if the paren starts the line */
616 ps.paren_level = ps.p_l_follow; /* then indent it */
618 *e_code++ = token[0];
620 if (sp_sw && (ps.p_l_follow == 0)) { /* check for end of if
621 * (...), or some such */
623 force_nl = true;/* must force newline after if */
624 ps.last_u_d = true; /* inform lexi that a following
625 * operator is unary */
626 ps.in_stmt = false; /* dont use stmt continuation
629 parse(hd_type); /* let parser worry about if, or whatever */
631 ps.search_brace = opt.btype_2; /* this should ensure that
632 * constructs such as main(){...}
633 * and int[]{...} have their braces
634 * put in the right place */
637 case unary_op: /* this could be any unary operation */
638 if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
639 ps.procname[0] == '\0' && ps.paren_level == 0) {
640 /* pointer declarations */
643 * if this is a unary op in a declaration, we should indent
646 for (i = 0; token[i]; ++i)
647 /* find length of token */;
648 indent_declaration(dec_ind - i, tabs_to_var);
649 ps.dumped_decl_indent = true;
651 else if (ps.want_blank)
655 int len = e_token - s_token;
657 CHECK_SIZE_CODE(len);
658 memcpy(e_code, token, len);
661 ps.want_blank = false;
664 case binary_op: /* any binary operation */
666 int len = e_token - s_token;
668 CHECK_SIZE_CODE(len + 1);
671 memcpy(e_code, token, len);
674 ps.want_blank = true;
677 case postop: /* got a trailing ++ or -- */
678 *e_code++ = token[0];
679 *e_code++ = token[1];
680 ps.want_blank = true;
683 case question: /* got a ? */
684 squest++; /* this will be used when a later colon
685 * appears so we can distinguish the
686 * <c>?<n>:<n> construct */
690 ps.want_blank = true;
693 case casestmt: /* got word 'case' or 'default' */
694 scase = true; /* so we can process the later colon properly */
697 case colon: /* got a ':' */
698 if (squest > 0) { /* it is part of the <c>?<n>: <n> construct */
703 ps.want_blank = true;
708 ps.want_blank = false;
711 ps.in_stmt = false; /* seeing a label does not imply we are in a
714 * turn everything so far into a label
717 int len = e_code - s_code;
719 CHECK_SIZE_LAB(len + 3);
720 memcpy(e_lab, s_code, len);
726 force_nl = ps.pcase = scase; /* ps.pcase will be used by
727 * dump_line to decide how to
728 * indent the label. force_nl
729 * will force a case n: to be
730 * on a line by itself */
732 ps.want_blank = false;
735 case semicolon: /* got a ';' */
736 if (ps.dec_nest == 0)
737 ps.in_or_st = false;/* we are not in an initialization or
738 * structure declaration */
739 scase = false; /* these will only need resetting in an error */
741 if (ps.last_token == rparen)
742 ps.in_parameter_declaration = 0;
744 ps.not_cast_mask = 0;
746 ps.block_init_level = 0;
749 if (ps.in_decl && s_code == e_code && !ps.block_init &&
750 !ps.dumped_decl_indent && ps.paren_level == 0) {
751 /* indent stray semicolons in declarations */
752 indent_declaration(dec_ind - 1, tabs_to_var);
753 ps.dumped_decl_indent = true;
756 ps.in_decl = (ps.dec_nest > 0); /* if we were in a first level
757 * structure declaration, we
760 if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) {
763 * This should be true iff there were unbalanced parens in the
764 * stmt. It is a bit complicated, because the semicolon might
767 diag2(1, "Unbalanced parens");
769 if (sp_sw) { /* this is a check for an if, while, etc. with
770 * unbalanced parens */
772 parse(hd_type); /* dont lose the if, or whatever */
776 ps.want_blank = true;
777 ps.in_stmt = (ps.p_l_follow > 0); /* we are no longer in the
778 * middle of a stmt */
780 if (!sp_sw) { /* if not if for (;;) */
781 parse(semicolon); /* let parser know about end of stmt */
782 force_nl = true;/* force newline after an end of stmt */
786 case lbrace: /* got a '{' */
787 ps.in_stmt = false; /* dont indent the {} */
789 force_nl = true;/* force other stuff on same line as '{' onto
791 else if (ps.block_init_level <= 0)
792 ps.block_init_level = 1;
794 ps.block_init_level++;
796 if (s_code != e_code && !ps.block_init) {
799 ps.want_blank = false;
801 else if (ps.in_parameter_declaration && !ps.in_or_st) {
803 if (opt.function_brace_split) { /* dump the line prior
804 * to the brace ... */
806 ps.want_blank = false;
807 } else /* add a space between the decl and brace */
808 ps.want_blank = true;
811 if (ps.in_parameter_declaration)
812 prefix_blankline_requested = 0;
814 if (ps.p_l_follow > 0) { /* check for preceding unbalanced
816 diag2(1, "Unbalanced parens");
818 if (sp_sw) { /* check for unclosed if, for, etc. */
821 ps.ind_level = ps.i_l_follow;
824 if (s_code == e_code)
825 ps.ind_stmt = false; /* dont put extra indentation on line
827 if (ps.in_decl && ps.in_or_st) { /* this is either a structure
828 * declaration or an init */
829 di_stack[ps.dec_nest] = dec_ind;
830 if (++ps.dec_nest == nitems(di_stack)) {
831 diag3(0, "Reached internal limit of %d struct levels",
838 ps.decl_on_line = false; /* we can't be in the middle of
839 * a declaration, so don't do
840 * special indentation of
842 if (opt.blanklines_after_declarations_at_proctop
843 && ps.in_parameter_declaration)
844 postfix_blankline_requested = 1;
845 ps.in_parameter_declaration = 0;
849 parse(lbrace); /* let parser know about this */
850 if (ps.want_blank) /* put a blank before '{' if '{' is not at
853 ps.want_blank = false;
855 ps.just_saw_decl = 0;
858 case rbrace: /* got a '}' */
859 if (ps.p_stack[ps.tos] == decl && !ps.block_init) /* semicolons can be
863 if (ps.p_l_follow) {/* check for unclosed if, for, else. */
864 diag2(1, "Unbalanced parens");
868 ps.just_saw_decl = 0;
869 ps.block_init_level--;
870 if (s_code != e_code && !ps.block_init) { /* '}' must be first on
873 diag2(0, "Line broken");
877 ps.want_blank = true;
878 ps.in_stmt = ps.ind_stmt = false;
879 if (ps.dec_nest > 0) { /* we are in multi-level structure
881 dec_ind = di_stack[--ps.dec_nest];
882 if (ps.dec_nest == 0 && !ps.in_parameter_declaration)
883 ps.just_saw_decl = 2;
886 prefix_blankline_requested = 0;
887 parse(rbrace); /* let parser know about this */
888 ps.search_brace = opt.cuddle_else && ps.p_stack[ps.tos] == ifhead
889 && ps.il[ps.tos] >= ps.ind_level;
890 if (ps.tos <= 1 && opt.blanklines_after_procs && ps.dec_nest <= 0)
891 postfix_blankline_requested = 1;
894 case swstmt: /* got keyword "switch" */
896 hd_type = swstmt; /* keep this for when we have seen the
898 goto copy_id; /* go move the token into buffer */
900 case sp_paren: /* token is if, while, for */
901 sp_sw = true; /* the interesting stuff is done after the
902 * expression is scanned */
903 hd_type = (*token == 'i' ? ifstmt :
904 (*token == 'w' ? whilestmt : forstmt));
907 * remember the type of header for later use by parser
909 goto copy_id; /* copy the token into line */
911 case sp_nparen: /* got else, do */
914 if (e_code != s_code && (!opt.cuddle_else || e_code[-1] != '}')) {
916 diag2(0, "Line broken");
917 dump_line();/* make sure this starts a line */
918 ps.want_blank = false;
920 force_nl = true;/* also, following stuff must go onto new line */
925 if (e_code != s_code) { /* make sure this starts a line */
927 diag2(0, "Line broken");
929 ps.want_blank = false;
931 force_nl = true;/* also, following stuff must go onto new line */
935 goto copy_id; /* move the token into line */
939 prefix_blankline_requested = 0;
943 if (ps.p_l_follow > 0)
945 case decl: /* we have a declaration type (int, etc.) */
946 parse(decl); /* let parser worry about indentation */
947 if (ps.last_token == rparen && ps.tos <= 1) {
948 if (s_code != e_code) {
953 if (ps.in_parameter_declaration && opt.indent_parameters && ps.dec_nest == 0) {
954 ps.ind_level = ps.i_l_follow = 1;
957 ps.in_or_st = true; /* this might be a structure or initialization
959 ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
960 if ( /* !ps.in_or_st && */ ps.dec_nest <= 0)
961 ps.just_saw_decl = 2;
962 prefix_blankline_requested = 0;
963 for (i = 0; token[i++];); /* get length of token */
965 if (ps.ind_level == 0 || ps.dec_nest > 0) {
966 /* global variable or struct member in local variable */
967 dec_ind = opt.decl_indent > 0 ? opt.decl_indent : i;
968 tabs_to_var = (opt.use_tabs ? opt.decl_indent > 0 : 0);
971 dec_ind = opt.local_decl_indent > 0 ? opt.local_decl_indent : i;
972 tabs_to_var = (opt.use_tabs ? opt.local_decl_indent > 0 : 0);
977 case ident: /* got an identifier or constant */
979 if (type_code == funcname) {
981 if (opt.procnames_start_line && s_code != e_code) {
985 else if (ps.want_blank) {
988 ps.want_blank = false;
990 else if (!ps.block_init && !ps.dumped_decl_indent &&
991 ps.paren_level == 0) { /* if we are in a declaration, we
992 * must indent identifier */
993 indent_declaration(dec_ind, tabs_to_var);
994 ps.dumped_decl_indent = true;
995 ps.want_blank = false;
998 else if (sp_sw && ps.p_l_follow == 0) {
1007 int len = e_token - s_token;
1009 CHECK_SIZE_CODE(len + 1);
1012 memcpy(e_code, s_token, len);
1015 if (type_code != funcname)
1016 ps.want_blank = true;
1021 int len = e_token - s_token;
1023 CHECK_SIZE_CODE(len + 1);
1026 memcpy(e_code, token, len);
1029 ps.want_blank = false;
1032 case period: /* treat a period kind of like a binary
1034 *e_code++ = '.'; /* move the period into line */
1035 ps.want_blank = false; /* dont put a blank after a period */
1039 ps.want_blank = (s_code != e_code); /* only put blank after comma
1040 * if comma does not start the
1042 if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
1043 !ps.dumped_decl_indent && ps.paren_level == 0) {
1044 /* indent leading commas and not the actual identifiers */
1045 indent_declaration(dec_ind - 1, tabs_to_var);
1046 ps.dumped_decl_indent = true;
1049 if (ps.p_l_follow == 0) {
1050 if (ps.block_init_level <= 0)
1052 if (break_comma && (!opt.leave_comma ||
1053 count_spaces_until(compute_code_target(), s_code, e_code) >
1054 opt.max_col - opt.tabsize))
1059 case preesc: /* got the character '#' */
1060 if ((s_com != e_com) ||
1065 *e_lab++ = '#'; /* move whole line to 'label' buffer */
1072 while (*buf_ptr == ' ' || *buf_ptr == '\t') {
1074 if (buf_ptr >= buf_end)
1077 while (*buf_ptr != '\n' || (in_comment && !had_eof)) {
1079 *e_lab = *buf_ptr++;
1080 if (buf_ptr >= buf_end)
1085 *e_lab++ = *buf_ptr++;
1086 if (buf_ptr >= buf_end)
1091 if (*buf_ptr == '*' && !in_comment && !quote) {
1093 *e_lab++ = *buf_ptr++;
1094 com_start = e_lab - s_lab - 2;
1106 if (*buf_ptr == '/' && in_comment) {
1108 *e_lab++ = *buf_ptr++;
1109 com_end = e_lab - s_lab;
1115 while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1117 if (e_lab - s_lab == com_end && bp_save == NULL) {
1118 /* comment on preprocessor line */
1119 if (sc_end == NULL) { /* if this is the first comment,
1120 * we must set up the buffer */
1122 sc_end = &save_com[0];
1125 *sc_end++ = '\n'; /* add newline between
1130 if (sc_end - save_com + com_end - com_start > sc_size)
1131 errx(1, "input too long");
1132 memmove(sc_end, s_lab + com_start, com_end - com_start);
1133 sc_end += com_end - com_start;
1134 e_lab = s_lab + com_start;
1135 while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1137 bp_save = buf_ptr; /* save current input buffer */
1139 buf_ptr = save_com; /* fix so that subsequent calls to
1140 * lexi will take tokens out of
1142 *sc_end++ = ' '; /* add trailing blank, just in case */
1147 *e_lab = '\0'; /* null terminate line */
1151 if (strncmp(s_lab, "#if", 3) == 0) { /* also ifdef, ifndef */
1152 if ((size_t)ifdef_level < nitems(state_stack)) {
1153 match_state[ifdef_level].tos = -1;
1154 state_stack[ifdef_level++] = ps;
1157 diag2(1, "#if stack overflow");
1159 else if (strncmp(s_lab, "#el", 3) == 0) { /* else, elif */
1160 if (ifdef_level <= 0)
1161 diag2(1, s_lab[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1163 match_state[ifdef_level - 1] = ps;
1164 ps = state_stack[ifdef_level - 1];
1167 else if (strncmp(s_lab, "#endif", 6) == 0) {
1168 if (ifdef_level <= 0)
1169 diag2(1, "Unmatched #endif");
1185 int d = nitems(recognized);
1187 if (strncmp(s_lab + 1, recognized[d].string, recognized[d].size) == 0)
1190 diag2(1, "Unrecognized cpp directive");
1194 if (opt.blanklines_around_conditional_compilation) {
1195 postfix_blankline_requested++;
1196 n_real_blanklines = 0;
1199 postfix_blankline_requested = 0;
1200 prefix_blankline_requested = 0;
1202 break; /* subsequent processing of the newline
1203 * character will cause the line to be printed */
1205 case comment: /* we have gotten a / followed by * this is a biggie */
1208 } /* end of big switch stmt */
1210 *e_code = '\0'; /* make sure code section is null terminated */
1211 if (type_code != comment && type_code != newline && type_code != preesc)
1212 ps.last_token = type_code;
1213 } /* end of main while (1) loop */
1217 * copy input file to backup file if in_name is /blah/blah/blah/file, then
1218 * backup file will be ".Bfile" then make the backup file the input and
1219 * original input file the output
1226 char buff[8 * 1024];
1229 /* construct file name .Bfile */
1230 for (p = in_name; *p; p++); /* skip to end of string */
1231 while (p > in_name && *p != '/') /* find last '/' */
1235 sprintf(bakfile, "%s%s", p, simple_backup_suffix);
1237 /* copy in_name to backup file */
1238 bakchn = creat(bakfile, 0600);
1240 err(1, "%s", bakfile);
1241 while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
1242 if (write(bakchn, buff, n) != n)
1243 err(1, "%s", bakfile);
1245 err(1, "%s", in_name);
1249 /* re-open backup file as the input file */
1250 input = fopen(bakfile, "r");
1252 err(1, "%s", bakfile);
1253 /* now the original input file will be the output */
1254 output = fopen(in_name, "w");
1255 if (output == NULL) {
1257 err(1, "%s", in_name);
1262 indent_declaration(int cur_dec_ind, int tabs_to_var)
1264 int pos = e_code - s_code;
1265 char *startpos = e_code;
1268 * get the tab math right for indentations that are not multiples of tabsize
1270 if ((ps.ind_level * opt.ind_size) % opt.tabsize != 0) {
1271 pos += (ps.ind_level * opt.ind_size) % opt.tabsize;
1272 cur_dec_ind += (ps.ind_level * opt.ind_size) % opt.tabsize;
1277 CHECK_SIZE_CODE(cur_dec_ind / opt.tabsize);
1278 while ((tpos = opt.tabsize * (1 + pos / opt.tabsize)) <= cur_dec_ind) {
1283 CHECK_SIZE_CODE(cur_dec_ind - pos + 1);
1284 while (pos < cur_dec_ind) {
1288 if (e_code == startpos && ps.want_blank) {
1290 ps.want_blank = false;