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 - check for some common stylistic errors.
27 #
28 # cstyle is a sort of "lint" for C coding style.
29 # It attempts to check for the style used in the
30 # kernel, sometimes known as "Bill Joy Normal Form".
31 #
32 # There's a lot this can't check for, like proper indentation
33 # of code blocks. There's also a lot more this could check for.
34 #
35 # A note to the non perl literate:
36 #
37 # perl regular expressions are pretty much like egrep
38 # regular expressions, with the following special symbols
39 #
40 # \s any space character
41 # \S any non-space character
42 # \w any "word" character [a-zA-Z0-9_]
43 # \W any non-word character
44 # \d a digit [0-9]
45 # \D a non-digit
46 # \b word boundary (between \w and \W)
47 # \B non-word boundary
48 #
49
50 require 5.0;
51 use IO::File;
52 use Getopt::Std;
53 use strict;
54
55 my $usage =
56 "usage: cstyle [-chpvCP] [-o constructs] file ...
57 -c check continuation indentation inside functions
58 -h perform heuristic checks that are sometimes wrong
59 -p perform some of the more picky checks
60 -v verbose
61 -C don't check anything in header block comments
62 -P check for use of non-POSIX types
63 -o constructs
64 allow a comma-seperated list of optional constructs:
65 doxygen allow doxygen-style block comments (/** /*!)
66 splint allow splint-style lint comments (/*@ ... @*/)
67 ";
68
69 my %opts;
70
71 if (!getopts("cho:pvCP", \%opts)) {
72 print $usage;
73 exit 2;
74 }
75
76 my $check_continuation = $opts{'c'};
77 my $heuristic = $opts{'h'};
78 my $picky = $opts{'p'};
79 my $verbose = $opts{'v'};
80 my $ignore_hdr_comment = $opts{'C'};
81 my $check_posix_types = $opts{'P'};
82
83 my $doxygen_comments = 0;
84 my $splint_comments = 0;
85
86 if (defined($opts{'o'})) {
87 for my $x (split /,/, $opts{'o'}) {
88 if ($x eq "doxygen") {
89 $doxygen_comments = 1;
90 } elsif ($x eq "splint") {
91 $splint_comments = 1;
92 } else {
93 print "cstyle: unrecognized construct \"$x\"\n";
94 print $usage;
95 exit 2;
96 }
97 }
98 }
99
100 my ($filename, $line, $prev); # shared globals
101
102 my $fmt;
103 my $hdr_comment_start;
104
105 if ($verbose) {
106 $fmt = "%s: %d: %s\n%s\n";
107 } else {
108 $fmt = "%s: %d: %s\n";
109 }
110
111 if ($doxygen_comments) {
112 # doxygen comments look like "/*!" or "/**"; allow them.
113 $hdr_comment_start = qr/^\s*\/\*[\!\*]?$/;
114 } else {
115 $hdr_comment_start = qr/^\s*\/\*$/;
116 }
117
118 # Note, following must be in single quotes so that \s and \w work right.
119 my $typename = '(int|char|short|long|unsigned|float|double' .
120 '|\w+_t|struct\s+\w+|union\s+\w+|FILE)';
121
122 # mapping of old types to POSIX compatible types
123 my %old2posix = (
124 'unchar' => 'uchar_t',
125 'ushort' => 'ushort_t',
126 'uint' => 'uint_t',
127 'ulong' => 'ulong_t',
128 'u_int' => 'uint_t',
129 'u_short' => 'ushort_t',
130 'u_long' => 'ulong_t',
131 'u_char' => 'uchar_t',
132 'quad' => 'quad_t'
133 );
134
135 my $lint_re = qr/\/\*(?:
136 ARGSUSED[0-9]*|NOTREACHED|LINTLIBRARY|VARARGS[0-9]*|
137 CONSTCOND|CONSTANTCOND|CONSTANTCONDITION|EMPTY|
138 FALLTHRU|FALLTHROUGH|LINTED.*?|PRINTFLIKE[0-9]*|
139 PROTOLIB[0-9]*|SCANFLIKE[0-9]*|CSTYLED.*?
140 )\*\//x;
141
142 my $splint_re = qr/\/\*@.*?@\*\//x;
143
144 my $warlock_re = qr/\/\*\s*(?:
145 VARIABLES\ PROTECTED\ BY|
146 MEMBERS\ PROTECTED\ BY|
147 ALL\ MEMBERS\ PROTECTED\ BY|
148 READ-ONLY\ VARIABLES:|
149 READ-ONLY\ MEMBERS:|
150 VARIABLES\ READABLE\ WITHOUT\ LOCK:|
151 MEMBERS\ READABLE\ WITHOUT\ LOCK:|
152 LOCKS\ COVERED\ BY|
153 LOCK\ UNNEEDED\ BECAUSE|
154 LOCK\ NEEDED:|
155 LOCK\ HELD\ ON\ ENTRY:|
156 READ\ LOCK\ HELD\ ON\ ENTRY:|
157 WRITE\ LOCK\ HELD\ ON\ ENTRY:|
158 LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
159 READ\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
160 WRITE\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
161 LOCK\ RELEASED\ AS\ SIDE\ EFFECT:|
162 LOCK\ UPGRADED\ AS\ SIDE\ EFFECT:|
163 LOCK\ DOWNGRADED\ AS\ SIDE\ EFFECT:|
164 FUNCTIONS\ CALLED\ THROUGH\ POINTER|
165 FUNCTIONS\ CALLED\ THROUGH\ MEMBER|
166 LOCK\ ORDER:
167 )/x;
168
169 my $err_stat = 0; # exit status
170
171 if ($#ARGV >= 0) {
172 foreach my $arg (@ARGV) {
173 my $fh = new IO::File $arg, "r";
174 if (!defined($fh)) {
175 printf "%s: can not open\n", $arg;
176 } else {
177 &cstyle($arg, $fh);
178 close $fh;
179 }
180 }
181 } else {
182 &cstyle("<stdin>", *STDIN);
183 }
184 exit $err_stat;
185
186 my $no_errs = 0; # set for CSTYLED-protected lines
187
188 sub err($) {
189 my ($error) = @_;
190 unless ($no_errs) {
191 printf $fmt, $filename, $., $error, $line;
192 $err_stat = 1;
193 }
194 }
195
196 sub err_prefix($$) {
197 my ($prevline, $error) = @_;
198 my $out = $prevline."\n".$line;
199 unless ($no_errs) {
200 printf $fmt, $filename, $., $error, $out;
201 $err_stat = 1;
202 }
203 }
204
205 sub err_prev($) {
206 my ($error) = @_;
207 unless ($no_errs) {
208 printf $fmt, $filename, $. - 1, $error, $prev;
209 $err_stat = 1;
210 }
211 }
212
213 sub cstyle($$) {
214
215 my ($fn, $filehandle) = @_;
216 $filename = $fn; # share it globally
217
218 my $in_cpp = 0;
219 my $next_in_cpp = 0;
220
221 my $in_comment = 0;
222 my $in_header_comment = 0;
223 my $comment_done = 0;
224 my $in_warlock_comment = 0;
225 my $in_function = 0;
226 my $in_function_header = 0;
227 my $in_declaration = 0;
228 my $note_level = 0;
229 my $nextok = 0;
230 my $nocheck = 0;
231
232 my $in_string = 0;
233
234 my ($okmsg, $comment_prefix);
235
236 $line = '';
237 $prev = '';
238 reset_indent();
239
240 line: while (<$filehandle>) {
241 s/\r?\n$//; # strip return and newline
242
243 # save the original line, then remove all text from within
244 # double or single quotes, we do not want to check such text.
245
246 $line = $_;
247
248 #
249 # C allows strings to be continued with a backslash at the end of
250 # the line. We translate that into a quoted string on the previous
251 # line followed by an initial quote on the next line.
252 #
253 # (we assume that no-one will use backslash-continuation with character
254 # constants)
255 #
256 $_ = '"' . $_ if ($in_string && !$nocheck && !$in_comment);
257
258 #
259 # normal strings and characters
260 #
261 s/'([^\\']|\\[^xX0]|\\0[0-9]*|\\[xX][0-9a-fA-F]*)'/''/g;
262 s/"([^\\"]|\\.)*"/\"\"/g;
263
264 #
265 # detect string continuation
266 #
267 if ($nocheck || $in_comment) {
268 $in_string = 0;
269 } else {
270 #
271 # Now that all full strings are replaced with "", we check
272 # for unfinished strings continuing onto the next line.
273 #
274 $in_string =
275 (s/([^"](?:"")*)"([^\\"]|\\.)*\\$/$1""/ ||
276 s/^("")*"([^\\"]|\\.)*\\$/""/);
277 }
278
279 #
280 # figure out if we are in a cpp directive
281 #
282 $in_cpp = $next_in_cpp || /^\s*#/; # continued or started
283 $next_in_cpp = $in_cpp && /\\$/; # only if continued
284
285 # strip off trailing backslashes, which appear in long macros
286 s/\s*\\$//;
287
288 # an /* END CSTYLED */ comment ends a no-check block.
289 if ($nocheck) {
290 if (/\/\* *END *CSTYLED *\*\//) {
291 $nocheck = 0;
292 } else {
293 reset_indent();
294 next line;
295 }
296 }
297
298 # a /*CSTYLED*/ comment indicates that the next line is ok.
299 if ($nextok) {
300 if ($okmsg) {
301 err($okmsg);
302 }
303 $nextok = 0;
304 $okmsg = 0;
305 if (/\/\* *CSTYLED.*\*\//) {
306 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
307 $okmsg = $1;
308 $nextok = 1;
309 }
310 $no_errs = 1;
311 } elsif ($no_errs) {
312 $no_errs = 0;
313 }
314
315 # check length of line.
316 # first, a quick check to see if there is any chance of being too long.
317 if (($line =~ tr/\t/\t/) * 7 + length($line) > 80) {
318 # yes, there is a chance.
319 # replace tabs with spaces and check again.
320 my $eline = $line;
321 1 while $eline =~
322 s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
323 if (length($eline) > 80) {
324 err("line > 80 characters");
325 }
326 }
327
328 # ignore NOTE(...) annotations (assumes NOTE is on lines by itself).
329 if ($note_level || /\b_?NOTE\s*\(/) { # if in NOTE or this is NOTE
330 s/[^()]//g; # eliminate all non-parens
331 $note_level += s/\(//g - length; # update paren nest level
332 next;
333 }
334
335 # a /* BEGIN CSTYLED */ comment starts a no-check block.
336 if (/\/\* *BEGIN *CSTYLED *\*\//) {
337 $nocheck = 1;
338 }
339
340 # a /*CSTYLED*/ comment indicates that the next line is ok.
341 if (/\/\* *CSTYLED.*\*\//) {
342 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
343 $okmsg = $1;
344 $nextok = 1;
345 }
346 if (/\/\/ *CSTYLED/) {
347 /^.*\/\/ *CSTYLED *(.*)$/;
348 $okmsg = $1;
349 $nextok = 1;
350 }
351
352 # universal checks; apply to everything
353 if (/\t +\t/) {
354 err("spaces between tabs");
355 }
356 if (/ \t+ /) {
357 err("tabs between spaces");
358 }
359 if (/\s$/) {
360 err("space or tab at end of line");
361 }
362 if (/[^ \t(]\/\*/ && !/\w\(\/\*.*\*\/\);/) {
363 err("comment preceded by non-blank");
364 }
365
366 # is this the beginning or ending of a function?
367 # (not if "struct foo\n{\n")
368 if (/^{$/ && $prev =~ /\)\s*(const\s*)?(\/\*.*\*\/\s*)?\\?$/) {
369 $in_function = 1;
370 $in_declaration = 1;
371 $in_function_header = 0;
372 $prev = $line;
373 next line;
374 }
375 if (/^}\s*(\/\*.*\*\/\s*)*$/) {
376 if ($prev =~ /^\s*return\s*;/) {
377 err_prev("unneeded return at end of function");
378 }
379 $in_function = 0;
380 reset_indent(); # we don't check between functions
381 $prev = $line;
382 next line;
383 }
384 if (/^\w*\($/) {
385 $in_function_header = 1;
386 }
387
388 if ($in_warlock_comment && /\*\//) {
389 $in_warlock_comment = 0;
390 $prev = $line;
391 next line;
392 }
393
394 # a blank line terminates the declarations within a function.
395 # XXX - but still a problem in sub-blocks.
396 if ($in_declaration && /^$/) {
397 $in_declaration = 0;
398 }
399
400 if ($comment_done) {
401 $in_comment = 0;
402 $in_header_comment = 0;
403 $comment_done = 0;
404 }
405 # does this looks like the start of a block comment?
406 if (/$hdr_comment_start/) {
407 if (!/^\t*\/\*/) {
408 err("block comment not indented by tabs");
409 }
410 $in_comment = 1;
411 /^(\s*)\//;
412 $comment_prefix = $1;
413 if ($comment_prefix eq "") {
414 $in_header_comment = 1;
415 }
416 $prev = $line;
417 next line;
418 }
419 # are we still in the block comment?
420 if ($in_comment) {
421 if (/^$comment_prefix \*\/$/) {
422 $comment_done = 1;
423 } elsif (/\*\//) {
424 $comment_done = 1;
425 err("improper block comment close")
426 unless ($ignore_hdr_comment && $in_header_comment);
427 } elsif (!/^$comment_prefix \*[ \t]/ &&
428 !/^$comment_prefix \*$/) {
429 err("improper block comment")
430 unless ($ignore_hdr_comment && $in_header_comment);
431 }
432 }
433
434 if ($in_header_comment && $ignore_hdr_comment) {
435 $prev = $line;
436 next line;
437 }
438
439 # check for errors that might occur in comments and in code.
440
441 # allow spaces to be used to draw pictures in header comments.
442 if (/[^ ] / && !/".* .*"/ && !$in_header_comment) {
443 err("spaces instead of tabs");
444 }
445 if (/^ / && !/^ \*[ \t\/]/ && !/^ \*$/ &&
446 (!/^ \w/ || $in_function != 0)) {
447 err("indent by spaces instead of tabs");
448 }
449 if (/^\t+ [^ \t\*]/ || /^\t+ \S/ || /^\t+ \S/) {
450 err("continuation line not indented by 4 spaces");
451 }
452 if (/$warlock_re/ && !/\*\//) {
453 $in_warlock_comment = 1;
454 $prev = $line;
455 next line;
456 }
457 if (/^\s*\/\*./ && !/^\s*\/\*.*\*\// && !/$hdr_comment_start/) {
458 err("improper first line of block comment");
459 }
460
461 if ($in_comment) { # still in comment, don't do further checks
462 $prev = $line;
463 next line;
464 }
465
466 if ((/[^(]\/\*\S/ || /^\/\*\S/) &&
467 !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
468 err("missing blank after open comment");
469 }
470 if (/\S\*\/[^)]|\S\*\/$/ &&
471 !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
472 err("missing blank before close comment");
473 }
474 if (/\/\/\S/) { # C++ comments
475 err("missing blank after start comment");
476 }
477 # check for unterminated single line comments, but allow them when
478 # they are used to comment out the argument list of a function
479 # declaration.
480 if (/\S.*\/\*/ && !/\S.*\/\*.*\*\// && !/\(\/\*/) {
481 err("unterminated single line comment");
482 }
483
484 # check that #if doesn't enumerate ISA defines when there are more
485 # concise ways of checking. E.g., don't do:
486 # #if defined(__amd64) || defined(__i386)
487 # when there is:
488 # #ifdef __x86
489 if (/^#if\sdefined\((.*)\)\s\|\|\sdefined\((.*)\)/) {
490 my $first = $1;
491 my $second = $2;
492 ($first, $second) = ($second, $first) if ($first gt $second);
493
494 if (($first eq "__amd64") && ($second eq "__i386")) {
495 err("#if checking for $first or $second instead of " .
496 "__x86");
497 }
498 }
499
500 if (/^(#else|#endif|#include)(.*)$/) {
501 $prev = $line;
502 if ($picky) {
503 my $directive = $1;
504 my $clause = $2;
505 # Enforce ANSI rules for #else and #endif: no noncomment
506 # identifiers are allowed after #endif or #else. Allow
507 # C++ comments since they seem to be a fact of life.
508 if ((($1 eq "#endif") || ($1 eq "#else")) &&
509 ($clause ne "") &&
510 (!($clause =~ /^\s+\/\*.*\*\/$/)) &&
511 (!($clause =~ /^\s+\/\/.*$/))) {
512 err("non-comment text following " .
513 "$directive (or malformed $directive " .
514 "directive)");
515 }
516 }
517 next line;
518 }
519
520 #
521 # delete any comments and check everything else. Note that
522 # ".*?" is a non-greedy match, so that we don't get confused by
523 # multiple comments on the same line.
524 #
525 s/\/\*.*?\*\///g;
526 s/\/\/.*$//; # C++ comments
527
528 # delete any trailing whitespace; we have already checked for that.
529 s/\s*$//;
530
531 # following checks do not apply to text in comments.
532
533 if (/[^<>\s][!<>=]=/ || /[^<>][!<>=]=[^\s,]/ ||
534 (/[^->]>[^,=>\s]/ && !/[^->]>$/) ||
535 (/[^<]<[^,=<\s]/ && !/[^<]<$/) ||
536 /[^<\s]<[^<]/ || /[^->\s]>[^>]/) {
537 err("missing space around relational operator");
538 }
539 if (/\S>>=/ || /\S<<=/ || />>=\S/ || /<<=\S/ || /\S[-+*\/&|^%]=/ ||
540 (/[^-+*\/&|^%!<>=\s]=[^=]/ && !/[^-+*\/&|^%!<>=\s]=$/) ||
541 (/[^!<>=]=[^=\s]/ && !/[^!<>=]=$/)) {
542 # XXX - should only check this for C++ code
543 # XXX - there are probably other forms that should be allowed
544 if (!/\soperator=/) {
545 err("missing space around assignment operator");
546 }
547 }
548 if (/[,;]\S/ && !/\bfor \(;;\)/) {
549 err("comma or semicolon followed by non-blank");
550 }
551 # allow "for" statements to have empty "while" clauses
552 if (/\s[,;]/ && !/^[\t]+;$/ && !/^\s*for \([^;]*; ;[^;]*\)/) {
553 err("comma or semicolon preceded by blank");
554 }
555 if (/^\s*(&&|\|\|)/) {
556 err("improper boolean continuation");
557 }
558 if (/\S *(&&|\|\|)/ || /(&&|\|\|) *\S/) {
559 err("more than one space around boolean operator");
560 }
561 if (/\b(for|if|while|switch|sizeof|return|case)\(/) {
562 err("missing space between keyword and paren");
563 }
564 if (/(\b(for|if|while|switch|return)\b.*){2,}/ && !/^#define/) {
565 # multiple "case" and "sizeof" allowed
566 err("more than one keyword on line");
567 }
568 if (/\b(for|if|while|switch|sizeof|return|case)\s\s+\(/ &&
569 !/^#if\s+\(/) {
570 err("extra space between keyword and paren");
571 }
572 # try to detect "func (x)" but not "if (x)" or
573 # "#define foo (x)" or "int (*func)();"
574 if (/\w\s\(/) {
575 my $s = $_;
576 # strip off all keywords on the line
577 s/\b(for|if|while|switch|return|case|sizeof)\s\(/XXX(/g;
578 s/#elif\s\(/XXX(/g;
579 s/^#define\s+\w+\s+\(/XXX(/;
580 # do not match things like "void (*f)();"
581 # or "typedef void (func_t)();"
582 s/\w\s\(+\*/XXX(*/g;
583 s/\b($typename|void)\s+\(+/XXX(/og;
584 if (/\w\s\(/) {
585 err("extra space between function name and left paren");
586 }
587 $_ = $s;
588 }
589 # try to detect "int foo(x)", but not "extern int foo(x);"
590 # XXX - this still trips over too many legitimate things,
591 # like "int foo(x,\n\ty);"
592 # if (/^(\w+(\s|\*)+)+\w+\(/ && !/\)[;,](\s|)*$/ &&
593 # !/^(extern|static)\b/) {
594 # err("return type of function not on separate line");
595 # }
596 # this is a close approximation
597 if (/^(\w+(\s|\*)+)+\w+\(.*\)(\s|)*$/ &&
598 !/^(extern|static)\b/) {
599 err("return type of function not on separate line");
600 }
601 if (/^#define /) {
602 err("#define followed by space instead of tab");
603 }
604 if (/^\s*return\W[^;]*;/ && !/^\s*return\s*\(.*\);/) {
605 err("unparenthesized return expression");
606 }
607 if (/\bsizeof\b/ && !/\bsizeof\s*\(.*\)/) {
608 err("unparenthesized sizeof expression");
609 }
610 if (/\(\s/) {
611 err("whitespace after left paren");
612 }
613 # allow "for" statements to have empty "continue" clauses
614 if (/\s\)/ && !/^\s*for \([^;]*;[^;]*; \)/) {
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|)*$/ &&
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///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 }