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