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