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