]> git.proxmox.com Git - mirror_zfs.git/blob - scripts/cstyle.pl
Fix cstyle.pl warnings
[mirror_zfs.git] / scripts / cstyle.pl
1 #!/usr/bin/perl -w
2 #
3 # CDDL HEADER START
4 #
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.
8 #
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.
13 #
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]
19 #
20 # CDDL HEADER END
21 #
22 #
23 # Copyright 2008 Sun Microsystems, Inc. All rights reserved.
24 # Use is subject to license terms.
25 #
26 # @(#)cstyle 1.58 98/09/09 (from shannon)
27 #ident "%Z%%M% %I% %E% SMI"
28 #
29 # cstyle - check for some common stylistic errors.
30 #
31 # cstyle is a sort of "lint" for C coding style.
32 # It attempts to check for the style used in the
33 # kernel, sometimes known as "Bill Joy Normal Form".
34 #
35 # There's a lot this can't check for, like proper indentation
36 # of code blocks. There's also a lot more this could check for.
37 #
38 # A note to the non perl literate:
39 #
40 # perl regular expressions are pretty much like egrep
41 # regular expressions, with the following special symbols
42 #
43 # \s any space character
44 # \S any non-space character
45 # \w any "word" character [a-zA-Z0-9_]
46 # \W any non-word character
47 # \d a digit [0-9]
48 # \D a non-digit
49 # \b word boundary (between \w and \W)
50 # \B non-word boundary
51 #
52
53 require 5.0;
54 use IO::File;
55 use Getopt::Std;
56 use strict;
57
58 my $usage =
59 "usage: cstyle [-chpvCP] [-o constructs] file ...
60 -c check continuation indentation inside functions
61 -h perform heuristic checks that are sometimes wrong
62 -p perform some of the more picky checks
63 -v verbose
64 -C don't check anything in header block comments
65 -P check for use of non-POSIX types
66 -o constructs
67 allow a comma-seperated list of optional constructs:
68 doxygen allow doxygen-style block comments (/** /*!)
69 splint allow splint-style lint comments (/*@ ... @*/)
70 ";
71
72 my %opts;
73
74 if (!getopts("cho:pvCP", \%opts)) {
75 print $usage;
76 exit 2;
77 }
78
79 my $check_continuation = $opts{'c'};
80 my $heuristic = $opts{'h'};
81 my $picky = $opts{'p'};
82 my $verbose = $opts{'v'};
83 my $ignore_hdr_comment = $opts{'C'};
84 my $check_posix_types = $opts{'P'};
85
86 my $doxygen_comments = 0;
87 my $splint_comments = 0;
88
89 if (defined($opts{'o'})) {
90 for my $x (split /,/, $opts{'o'}) {
91 if ($x eq "doxygen") {
92 $doxygen_comments = 1;
93 } elsif ($x eq "splint") {
94 $splint_comments = 1;
95 } else {
96 print "cstyle: unrecognized construct \"$x\"\n";
97 print $usage;
98 exit 2;
99 }
100 }
101 }
102
103 my ($filename, $line, $prev); # shared globals
104
105 my $fmt;
106 my $hdr_comment_start;
107
108 if ($verbose) {
109 $fmt = "%s: %d: %s\n%s\n";
110 } else {
111 $fmt = "%s: %d: %s\n";
112 }
113
114 if ($doxygen_comments) {
115 # doxygen comments look like "/*!" or "/**"; allow them.
116 $hdr_comment_start = qr/^\s*\/\*[\!\*]?$/;
117 } else {
118 $hdr_comment_start = qr/^\s*\/\*$/;
119 }
120
121 # Note, following must be in single quotes so that \s and \w work right.
122 my $typename = '(int|char|short|long|unsigned|float|double' .
123 '|\w+_t|struct\s+\w+|union\s+\w+|FILE)';
124
125 # mapping of old types to POSIX compatible types
126 my %old2posix = (
127 'unchar' => 'uchar_t',
128 'ushort' => 'ushort_t',
129 'uint' => 'uint_t',
130 'ulong' => 'ulong_t',
131 'u_int' => 'uint_t',
132 'u_short' => 'ushort_t',
133 'u_long' => 'ulong_t',
134 'u_char' => 'uchar_t',
135 'quad' => 'quad_t'
136 );
137
138 my $lint_re = qr/\/\*(?:
139 ARGSUSED[0-9]*|NOTREACHED|LINTLIBRARY|VARARGS[0-9]*|
140 CONSTCOND|CONSTANTCOND|CONSTANTCONDITION|EMPTY|
141 FALLTHRU|FALLTHROUGH|LINTED.*?|PRINTFLIKE[0-9]*|
142 PROTOLIB[0-9]*|SCANFLIKE[0-9]*|CSTYLED.*?
143 )\*\//x;
144
145 my $splint_re = qr/\/\*@.*?@\*\//x;
146
147 my $warlock_re = qr/\/\*\s*(?:
148 VARIABLES\ PROTECTED\ BY|
149 MEMBERS\ PROTECTED\ BY|
150 ALL\ MEMBERS\ PROTECTED\ BY|
151 READ-ONLY\ VARIABLES:|
152 READ-ONLY\ MEMBERS:|
153 VARIABLES\ READABLE\ WITHOUT\ LOCK:|
154 MEMBERS\ READABLE\ WITHOUT\ LOCK:|
155 LOCKS\ COVERED\ BY|
156 LOCK\ UNNEEDED\ BECAUSE|
157 LOCK\ NEEDED:|
158 LOCK\ HELD\ ON\ ENTRY:|
159 READ\ LOCK\ HELD\ ON\ ENTRY:|
160 WRITE\ LOCK\ HELD\ ON\ ENTRY:|
161 LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
162 READ\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
163 WRITE\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
164 LOCK\ RELEASED\ AS\ SIDE\ EFFECT:|
165 LOCK\ UPGRADED\ AS\ SIDE\ EFFECT:|
166 LOCK\ DOWNGRADED\ AS\ SIDE\ EFFECT:|
167 FUNCTIONS\ CALLED\ THROUGH\ POINTER|
168 FUNCTIONS\ CALLED\ THROUGH\ MEMBER|
169 LOCK\ ORDER:
170 )/x;
171
172 my $err_stat = 0; # exit status
173
174 if ($#ARGV >= 0) {
175 foreach my $arg (@ARGV) {
176 my $fh = new IO::File $arg, "r";
177 if (!defined($fh)) {
178 printf "%s: can not open\n", $arg;
179 } else {
180 &cstyle($arg, $fh);
181 close $fh;
182 }
183 }
184 } else {
185 &cstyle("<stdin>", *STDIN);
186 }
187 exit $err_stat;
188
189 my $no_errs = 0; # set for CSTYLED-protected lines
190
191 sub err($) {
192 my ($error) = @_;
193 unless ($no_errs) {
194 if ($verbose) {
195 printf $fmt, $filename, $., $error, $line;
196 } else {
197 printf $fmt, $filename, $., $error;
198 }
199 $err_stat = 1;
200 }
201 }
202
203 sub err_prefix($$) {
204 my ($prevline, $error) = @_;
205 my $out = $prevline."\n".$line;
206 unless ($no_errs) {
207 if ($verbose) {
208 printf $fmt, $filename, $., $error, $out;
209 } else {
210 printf $fmt, $filename, $., $error;
211 }
212 $err_stat = 1;
213 }
214 }
215
216 sub err_prev($) {
217 my ($error) = @_;
218 unless ($no_errs) {
219 if ($verbose) {
220 printf $fmt, $filename, $. - 1, $error, $prev;
221 } else {
222 printf $fmt, $filename, $. - 1, $error;
223 }
224 $err_stat = 1;
225 }
226 }
227
228 sub cstyle($$) {
229
230 my ($fn, $filehandle) = @_;
231 $filename = $fn; # share it globally
232
233 my $in_cpp = 0;
234 my $next_in_cpp = 0;
235
236 my $in_comment = 0;
237 my $in_header_comment = 0;
238 my $comment_done = 0;
239 my $in_warlock_comment = 0;
240 my $in_function = 0;
241 my $in_function_header = 0;
242 my $in_declaration = 0;
243 my $note_level = 0;
244 my $nextok = 0;
245 my $nocheck = 0;
246
247 my $in_string = 0;
248
249 my ($okmsg, $comment_prefix);
250
251 $line = '';
252 $prev = '';
253 reset_indent();
254
255 line: while (<$filehandle>) {
256 s/\r?\n$//; # strip return and newline
257
258 # save the original line, then remove all text from within
259 # double or single quotes, we do not want to check such text.
260
261 $line = $_;
262
263 #
264 # C allows strings to be continued with a backslash at the end of
265 # the line. We translate that into a quoted string on the previous
266 # line followed by an initial quote on the next line.
267 #
268 # (we assume that no-one will use backslash-continuation with character
269 # constants)
270 #
271 $_ = '"' . $_ if ($in_string && !$nocheck && !$in_comment);
272
273 #
274 # normal strings and characters
275 #
276 s/'([^\\']|\\[^xX0]|\\0[0-9]*|\\[xX][0-9a-fA-F]*)'/''/g;
277 s/"([^\\"]|\\.)*"/\"\"/g;
278
279 #
280 # detect string continuation
281 #
282 if ($nocheck || $in_comment) {
283 $in_string = 0;
284 } else {
285 #
286 # Now that all full strings are replaced with "", we check
287 # for unfinished strings continuing onto the next line.
288 #
289 $in_string =
290 (s/([^"](?:"")*)"([^\\"]|\\.)*\\$/$1""/ ||
291 s/^("")*"([^\\"]|\\.)*\\$/""/);
292 }
293
294 #
295 # figure out if we are in a cpp directive
296 #
297 $in_cpp = $next_in_cpp || /^\s*#/; # continued or started
298 $next_in_cpp = $in_cpp && /\\$/; # only if continued
299
300 # strip off trailing backslashes, which appear in long macros
301 s/\s*\\$//;
302
303 # an /* END CSTYLED */ comment ends a no-check block.
304 if ($nocheck) {
305 if (/\/\* *END *CSTYLED *\*\//) {
306 $nocheck = 0;
307 } else {
308 reset_indent();
309 next line;
310 }
311 }
312
313 # a /*CSTYLED*/ comment indicates that the next line is ok.
314 if ($nextok) {
315 if ($okmsg) {
316 err($okmsg);
317 }
318 $nextok = 0;
319 $okmsg = 0;
320 if (/\/\* *CSTYLED.*\*\//) {
321 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
322 $okmsg = $1;
323 $nextok = 1;
324 }
325 $no_errs = 1;
326 } elsif ($no_errs) {
327 $no_errs = 0;
328 }
329
330 # check length of line.
331 # first, a quick check to see if there is any chance of being too long.
332 if (($line =~ tr/\t/\t/) * 7 + length($line) > 80) {
333 # yes, there is a chance.
334 # replace tabs with spaces and check again.
335 my $eline = $line;
336 1 while $eline =~
337 s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
338 if (length($eline) > 80) {
339 err("line > 80 characters");
340 }
341 }
342
343 # ignore NOTE(...) annotations (assumes NOTE is on lines by itself).
344 if ($note_level || /\b_?NOTE\s*\(/) { # if in NOTE or this is NOTE
345 s/[^()]//g; # eliminate all non-parens
346 $note_level += s/\(//g - length; # update paren nest level
347 next;
348 }
349
350 # a /* BEGIN CSTYLED */ comment starts a no-check block.
351 if (/\/\* *BEGIN *CSTYLED *\*\//) {
352 $nocheck = 1;
353 }
354
355 # a /*CSTYLED*/ comment indicates that the next line is ok.
356 if (/\/\* *CSTYLED.*\*\//) {
357 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
358 $okmsg = $1;
359 $nextok = 1;
360 }
361 if (/\/\/ *CSTYLED/) {
362 /^.*\/\/ *CSTYLED *(.*)$/;
363 $okmsg = $1;
364 $nextok = 1;
365 }
366
367 # universal checks; apply to everything
368 if (/\t +\t/) {
369 err("spaces between tabs");
370 }
371 if (/ \t+ /) {
372 err("tabs between spaces");
373 }
374 if (/\s$/) {
375 err("space or tab at end of line");
376 }
377 if (/[^ \t(]\/\*/ && !/\w\(\/\*.*\*\/\);/) {
378 err("comment preceded by non-blank");
379 }
380
381 # is this the beginning or ending of a function?
382 # (not if "struct foo\n{\n")
383 if (/^{$/ && $prev =~ /\)\s*(const\s*)?(\/\*.*\*\/\s*)?\\?$/) {
384 $in_function = 1;
385 $in_declaration = 1;
386 $in_function_header = 0;
387 $prev = $line;
388 next line;
389 }
390 if (/^}\s*(\/\*.*\*\/\s*)*$/) {
391 if ($prev =~ /^\s*return\s*;/) {
392 err_prev("unneeded return at end of function");
393 }
394 $in_function = 0;
395 reset_indent(); # we don't check between functions
396 $prev = $line;
397 next line;
398 }
399 if (/^\w*\($/) {
400 $in_function_header = 1;
401 }
402
403 if ($in_warlock_comment && /\*\//) {
404 $in_warlock_comment = 0;
405 $prev = $line;
406 next line;
407 }
408
409 # a blank line terminates the declarations within a function.
410 # XXX - but still a problem in sub-blocks.
411 if ($in_declaration && /^$/) {
412 $in_declaration = 0;
413 }
414
415 if ($comment_done) {
416 $in_comment = 0;
417 $in_header_comment = 0;
418 $comment_done = 0;
419 }
420 # does this looks like the start of a block comment?
421 if (/$hdr_comment_start/) {
422 if (!/^\t*\/\*/) {
423 err("block comment not indented by tabs");
424 }
425 $in_comment = 1;
426 /^(\s*)\//;
427 $comment_prefix = $1;
428 if ($comment_prefix eq "") {
429 $in_header_comment = 1;
430 }
431 $prev = $line;
432 next line;
433 }
434 # are we still in the block comment?
435 if ($in_comment) {
436 if (/^$comment_prefix \*\/$/) {
437 $comment_done = 1;
438 } elsif (/\*\//) {
439 $comment_done = 1;
440 err("improper block comment close")
441 unless ($ignore_hdr_comment && $in_header_comment);
442 } elsif (!/^$comment_prefix \*[ \t]/ &&
443 !/^$comment_prefix \*$/) {
444 err("improper block comment")
445 unless ($ignore_hdr_comment && $in_header_comment);
446 }
447 }
448
449 if ($in_header_comment && $ignore_hdr_comment) {
450 $prev = $line;
451 next line;
452 }
453
454 # check for errors that might occur in comments and in code.
455
456 # allow spaces to be used to draw pictures in all comments.
457 if (/[^ ] / && !/".* .*"/ && !$in_comment) {
458 err("spaces instead of tabs");
459 }
460 if (/^ / && !/^ \*[ \t\/]/ && !/^ \*$/ &&
461 (!/^ \w/ || $in_function != 0)) {
462 err("indent by spaces instead of tabs");
463 }
464 if (/^\t+ [^ \t\*]/ || /^\t+ \S/ || /^\t+ \S/) {
465 err("continuation line not indented by 4 spaces");
466 }
467 if (/$warlock_re/ && !/\*\//) {
468 $in_warlock_comment = 1;
469 $prev = $line;
470 next line;
471 }
472 if (/^\s*\/\*./ && !/^\s*\/\*.*\*\// && !/$hdr_comment_start/) {
473 err("improper first line of block comment");
474 }
475
476 if ($in_comment) { # still in comment, don't do further checks
477 $prev = $line;
478 next line;
479 }
480
481 if ((/[^(]\/\*\S/ || /^\/\*\S/) &&
482 !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
483 err("missing blank after open comment");
484 }
485 if (/\S\*\/[^)]|\S\*\/$/ &&
486 !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
487 err("missing blank before close comment");
488 }
489 if (/\/\/\S/) { # C++ comments
490 err("missing blank after start comment");
491 }
492 # check for unterminated single line comments, but allow them when
493 # they are used to comment out the argument list of a function
494 # declaration.
495 if (/\S.*\/\*/ && !/\S.*\/\*.*\*\// && !/\(\/\*/) {
496 err("unterminated single line comment");
497 }
498
499 if (/^(#else|#endif|#include)(.*)$/) {
500 $prev = $line;
501 if ($picky) {
502 my $directive = $1;
503 my $clause = $2;
504 # Enforce ANSI rules for #else and #endif: no noncomment
505 # identifiers are allowed after #endif or #else. Allow
506 # C++ comments since they seem to be a fact of life.
507 if ((($1 eq "#endif") || ($1 eq "#else")) &&
508 ($clause ne "") &&
509 (!($clause =~ /^\s+\/\*.*\*\/$/)) &&
510 (!($clause =~ /^\s+\/\/.*$/))) {
511 err("non-comment text following " .
512 "$directive (or malformed $directive " .
513 "directive)");
514 }
515 }
516 next line;
517 }
518
519 #
520 # delete any comments and check everything else. Note that
521 # ".*?" is a non-greedy match, so that we don't get confused by
522 # multiple comments on the same line.
523 #
524 s/\/\*.*?\*\//\ 1/g;
525 s/\/\/.*$/\ 1/; # C++ comments
526
527 # delete any trailing whitespace; we have already checked for that.
528 s/\s*$//;
529
530 # following checks do not apply to text in comments.
531
532 if (/[^<>\s][!<>=]=/ || /[^<>][!<>=]=[^\s,]/ ||
533 (/[^->]>[^,=>\s]/ && !/[^->]>$/) ||
534 (/[^<]<[^,=<\s]/ && !/[^<]<$/) ||
535 /[^<\s]<[^<]/ || /[^->\s]>[^>]/) {
536 err("missing space around relational operator");
537 }
538 if (/\S>>=/ || /\S<<=/ || />>=\S/ || /<<=\S/ || /\S[-+*\/&|^%]=/ ||
539 (/[^-+*\/&|^%!<>=\s]=[^=]/ && !/[^-+*\/&|^%!<>=\s]=$/) ||
540 (/[^!<>=]=[^=\s]/ && !/[^!<>=]=$/)) {
541 # XXX - should only check this for C++ code
542 # XXX - there are probably other forms that should be allowed
543 if (!/\soperator=/) {
544 err("missing space around assignment operator");
545 }
546 }
547 if (/[,;]\S/ && !/\bfor \(;;\)/) {
548 err("comma or semicolon followed by non-blank");
549 }
550 # allow "for" statements to have empty "while" clauses
551 if (/\s[,;]/ && !/^[\t]+;$/ && !/^\s*for \([^;]*; ;[^;]*\)/) {
552 err("comma or semicolon preceded by blank");
553 }
554 if (/^\s*(&&|\|\|)/) {
555 err("improper boolean continuation");
556 }
557 if (/\S *(&&|\|\|)/ || /(&&|\|\|) *\S/) {
558 err("more than one space around boolean operator");
559 }
560 if (/\b(for|if|while|switch|sizeof|return|case)\(/) {
561 err("missing space between keyword and paren");
562 }
563 if (/(\b(for|if|while|switch|return)\b.*){2,}/ && !/^#define/) {
564 # multiple "case" and "sizeof" allowed
565 err("more than one keyword on line");
566 }
567 if (/\b(for|if|while|switch|sizeof|return|case)\s\s+\(/ &&
568 !/^#if\s+\(/) {
569 err("extra space between keyword and paren");
570 }
571 # try to detect "func (x)" but not "if (x)" or
572 # "#define foo (x)" or "int (*func)();"
573 if (/\w\s\(/) {
574 my $s = $_;
575 # strip off all keywords on the line
576 s/\b(for|if|while|switch|return|case|sizeof)\s\(/XXX(/g;
577 s/#elif\s\(/XXX(/g;
578 s/^#define\s+\w+\s+\(/XXX(/;
579 # do not match things like "void (*f)();"
580 # or "typedef void (func_t)();"
581 s/\w\s\(+\*/XXX(*/g;
582 s/\b($typename|void)\s+\(+/XXX(/og;
583 if (/\w\s\(/) {
584 err("extra space between function name and left paren");
585 }
586 $_ = $s;
587 }
588 # try to detect "int foo(x)", but not "extern int foo(x);"
589 # XXX - this still trips over too many legitimate things,
590 # like "int foo(x,\n\ty);"
591 # if (/^(\w+(\s|\*)+)+\w+\(/ && !/\)[;,](\s|\ 1)*$/ &&
592 # !/^(extern|static)\b/) {
593 # err("return type of function not on separate line");
594 # }
595 # this is a close approximation
596 if (/^(\w+(\s|\*)+)+\w+\(.*\)(\s|\ 1)*$/ &&
597 !/^(extern|static)\b/) {
598 err("return type of function not on separate line");
599 }
600 if (/^#define /) {
601 err("#define followed by space instead of tab");
602 }
603 if (/^\s*return\W[^;]*;/ && !/^\s*return\s*\(.*\);/) {
604 err("unparenthesized return expression");
605 }
606 if (/\bsizeof\b/ && !/\bsizeof\s*\(.*\)/) {
607 err("unparenthesized sizeof expression");
608 }
609 if (/\(\s/) {
610 err("whitespace after left paren");
611 }
612 # Allow "for" statements to have empty "continue" clauses.
613 # Allow right paren on its own line unless we're being picky (-p).
614 if (/\s\)/ && !/^\s*for \([^;]*;[^;]*; \)/ && ($picky || !/^\s*\)/)) {
615 err("whitespace before right paren");
616 }
617 if (/^\s*\(void\)[^ ]/) {
618 err("missing space after (void) cast");
619 }
620 if (/\S\{/ && !/\{\{/) {
621 err("missing space before left brace");
622 }
623 if ($in_function && /^\s+{/ &&
624 ($prev =~ /\)\s*$/ || $prev =~ /\bstruct\s+\w+$/)) {
625 err("left brace starting a line");
626 }
627 if (/}(else|while)/) {
628 err("missing space after right brace");
629 }
630 if (/}\s\s+(else|while)/) {
631 err("extra space after right brace");
632 }
633 if (/\b_VOID\b|\bVOID\b|\bSTATIC\b/) {
634 err("obsolete use of VOID or STATIC");
635 }
636 if (/\b$typename\*/o) {
637 err("missing space between type name and *");
638 }
639 if (/^\s+#/) {
640 err("preprocessor statement not in column 1");
641 }
642 if (/^#\s/) {
643 err("blank after preprocessor #");
644 }
645 if (/!\s*(strcmp|strncmp|bcmp)\s*\(/) {
646 err("don't use boolean ! with comparison functions");
647 }
648
649 #
650 # We completely ignore, for purposes of indentation:
651 # * lines outside of functions
652 # * preprocessor lines
653 #
654 if ($check_continuation && $in_function && !$in_cpp) {
655 process_indent($_);
656 }
657 if ($picky) {
658 # try to detect spaces after casts, but allow (e.g.)
659 # "sizeof (int) + 1", "void (*funcptr)(int) = foo;", and
660 # "int foo(int) __NORETURN;"
661 if ((/^\($typename( \*+)?\)\s/o ||
662 /\W\($typename( \*+)?\)\s/o) &&
663 !/sizeof\s*\($typename( \*)?\)\s/o &&
664 !/\($typename( \*+)?\)\s+=[^=]/o) {
665 err("space after cast");
666 }
667 if (/\b$typename\s*\*\s/o &&
668 !/\b$typename\s*\*\s+const\b/o) {
669 err("unary * followed by space");
670 }
671 }
672 if ($check_posix_types) {
673 # try to detect old non-POSIX types.
674 # POSIX requires all non-standard typedefs to end in _t,
675 # but historically these have been used.
676 if (/\b(unchar|ushort|uint|ulong|u_int|u_short|u_long|u_char|quad)\b/) {
677 err("non-POSIX typedef $1 used: use $old2posix{$1} instead");
678 }
679 }
680 if ($heuristic) {
681 # cannot check this everywhere due to "struct {\n...\n} foo;"
682 if ($in_function && !$in_declaration &&
683 /}./ && !/}\s+=/ && !/{.*}[;,]$/ && !/}(\s|\ 1)*$/ &&
684 !/} (else|while)/ && !/}}/) {
685 err("possible bad text following right brace");
686 }
687 # cannot check this because sub-blocks in
688 # the middle of code are ok
689 if ($in_function && /^\s+{/) {
690 err("possible left brace starting a line");
691 }
692 }
693 if (/^\s*else\W/) {
694 if ($prev =~ /^\s*}$/) {
695 err_prefix($prev,
696 "else and right brace should be on same line");
697 }
698 }
699 $prev = $line;
700 }
701
702 if ($prev eq "") {
703 err("last line in file is blank");
704 }
705
706 }
707
708 #
709 # Continuation-line checking
710 #
711 # The rest of this file contains the code for the continuation checking
712 # engine. It's a pretty simple state machine which tracks the expression
713 # depth (unmatched '('s and '['s).
714 #
715 # Keep in mind that the argument to process_indent() has already been heavily
716 # processed; all comments have been replaced by control-A, and the contents of
717 # strings and character constants have been elided.
718 #
719
720 my $cont_in; # currently inside of a continuation
721 my $cont_off; # skipping an initializer or definition
722 my $cont_noerr; # suppress cascading errors
723 my $cont_start; # the line being continued
724 my $cont_base; # the base indentation
725 my $cont_first; # this is the first line of a statement
726 my $cont_multiseg; # this continuation has multiple segments
727
728 my $cont_special; # this is a C statement (if, for, etc.)
729 my $cont_macro; # this is a macro
730 my $cont_case; # this is a multi-line case
731
732 my @cont_paren; # the stack of unmatched ( and [s we've seen
733
734 sub
735 reset_indent()
736 {
737 $cont_in = 0;
738 $cont_off = 0;
739 }
740
741 sub
742 delabel($)
743 {
744 #
745 # replace labels with tabs. Note that there may be multiple
746 # labels on a line.
747 #
748 local $_ = $_[0];
749
750 while (/^(\t*)( *(?:(?:\w+\s*)|(?:case\b[^:]*)): *)(.*)$/) {
751 my ($pre_tabs, $label, $rest) = ($1, $2, $3);
752 $_ = $pre_tabs;
753 while ($label =~ s/^([^\t]*)(\t+)//) {
754 $_ .= "\t" x (length($2) + length($1) / 8);
755 }
756 $_ .= ("\t" x (length($label) / 8)).$rest;
757 }
758
759 return ($_);
760 }
761
762 sub
763 process_indent($)
764 {
765 require strict;
766 local $_ = $_[0]; # preserve the global $_
767
768 s/\ 1//g; # No comments
769 s/\s+$//; # Strip trailing whitespace
770
771 return if (/^$/); # skip empty lines
772
773 # regexps used below; keywords taking (), macros, and continued cases
774 my $special = '(?:(?:\}\s*)?else\s+)?(?:if|for|while|switch)\b';
775 my $macro = '[A-Z_][A-Z_0-9]*\(';
776 my $case = 'case\b[^:]*$';
777
778 # skip over enumerations, array definitions, initializers, etc.
779 if ($cont_off <= 0 && !/^\s*$special/ &&
780 (/(?:(?:\b(?:enum|struct|union)\s*[^\{]*)|(?:\s+=\s*)){/ ||
781 (/^\s*{/ && $prev =~ /=\s*(?:\/\*.*\*\/\s*)*$/))) {
782 $cont_in = 0;
783 $cont_off = tr/{/{/ - tr/}/}/;
784 return;
785 }
786 if ($cont_off) {
787 $cont_off += tr/{/{/ - tr/}/}/;
788 return;
789 }
790
791 if (!$cont_in) {
792 $cont_start = $line;
793
794 if (/^\t* /) {
795 err("non-continuation indented 4 spaces");
796 $cont_noerr = 1; # stop reporting
797 }
798 $_ = delabel($_); # replace labels with tabs
799
800 # check if the statement is complete
801 return if (/^\s*\}?$/);
802 return if (/^\s*\}?\s*else\s*\{?$/);
803 return if (/^\s*do\s*\{?$/);
804 return if (/{$/);
805 return if (/}[,;]?$/);
806
807 # Allow macros on their own lines
808 return if (/^\s*[A-Z_][A-Z_0-9]*$/);
809
810 # cases we don't deal with, generally non-kosher
811 if (/{/) {
812 err("stuff after {");
813 return;
814 }
815
816 # Get the base line, and set up the state machine
817 /^(\t*)/;
818 $cont_base = $1;
819 $cont_in = 1;
820 @cont_paren = ();
821 $cont_first = 1;
822 $cont_multiseg = 0;
823
824 # certain things need special processing
825 $cont_special = /^\s*$special/? 1 : 0;
826 $cont_macro = /^\s*$macro/? 1 : 0;
827 $cont_case = /^\s*$case/? 1 : 0;
828 } else {
829 $cont_first = 0;
830
831 # Strings may be pulled back to an earlier (half-)tabstop
832 unless ($cont_noerr || /^$cont_base / ||
833 (/^\t*(?: )?(?:gettext\()?\"/ && !/^$cont_base\t/)) {
834 err_prefix($cont_start,
835 "continuation should be indented 4 spaces");
836 }
837 }
838
839 my $rest = $_; # keeps the remainder of the line
840
841 #
842 # The split matches 0 characters, so that each 'special' character
843 # is processed separately. Parens and brackets are pushed and
844 # popped off the @cont_paren stack. For normal processing, we wait
845 # until a ; or { terminates the statement. "special" processing
846 # (if/for/while/switch) is allowed to stop when the stack empties,
847 # as is macro processing. Case statements are terminated with a :
848 # and an empty paren stack.
849 #
850 foreach $_ (split /[^\(\)\[\]\{\}\;\:]*/) {
851 next if (length($_) == 0);
852
853 # rest contains the remainder of the line
854 my $rxp = "[^\Q$_\E]*\Q$_\E";
855 $rest =~ s/^$rxp//;
856
857 if (/\(/ || /\[/) {
858 push @cont_paren, $_;
859 } elsif (/\)/ || /\]/) {
860 my $cur = $_;
861 tr/\)\]/\(\[/;
862
863 my $old = (pop @cont_paren);
864 if (!defined($old)) {
865 err("unexpected '$cur'");
866 $cont_in = 0;
867 last;
868 } elsif ($old ne $_) {
869 err("'$cur' mismatched with '$old'");
870 $cont_in = 0;
871 last;
872 }
873
874 #
875 # If the stack is now empty, do special processing
876 # for if/for/while/switch and macro statements.
877 #
878 next if (@cont_paren != 0);
879 if ($cont_special) {
880 if ($rest =~ /^\s*{?$/) {
881 $cont_in = 0;
882 last;
883 }
884 if ($rest =~ /^\s*;$/) {
885 err("empty if/for/while body ".
886 "not on its own line");
887 $cont_in = 0;
888 last;
889 }
890 if (!$cont_first && $cont_multiseg == 1) {
891 err_prefix($cont_start,
892 "multiple statements continued ".
893 "over multiple lines");
894 $cont_multiseg = 2;
895 } elsif ($cont_multiseg == 0) {
896 $cont_multiseg = 1;
897 }
898 # We've finished this section, start
899 # processing the next.
900 goto section_ended;
901 }
902 if ($cont_macro) {
903 if ($rest =~ /^$/) {
904 $cont_in = 0;
905 last;
906 }
907 }
908 } elsif (/\;/) {
909 if ($cont_case) {
910 err("unexpected ;");
911 } elsif (!$cont_special) {
912 err("unexpected ;") if (@cont_paren != 0);
913 if (!$cont_first && $cont_multiseg == 1) {
914 err_prefix($cont_start,
915 "multiple statements continued ".
916 "over multiple lines");
917 $cont_multiseg = 2;
918 } elsif ($cont_multiseg == 0) {
919 $cont_multiseg = 1;
920 }
921 if ($rest =~ /^$/) {
922 $cont_in = 0;
923 last;
924 }
925 if ($rest =~ /^\s*special/) {
926 err("if/for/while/switch not started ".
927 "on its own line");
928 }
929 goto section_ended;
930 }
931 } elsif (/\{/) {
932 err("{ while in parens/brackets") if (@cont_paren != 0);
933 err("stuff after {") if ($rest =~ /[^\s}]/);
934 $cont_in = 0;
935 last;
936 } elsif (/\}/) {
937 err("} while in parens/brackets") if (@cont_paren != 0);
938 if (!$cont_special && $rest !~ /^\s*(while|else)\b/) {
939 if ($rest =~ /^$/) {
940 err("unexpected }");
941 } else {
942 err("stuff after }");
943 }
944 $cont_in = 0;
945 last;
946 }
947 } elsif (/\:/ && $cont_case && @cont_paren == 0) {
948 err("stuff after multi-line case") if ($rest !~ /$^/);
949 $cont_in = 0;
950 last;
951 }
952 next;
953 section_ended:
954 # End of a statement or if/while/for loop. Reset
955 # cont_special and cont_macro based on the rest of the
956 # line.
957 $cont_special = ($rest =~ /^\s*$special/)? 1 : 0;
958 $cont_macro = ($rest =~ /^\s*$macro/)? 1 : 0;
959 $cont_case = 0;
960 next;
961 }
962 $cont_noerr = 0 if (!$cont_in);
963 }