GCC 7.1 fixes
[zfs.git] / scripts / cstyle.pl
blob73c708c0b93ecc8eb1974988168357485e810d93
1 #!/usr/bin/env perl
3 # CDDL HEADER START
5 # The contents of this file are subject to the terms of the
6 # Common Development and Distribution License (the "License").
7 # You may not use this file except in compliance with the License.
9 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 # or http://www.opensolaris.org/os/licensing.
11 # See the License for the specific language governing permissions
12 # and limitations under the License.
14 # When distributing Covered Code, include this CDDL HEADER in each
15 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 # If applicable, add the following below this CDDL HEADER, with the
17 # fields enclosed by brackets "[]" replaced with your own identifying
18 # information: Portions Copyright [yyyy] [name of copyright owner]
20 # CDDL HEADER END
22 # Copyright 2016 Nexenta Systems, Inc.
24 # Copyright 2008 Sun Microsystems, Inc. All rights reserved.
25 # Use is subject to license terms.
27 # @(#)cstyle 1.58 98/09/09 (from shannon)
28 #ident "%Z%%M% %I% %E% SMI"
30 # cstyle - check for some common stylistic errors.
32 # cstyle is a sort of "lint" for C coding style.
33 # It attempts to check for the style used in the
34 # kernel, sometimes known as "Bill Joy Normal Form".
36 # There's a lot this can't check for, like proper indentation
37 # of code blocks. There's also a lot more this could check for.
39 # A note to the non perl literate:
41 # perl regular expressions are pretty much like egrep
42 # regular expressions, with the following special symbols
44 # \s any space character
45 # \S any non-space character
46 # \w any "word" character [a-zA-Z0-9_]
47 # \W any non-word character
48 # \d a digit [0-9]
49 # \D a non-digit
50 # \b word boundary (between \w and \W)
51 # \B non-word boundary
54 require 5.0;
55 use warnings;
56 use IO::File;
57 use Getopt::Std;
58 use strict;
60 my $usage =
61 "usage: cstyle [-chpvCP] [-o constructs] file ...
62 -c check continuation indentation inside functions
63 -h perform heuristic checks that are sometimes wrong
64 -p perform some of the more picky checks
65 -v verbose
66 -C don't check anything in header block comments
67 -P check for use of non-POSIX types
68 -o constructs
69 allow a comma-separated list of optional constructs:
70 doxygen allow doxygen-style block comments (/** /*!)
71 splint allow splint-style lint comments (/*@ ... @*/)
74 my %opts;
76 if (!getopts("cho:pvCP", \%opts)) {
77 print $usage;
78 exit 2;
81 my $check_continuation = $opts{'c'};
82 my $heuristic = $opts{'h'};
83 my $picky = $opts{'p'};
84 my $verbose = $opts{'v'};
85 my $ignore_hdr_comment = $opts{'C'};
86 my $check_posix_types = $opts{'P'};
88 my $doxygen_comments = 0;
89 my $splint_comments = 0;
91 if (defined($opts{'o'})) {
92 for my $x (split /,/, $opts{'o'}) {
93 if ($x eq "doxygen") {
94 $doxygen_comments = 1;
95 } elsif ($x eq "splint") {
96 $splint_comments = 1;
97 } else {
98 print "cstyle: unrecognized construct \"$x\"\n";
99 print $usage;
100 exit 2;
105 my ($filename, $line, $prev); # shared globals
107 my $fmt;
108 my $hdr_comment_start;
110 if ($verbose) {
111 $fmt = "%s: %d: %s\n%s\n";
112 } else {
113 $fmt = "%s: %d: %s\n";
116 if ($doxygen_comments) {
117 # doxygen comments look like "/*!" or "/**"; allow them.
118 $hdr_comment_start = qr/^\s*\/\*[\!\*]?$/;
119 } else {
120 $hdr_comment_start = qr/^\s*\/\*$/;
123 # Note, following must be in single quotes so that \s and \w work right.
124 my $typename = '(int|char|short|long|unsigned|float|double' .
125 '|\w+_t|struct\s+\w+|union\s+\w+|FILE)';
127 # mapping of old types to POSIX compatible types
128 my %old2posix = (
129 'unchar' => 'uchar_t',
130 'ushort' => 'ushort_t',
131 'uint' => 'uint_t',
132 'ulong' => 'ulong_t',
133 'u_int' => 'uint_t',
134 'u_short' => 'ushort_t',
135 'u_long' => 'ulong_t',
136 'u_char' => 'uchar_t',
137 'quad' => 'quad_t'
140 my $lint_re = qr/\/\*(?:
141 ARGSUSED[0-9]*|NOTREACHED|LINTLIBRARY|VARARGS[0-9]*|
142 CONSTCOND|CONSTANTCOND|CONSTANTCONDITION|EMPTY|
143 FALLTHRU|FALLTHROUGH|LINTED.*?|PRINTFLIKE[0-9]*|
144 PROTOLIB[0-9]*|SCANFLIKE[0-9]*|CSTYLED.*?
145 )\*\//x;
147 my $splint_re = qr/\/\*@.*?@\*\//x;
149 my $warlock_re = qr/\/\*\s*(?:
150 VARIABLES\ PROTECTED\ BY|
151 MEMBERS\ PROTECTED\ BY|
152 ALL\ MEMBERS\ PROTECTED\ BY|
153 READ-ONLY\ VARIABLES:|
154 READ-ONLY\ MEMBERS:|
155 VARIABLES\ READABLE\ WITHOUT\ LOCK:|
156 MEMBERS\ READABLE\ WITHOUT\ LOCK:|
157 LOCKS\ COVERED\ BY|
158 LOCK\ UNNEEDED\ BECAUSE|
159 LOCK\ NEEDED:|
160 LOCK\ HELD\ ON\ ENTRY:|
161 READ\ LOCK\ HELD\ ON\ ENTRY:|
162 WRITE\ LOCK\ HELD\ ON\ ENTRY:|
163 LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
164 READ\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
165 WRITE\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
166 LOCK\ RELEASED\ AS\ SIDE\ EFFECT:|
167 LOCK\ UPGRADED\ AS\ SIDE\ EFFECT:|
168 LOCK\ DOWNGRADED\ AS\ SIDE\ EFFECT:|
169 FUNCTIONS\ CALLED\ THROUGH\ POINTER|
170 FUNCTIONS\ CALLED\ THROUGH\ MEMBER|
171 LOCK\ ORDER:
172 )/x;
174 my $err_stat = 0; # exit status
176 if ($#ARGV >= 0) {
177 foreach my $arg (@ARGV) {
178 my $fh = new IO::File $arg, "r";
179 if (!defined($fh)) {
180 printf "%s: can not open\n", $arg;
181 } else {
182 &cstyle($arg, $fh);
183 close $fh;
186 } else {
187 &cstyle("<stdin>", *STDIN);
189 exit $err_stat;
191 my $no_errs = 0; # set for CSTYLED-protected lines
193 sub err($) {
194 my ($error) = @_;
195 unless ($no_errs) {
196 if ($verbose) {
197 printf $fmt, $filename, $., $error, $line;
198 } else {
199 printf $fmt, $filename, $., $error;
201 $err_stat = 1;
205 sub err_prefix($$) {
206 my ($prevline, $error) = @_;
207 my $out = $prevline."\n".$line;
208 unless ($no_errs) {
209 if ($verbose) {
210 printf $fmt, $filename, $., $error, $out;
211 } else {
212 printf $fmt, $filename, $., $error;
214 $err_stat = 1;
218 sub err_prev($) {
219 my ($error) = @_;
220 unless ($no_errs) {
221 if ($verbose) {
222 printf $fmt, $filename, $. - 1, $error, $prev;
223 } else {
224 printf $fmt, $filename, $. - 1, $error;
226 $err_stat = 1;
230 sub cstyle($$) {
232 my ($fn, $filehandle) = @_;
233 $filename = $fn; # share it globally
235 my $in_cpp = 0;
236 my $next_in_cpp = 0;
238 my $in_comment = 0;
239 my $in_header_comment = 0;
240 my $comment_done = 0;
241 my $in_warlock_comment = 0;
242 my $in_function = 0;
243 my $in_function_header = 0;
244 my $function_header_full_indent = 0;
245 my $in_declaration = 0;
246 my $note_level = 0;
247 my $nextok = 0;
248 my $nocheck = 0;
250 my $in_string = 0;
252 my ($okmsg, $comment_prefix);
254 $line = '';
255 $prev = '';
256 reset_indent();
258 line: while (<$filehandle>) {
259 s/\r?\n$//; # strip return and newline
261 # save the original line, then remove all text from within
262 # double or single quotes, we do not want to check such text.
264 $line = $_;
267 # C allows strings to be continued with a backslash at the end of
268 # the line. We translate that into a quoted string on the previous
269 # line followed by an initial quote on the next line.
271 # (we assume that no-one will use backslash-continuation with character
272 # constants)
274 $_ = '"' . $_ if ($in_string && !$nocheck && !$in_comment);
277 # normal strings and characters
279 s/'([^\\']|\\[^xX0]|\\0[0-9]*|\\[xX][0-9a-fA-F]*)'/''/g;
280 s/"([^\\"]|\\.)*"/\"\"/g;
283 # detect string continuation
285 if ($nocheck || $in_comment) {
286 $in_string = 0;
287 } else {
289 # Now that all full strings are replaced with "", we check
290 # for unfinished strings continuing onto the next line.
292 $in_string =
293 (s/([^"](?:"")*)"([^\\"]|\\.)*\\$/$1""/ ||
294 s/^("")*"([^\\"]|\\.)*\\$/""/);
298 # figure out if we are in a cpp directive
300 $in_cpp = $next_in_cpp || /^\s*#/; # continued or started
301 $next_in_cpp = $in_cpp && /\\$/; # only if continued
303 # strip off trailing backslashes, which appear in long macros
304 s/\s*\\$//;
306 # an /* END CSTYLED */ comment ends a no-check block.
307 if ($nocheck) {
308 if (/\/\* *END *CSTYLED *\*\//) {
309 $nocheck = 0;
310 } else {
311 reset_indent();
312 next line;
316 # a /*CSTYLED*/ comment indicates that the next line is ok.
317 if ($nextok) {
318 if ($okmsg) {
319 err($okmsg);
321 $nextok = 0;
322 $okmsg = 0;
323 if (/\/\* *CSTYLED.*\*\//) {
324 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
325 $okmsg = $1;
326 $nextok = 1;
328 $no_errs = 1;
329 } elsif ($no_errs) {
330 $no_errs = 0;
333 # check length of line.
334 # first, a quick check to see if there is any chance of being too long.
335 if (($line =~ tr/\t/\t/) * 7 + length($line) > 80) {
336 # yes, there is a chance.
337 # replace tabs with spaces and check again.
338 my $eline = $line;
339 1 while $eline =~
340 s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
341 if (length($eline) > 80) {
342 err("line > 80 characters");
346 # ignore NOTE(...) annotations (assumes NOTE is on lines by itself).
347 if ($note_level || /\b_?NOTE\s*\(/) { # if in NOTE or this is NOTE
348 s/[^()]//g; # eliminate all non-parens
349 $note_level += s/\(//g - length; # update paren nest level
350 next;
353 # a /* BEGIN CSTYLED */ comment starts a no-check block.
354 if (/\/\* *BEGIN *CSTYLED *\*\//) {
355 $nocheck = 1;
358 # a /*CSTYLED*/ comment indicates that the next line is ok.
359 if (/\/\* *CSTYLED.*\*\//) {
360 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
361 $okmsg = $1;
362 $nextok = 1;
364 if (/\/\/ *CSTYLED/) {
365 /^.*\/\/ *CSTYLED *(.*)$/;
366 $okmsg = $1;
367 $nextok = 1;
370 # universal checks; apply to everything
371 if (/\t +\t/) {
372 err("spaces between tabs");
374 if (/ \t+ /) {
375 err("tabs between spaces");
377 if (/\s$/) {
378 err("space or tab at end of line");
380 if (/[^ \t(]\/\*/ && !/\w\(\/\*.*\*\/\);/) {
381 err("comment preceded by non-blank");
384 # is this the beginning or ending of a function?
385 # (not if "struct foo\n{\n")
386 if (/^{$/ && $prev =~ /\)\s*(const\s*)?(\/\*.*\*\/\s*)?\\?$/) {
387 $in_function = 1;
388 $in_declaration = 1;
389 $in_function_header = 0;
390 $function_header_full_indent = 0;
391 $prev = $line;
392 next line;
394 if (/^}\s*(\/\*.*\*\/\s*)*$/) {
395 if ($prev =~ /^\s*return\s*;/) {
396 err_prev("unneeded return at end of function");
398 $in_function = 0;
399 reset_indent(); # we don't check between functions
400 $prev = $line;
401 next line;
403 if ($in_function_header && ! /^ (\w|\.)/ ) {
404 if (/^{}$/ # empty functions
405 || /;/ #run function with multiline arguments
406 || /#/ #preprocessor commands
407 || /^[^\s\\]*\(.*\)$/ #functions without ; at the end
408 || /^$/ #function declaration can't have empty line
410 $in_function_header = 0;
411 $function_header_full_indent = 0;
412 } elsif ($prev =~ /^__attribute__/) { #__attribute__((*))
413 $in_function_header = 0;
414 $function_header_full_indent = 0;
415 $prev = $line;
416 next line;
417 } elsif ($picky && ! (/^\t/ && $function_header_full_indent != 0)) {
419 err("continuation line should be indented by 4 spaces");
424 # If this matches something of form "foo(", it's probably a function
425 # definition, unless it ends with ") bar;", in which case it's a declaration
426 # that uses a macro to generate the type.
428 if (/^\w+\(/ && !/\) \w+;/) {
429 $in_function_header = 1;
430 if (/\($/) {
431 $function_header_full_indent = 1;
434 if ($in_function_header && /^{$/) {
435 $in_function_header = 0;
436 $function_header_full_indent = 0;
437 $in_function = 1;
439 if ($in_function_header && /\);$/) {
440 $in_function_header = 0;
441 $function_header_full_indent = 0;
443 if ($in_function_header && /{$/ ) {
444 if ($picky) {
445 err("opening brace on same line as function header");
447 $in_function_header = 0;
448 $function_header_full_indent = 0;
449 $in_function = 1;
450 next line;
453 if ($in_warlock_comment && /\*\//) {
454 $in_warlock_comment = 0;
455 $prev = $line;
456 next line;
459 # a blank line terminates the declarations within a function.
460 # XXX - but still a problem in sub-blocks.
461 if ($in_declaration && /^$/) {
462 $in_declaration = 0;
465 if ($comment_done) {
466 $in_comment = 0;
467 $in_header_comment = 0;
468 $comment_done = 0;
470 # does this looks like the start of a block comment?
471 if (/$hdr_comment_start/) {
472 if (!/^\t*\/\*/) {
473 err("block comment not indented by tabs");
475 $in_comment = 1;
476 /^(\s*)\//;
477 $comment_prefix = $1;
478 if ($comment_prefix eq "") {
479 $in_header_comment = 1;
481 $prev = $line;
482 next line;
484 # are we still in the block comment?
485 if ($in_comment) {
486 if (/^$comment_prefix \*\/$/) {
487 $comment_done = 1;
488 } elsif (/\*\//) {
489 $comment_done = 1;
490 err("improper block comment close")
491 unless ($ignore_hdr_comment && $in_header_comment);
492 } elsif (!/^$comment_prefix \*[ \t]/ &&
493 !/^$comment_prefix \*$/) {
494 err("improper block comment")
495 unless ($ignore_hdr_comment && $in_header_comment);
499 if ($in_header_comment && $ignore_hdr_comment) {
500 $prev = $line;
501 next line;
504 # check for errors that might occur in comments and in code.
506 # allow spaces to be used to draw pictures in all comments.
507 if (/[^ ] / && !/".* .*"/ && !$in_comment) {
508 err("spaces instead of tabs");
510 if (/^ / && !/^ \*[ \t\/]/ && !/^ \*$/ &&
511 (!/^ (\w|\.)/ || $in_function != 0)) {
512 err("indent by spaces instead of tabs");
514 if (/^\t+ [^ \t\*]/ || /^\t+ \S/ || /^\t+ \S/) {
515 err("continuation line not indented by 4 spaces");
517 if (/$warlock_re/ && !/\*\//) {
518 $in_warlock_comment = 1;
519 $prev = $line;
520 next line;
522 if (/^\s*\/\*./ && !/^\s*\/\*.*\*\// && !/$hdr_comment_start/) {
523 err("improper first line of block comment");
526 if ($in_comment) { # still in comment, don't do further checks
527 $prev = $line;
528 next line;
531 if ((/[^(]\/\*\S/ || /^\/\*\S/) &&
532 !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
533 err("missing blank after open comment");
535 if (/\S\*\/[^)]|\S\*\/$/ &&
536 !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
537 err("missing blank before close comment");
539 if (/\/\/\S/) { # C++ comments
540 err("missing blank after start comment");
542 # check for unterminated single line comments, but allow them when
543 # they are used to comment out the argument list of a function
544 # declaration.
545 if (/\S.*\/\*/ && !/\S.*\/\*.*\*\// && !/\(\/\*/) {
546 err("unterminated single line comment");
549 if (/^(#else|#endif|#include)(.*)$/) {
550 $prev = $line;
551 if ($picky) {
552 my $directive = $1;
553 my $clause = $2;
554 # Enforce ANSI rules for #else and #endif: no noncomment
555 # identifiers are allowed after #endif or #else. Allow
556 # C++ comments since they seem to be a fact of life.
557 if ((($1 eq "#endif") || ($1 eq "#else")) &&
558 ($clause ne "") &&
559 (!($clause =~ /^\s+\/\*.*\*\/$/)) &&
560 (!($clause =~ /^\s+\/\/.*$/))) {
561 err("non-comment text following " .
562 "$directive (or malformed $directive " .
563 "directive)");
566 next line;
570 # delete any comments and check everything else. Note that
571 # ".*?" is a non-greedy match, so that we don't get confused by
572 # multiple comments on the same line.
574 s/\/\*.*?\*\//\x01/g;
575 s/\/\/.*$/\x01/; # C++ comments
577 # delete any trailing whitespace; we have already checked for that.
578 s/\s*$//;
580 # following checks do not apply to text in comments.
582 if (/[^<>\s][!<>=]=/ || /[^<>][!<>=]=[^\s,]/ ||
583 (/[^->]>[^,=>\s]/ && !/[^->]>$/) ||
584 (/[^<]<[^,=<\s]/ && !/[^<]<$/) ||
585 /[^<\s]<[^<]/ || /[^->\s]>[^>]/) {
586 err("missing space around relational operator");
588 if (/\S>>=/ || /\S<<=/ || />>=\S/ || /<<=\S/ || /\S[-+*\/&|^%]=/ ||
589 (/[^-+*\/&|^%!<>=\s]=[^=]/ && !/[^-+*\/&|^%!<>=\s]=$/) ||
590 (/[^!<>=]=[^=\s]/ && !/[^!<>=]=$/)) {
591 # XXX - should only check this for C++ code
592 # XXX - there are probably other forms that should be allowed
593 if (!/\soperator=/) {
594 err("missing space around assignment operator");
597 if (/[,;]\S/ && !/\bfor \(;;\)/) {
598 err("comma or semicolon followed by non-blank");
600 # allow "for" statements to have empty "while" clauses
601 if (/\s[,;]/ && !/^[\t]+;$/ && !/^\s*for \([^;]*; ;[^;]*\)/) {
602 err("comma or semicolon preceded by blank");
604 if (/^\s*(&&|\|\|)/) {
605 err("improper boolean continuation");
607 if (/\S *(&&|\|\|)/ || /(&&|\|\|) *\S/) {
608 err("more than one space around boolean operator");
610 if (/\b(for|if|while|switch|sizeof|return|case)\(/) {
611 err("missing space between keyword and paren");
613 if (/(\b(for|if|while|switch|return)\b.*){2,}/ && !/^#define/) {
614 # multiple "case" and "sizeof" allowed
615 err("more than one keyword on line");
617 if (/\b(for|if|while|switch|sizeof|return|case)\s\s+\(/ &&
618 !/^#if\s+\(/) {
619 err("extra space between keyword and paren");
621 # try to detect "func (x)" but not "if (x)" or
622 # "#define foo (x)" or "int (*func)();"
623 if (/\w\s\(/) {
624 my $s = $_;
625 # strip off all keywords on the line
626 s/\b(for|if|while|switch|return|case|sizeof)\s\(/XXX(/g;
627 s/#elif\s\(/XXX(/g;
628 s/^#define\s+\w+\s+\(/XXX(/;
629 # do not match things like "void (*f)();"
630 # or "typedef void (func_t)();"
631 s/\w\s\(+\*/XXX(*/g;
632 s/\b($typename|void)\s+\(+/XXX(/og;
633 if (/\w\s\(/) {
634 err("extra space between function name and left paren");
636 $_ = $s;
638 # try to detect "int foo(x)", but not "extern int foo(x);"
639 # XXX - this still trips over too many legitimate things,
640 # like "int foo(x,\n\ty);"
641 # if (/^(\w+(\s|\*)+)+\w+\(/ && !/\)[;,](\s|\x01)*$/ &&
642 # !/^(extern|static)\b/) {
643 # err("return type of function not on separate line");
645 # this is a close approximation
646 if (/^(\w+(\s|\*)+)+\w+\(.*\)(\s|\x01)*$/ &&
647 !/^(extern|static)\b/) {
648 err("return type of function not on separate line");
650 if (/^#define /) {
651 err("#define followed by space instead of tab");
653 if (/^\s*return\W[^;]*;/ && !/^\s*return\s*\(.*\);/) {
654 err("unparenthesized return expression");
656 if (/\bsizeof\b/ && !/\bsizeof\s*\(.*\)/) {
657 err("unparenthesized sizeof expression");
659 if (/\(\s/) {
660 err("whitespace after left paren");
662 # Allow "for" statements to have empty "continue" clauses.
663 # Allow right paren on its own line unless we're being picky (-p).
664 if (/\s\)/ && !/^\s*for \([^;]*;[^;]*; \)/ && ($picky || !/^\s*\)/)) {
665 err("whitespace before right paren");
667 if (/^\s*\(void\)[^ ]/) {
668 err("missing space after (void) cast");
670 if (/\S\{/ && !/\{\{/) {
671 err("missing space before left brace");
673 if ($in_function && /^\s+{/ &&
674 ($prev =~ /\)\s*$/ || $prev =~ /\bstruct\s+\w+$/)) {
675 err("left brace starting a line");
677 if (/}(else|while)/) {
678 err("missing space after right brace");
680 if (/}\s\s+(else|while)/) {
681 err("extra space after right brace");
683 if (/\b_VOID\b|\bVOID\b|\bSTATIC\b/) {
684 err("obsolete use of VOID or STATIC");
686 if (/\b$typename\*/o) {
687 err("missing space between type name and *");
689 if (/^\s+#/) {
690 err("preprocessor statement not in column 1");
692 if (/^#\s/) {
693 err("blank after preprocessor #");
695 if (/!\s*(strcmp|strncmp|bcmp)\s*\(/) {
696 err("don't use boolean ! with comparison functions");
700 # We completely ignore, for purposes of indentation:
701 # * lines outside of functions
702 # * preprocessor lines
704 if ($check_continuation && $in_function && !$in_cpp) {
705 process_indent($_);
707 if ($picky) {
708 # try to detect spaces after casts, but allow (e.g.)
709 # "sizeof (int) + 1", "void (*funcptr)(int) = foo;", and
710 # "int foo(int) __NORETURN;"
711 if ((/^\($typename( \*+)?\)\s/o ||
712 /\W\($typename( \*+)?\)\s/o) &&
713 !/sizeof\s*\($typename( \*)?\)\s/o &&
714 !/\($typename( \*+)?\)\s+=[^=]/o) {
715 err("space after cast");
717 if (/\b$typename\s*\*\s/o &&
718 !/\b$typename\s*\*\s+const\b/o) {
719 err("unary * followed by space");
722 if ($check_posix_types) {
723 # try to detect old non-POSIX types.
724 # POSIX requires all non-standard typedefs to end in _t,
725 # but historically these have been used.
726 if (/\b(unchar|ushort|uint|ulong|u_int|u_short|u_long|u_char|quad)\b/) {
727 err("non-POSIX typedef $1 used: use $old2posix{$1} instead");
730 if ($heuristic) {
731 # cannot check this everywhere due to "struct {\n...\n} foo;"
732 if ($in_function && !$in_declaration &&
733 /}./ && !/}\s+=/ && !/{.*}[;,]$/ && !/}(\s|\x01)*$/ &&
734 !/} (else|while)/ && !/}}/) {
735 err("possible bad text following right brace");
737 # cannot check this because sub-blocks in
738 # the middle of code are ok
739 if ($in_function && /^\s+{/) {
740 err("possible left brace starting a line");
743 if (/^\s*else\W/) {
744 if ($prev =~ /^\s*}$/) {
745 err_prefix($prev,
746 "else and right brace should be on same line");
749 $prev = $line;
752 if ($prev eq "") {
753 err("last line in file is blank");
759 # Continuation-line checking
761 # The rest of this file contains the code for the continuation checking
762 # engine. It's a pretty simple state machine which tracks the expression
763 # depth (unmatched '('s and '['s).
765 # Keep in mind that the argument to process_indent() has already been heavily
766 # processed; all comments have been replaced by control-A, and the contents of
767 # strings and character constants have been elided.
770 my $cont_in; # currently inside of a continuation
771 my $cont_off; # skipping an initializer or definition
772 my $cont_noerr; # suppress cascading errors
773 my $cont_start; # the line being continued
774 my $cont_base; # the base indentation
775 my $cont_first; # this is the first line of a statement
776 my $cont_multiseg; # this continuation has multiple segments
778 my $cont_special; # this is a C statement (if, for, etc.)
779 my $cont_macro; # this is a macro
780 my $cont_case; # this is a multi-line case
782 my @cont_paren; # the stack of unmatched ( and [s we've seen
785 reset_indent()
787 $cont_in = 0;
788 $cont_off = 0;
792 delabel($)
795 # replace labels with tabs. Note that there may be multiple
796 # labels on a line.
798 local $_ = $_[0];
800 while (/^(\t*)( *(?:(?:\w+\s*)|(?:case\b[^:]*)): *)(.*)$/) {
801 my ($pre_tabs, $label, $rest) = ($1, $2, $3);
802 $_ = $pre_tabs;
803 while ($label =~ s/^([^\t]*)(\t+)//) {
804 $_ .= "\t" x (length($2) + length($1) / 8);
806 $_ .= ("\t" x (length($label) / 8)).$rest;
809 return ($_);
813 process_indent($)
815 require strict;
816 local $_ = $_[0]; # preserve the global $_
818 s/\x01//g; # No comments
819 s/\s+$//; # Strip trailing whitespace
821 return if (/^$/); # skip empty lines
823 # regexps used below; keywords taking (), macros, and continued cases
824 my $special = '(?:(?:\}\s*)?else\s+)?(?:if|for|while|switch)\b';
825 my $macro = '[A-Z_][A-Z_0-9]*\(';
826 my $case = 'case\b[^:]*$';
828 # skip over enumerations, array definitions, initializers, etc.
829 if ($cont_off <= 0 && !/^\s*$special/ &&
830 (/(?:(?:\b(?:enum|struct|union)\s*[^\{]*)|(?:\s+=\s*)){/ ||
831 (/^\s*{/ && $prev =~ /=\s*(?:\/\*.*\*\/\s*)*$/))) {
832 $cont_in = 0;
833 $cont_off = tr/{/{/ - tr/}/}/;
834 return;
836 if ($cont_off) {
837 $cont_off += tr/{/{/ - tr/}/}/;
838 return;
841 if (!$cont_in) {
842 $cont_start = $line;
844 if (/^\t* /) {
845 err("non-continuation indented 4 spaces");
846 $cont_noerr = 1; # stop reporting
848 $_ = delabel($_); # replace labels with tabs
850 # check if the statement is complete
851 return if (/^\s*\}?$/);
852 return if (/^\s*\}?\s*else\s*\{?$/);
853 return if (/^\s*do\s*\{?$/);
854 return if (/{$/);
855 return if (/}[,;]?$/);
857 # Allow macros on their own lines
858 return if (/^\s*[A-Z_][A-Z_0-9]*$/);
860 # cases we don't deal with, generally non-kosher
861 if (/{/) {
862 err("stuff after {");
863 return;
866 # Get the base line, and set up the state machine
867 /^(\t*)/;
868 $cont_base = $1;
869 $cont_in = 1;
870 @cont_paren = ();
871 $cont_first = 1;
872 $cont_multiseg = 0;
874 # certain things need special processing
875 $cont_special = /^\s*$special/? 1 : 0;
876 $cont_macro = /^\s*$macro/? 1 : 0;
877 $cont_case = /^\s*$case/? 1 : 0;
878 } else {
879 $cont_first = 0;
881 # Strings may be pulled back to an earlier (half-)tabstop
882 unless ($cont_noerr || /^$cont_base / ||
883 (/^\t*(?: )?(?:gettext\()?\"/ && !/^$cont_base\t/)) {
884 err_prefix($cont_start,
885 "continuation should be indented 4 spaces");
889 my $rest = $_; # keeps the remainder of the line
892 # The split matches 0 characters, so that each 'special' character
893 # is processed separately. Parens and brackets are pushed and
894 # popped off the @cont_paren stack. For normal processing, we wait
895 # until a ; or { terminates the statement. "special" processing
896 # (if/for/while/switch) is allowed to stop when the stack empties,
897 # as is macro processing. Case statements are terminated with a :
898 # and an empty paren stack.
900 foreach $_ (split /[^\(\)\[\]\{\}\;\:]*/) {
901 next if (length($_) == 0);
903 # rest contains the remainder of the line
904 my $rxp = "[^\Q$_\E]*\Q$_\E";
905 $rest =~ s/^$rxp//;
907 if (/\(/ || /\[/) {
908 push @cont_paren, $_;
909 } elsif (/\)/ || /\]/) {
910 my $cur = $_;
911 tr/\)\]/\(\[/;
913 my $old = (pop @cont_paren);
914 if (!defined($old)) {
915 err("unexpected '$cur'");
916 $cont_in = 0;
917 last;
918 } elsif ($old ne $_) {
919 err("'$cur' mismatched with '$old'");
920 $cont_in = 0;
921 last;
925 # If the stack is now empty, do special processing
926 # for if/for/while/switch and macro statements.
928 next if (@cont_paren != 0);
929 if ($cont_special) {
930 if ($rest =~ /^\s*{?$/) {
931 $cont_in = 0;
932 last;
934 if ($rest =~ /^\s*;$/) {
935 err("empty if/for/while body ".
936 "not on its own line");
937 $cont_in = 0;
938 last;
940 if (!$cont_first && $cont_multiseg == 1) {
941 err_prefix($cont_start,
942 "multiple statements continued ".
943 "over multiple lines");
944 $cont_multiseg = 2;
945 } elsif ($cont_multiseg == 0) {
946 $cont_multiseg = 1;
948 # We've finished this section, start
949 # processing the next.
950 goto section_ended;
952 if ($cont_macro) {
953 if ($rest =~ /^$/) {
954 $cont_in = 0;
955 last;
958 } elsif (/\;/) {
959 if ($cont_case) {
960 err("unexpected ;");
961 } elsif (!$cont_special) {
962 err("unexpected ;") if (@cont_paren != 0);
963 if (!$cont_first && $cont_multiseg == 1) {
964 err_prefix($cont_start,
965 "multiple statements continued ".
966 "over multiple lines");
967 $cont_multiseg = 2;
968 } elsif ($cont_multiseg == 0) {
969 $cont_multiseg = 1;
971 if ($rest =~ /^$/) {
972 $cont_in = 0;
973 last;
975 if ($rest =~ /^\s*special/) {
976 err("if/for/while/switch not started ".
977 "on its own line");
979 goto section_ended;
981 } elsif (/\{/) {
982 err("{ while in parens/brackets") if (@cont_paren != 0);
983 err("stuff after {") if ($rest =~ /[^\s}]/);
984 $cont_in = 0;
985 last;
986 } elsif (/\}/) {
987 err("} while in parens/brackets") if (@cont_paren != 0);
988 if (!$cont_special && $rest !~ /^\s*(while|else)\b/) {
989 if ($rest =~ /^$/) {
990 err("unexpected }");
991 } else {
992 err("stuff after }");
994 $cont_in = 0;
995 last;
997 } elsif (/\:/ && $cont_case && @cont_paren == 0) {
998 err("stuff after multi-line case") if ($rest !~ /$^/);
999 $cont_in = 0;
1000 last;
1002 next;
1003 section_ended:
1004 # End of a statement or if/while/for loop. Reset
1005 # cont_special and cont_macro based on the rest of the
1006 # line.
1007 $cont_special = ($rest =~ /^\s*$special/)? 1 : 0;
1008 $cont_macro = ($rest =~ /^\s*$macro/)? 1 : 0;
1009 $cont_case = 0;
1010 next;
1012 $cont_noerr = 0 if (!$cont_in);