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