]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tools/build/checkstyle9.pl
checkstyle9.pl: Another correction to github workflow
[FreeBSD/FreeBSD.git] / tools / build / checkstyle9.pl
1 #!/usr/bin/env perl
2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
7
8 use strict;
9 use warnings;
10 use Term::ANSIColor qw(:constants);
11
12 my $P = $0;
13 $P =~ s@.*/@@g;
14
15 our $SrcFile    = qr{\.(?:h|c|cpp|s|S|pl|py|sh)$};
16
17 my $V = '0.31';
18
19 use Getopt::Long qw(:config no_auto_abbrev);
20
21 my $quiet = 0;
22 my $tree = 1;
23 my $chk_signoff = 1;
24 my $chk_patch = undef;
25 my $chk_branch = undef;
26 my $tst_only;
27 my $emacs = 0;
28 my $github = 0;
29 my $terse = 0;
30 my $file = undef;
31 my $color = "auto";
32 my $no_warnings = 0;
33 my $summary = 1;
34 my $mailback = 0;
35 my $summary_file = 0;
36 my $root;
37 my %debug;
38 my $help = 0;
39
40 sub help {
41         my ($exitcode) = @_;
42
43         print << "EOM";
44 Usage:
45
46     $P [OPTION]... [FILE]...
47     $P [OPTION]... [GIT-REV-LIST]
48
49 Version: $V
50
51 Options:
52   -q, --quiet                quiet
53   --patch                    treat FILE as patchfile
54   --branch                   treat args as GIT revision list
55   --emacs                    emacs compile window format
56   --terse                    one line per report
57   -f, --file                 treat FILE as regular source file
58   --strict                   fail if only warnings are found
59   --no-summary               suppress the per-file summary
60   --mailback                 only produce a report in case of warnings/errors
61   --summary-file             include the filename in summary
62   --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
63                              'values', 'possible', 'type', and 'attr' (default
64                              is all off)
65   --test-only=WORD           report only warnings/errors containing WORD
66                              literally
67   --color[=WHEN]             Use colors 'always', 'never', or only when output
68                              is a terminal ('auto'). Default is 'auto'.
69   -h, --help, --version      display this help and exit
70
71 When FILE is - read standard input.
72 EOM
73
74         exit($exitcode);
75 }
76
77 # Use at your own risk
78 print "\n", MAGENTA, "WARNING:", RESET, " This code is highly experimental ... likely isn't a great style(9) match yet\n\n";
79
80 # Perl's Getopt::Long allows options to take optional arguments after a space.
81 # Prevent --color by itself from consuming other arguments
82 foreach (@ARGV) {
83         if ($_ eq "--color" || $_ eq "-color") {
84                 $_ = "--color=$color";
85         }
86 }
87
88 GetOptions(
89         'q|quiet+'      => \$quiet,
90         'tree!'         => \$tree,
91         'signoff!'      => \$chk_signoff,
92         'patch!'        => \$chk_patch,
93         'branch!'       => \$chk_branch,
94         'emacs!'        => \$emacs,
95         'github!'       => \$github,
96         'terse!'        => \$terse,
97         'f|file!'       => \$file,
98         'strict!'       => \$no_warnings,
99         'root=s'        => \$root,
100         'summary!'      => \$summary,
101         'mailback!'     => \$mailback,
102         'summary-file!' => \$summary_file,
103
104         'debug=s'       => \%debug,
105         'test-only=s'   => \$tst_only,
106         'color=s'       => \$color,
107         'no-color'      => sub { $color = 'never'; },
108         'h|help'        => \$help,
109         'version'       => \$help
110 ) or help(1);
111
112 help(0) if ($help);
113
114 my $exit = 0;
115
116 if ($#ARGV < 0) {
117         print "$P: no input files\n";
118         exit(1);
119 }
120
121 if (!defined $chk_branch && !defined $chk_patch && !defined $file) {
122         $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
123         $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
124         $chk_patch = $chk_branch || $file ? 0 : 1;
125 } elsif (!defined $chk_branch && !defined $chk_patch) {
126         if ($file) {
127                 $chk_branch = $chk_patch = 0;
128         } else {
129                 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
130                 $chk_patch = $chk_branch ? 0 : 1;
131         }
132 } elsif (!defined $chk_branch && !defined $file) {
133         if ($chk_patch) {
134                 $chk_branch = $file = 0;
135         } else {
136                 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
137                 $file = $chk_branch ? 0 : 1;
138         }
139 } elsif (!defined $chk_patch && !defined $file) {
140         if ($chk_branch) {
141                 $chk_patch = $file = 0;
142         } else {
143                 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
144                 $chk_patch = $file ? 0 : 1;
145         }
146 } elsif (!defined $chk_branch) {
147         $chk_branch = $chk_patch || $file ? 0 : 1;
148 } elsif (!defined $chk_patch) {
149         $chk_patch = $chk_branch || $file ? 0 : 1;
150 } elsif (!defined $file) {
151         $file = $chk_patch || $chk_branch ? 0 : 1;
152 }
153
154 if (($chk_patch && $chk_branch) ||
155     ($chk_patch && $file) ||
156     ($chk_branch && $file)) {
157         die "Only one of --file, --branch, --patch is permitted\n";
158 }
159 if (!$chk_patch && !$chk_branch && !$file) {
160         die "One of --file, --branch, --patch is required\n";
161 }
162
163 if ($color =~ /^always$/i) {
164         $color = 1;
165 } elsif ($color =~ /^never$/i) {
166         $color = 0;
167 } elsif ($color =~ /^auto$/i) {
168         $color = (-t STDOUT);
169 } else {
170         die "Invalid color mode: $color\n";
171 }
172
173 my $dbg_values = 0;
174 my $dbg_possible = 0;
175 my $dbg_adv_dcs = 0;
176 my $dbg_adv_checking = 0;
177 my $dbg_adv_apw = 0;
178 for my $key (keys %debug) {
179         ## no critic
180         eval "\${dbg_$key} = '$debug{$key}';";
181         die "$@" if ($@);
182 }
183
184 my $rpt_cleaners = 0;
185
186 if ($terse) {
187         $emacs = 1;
188         $quiet++;
189 }
190
191 my $emitted_corrupt = 0;
192
193 our $Ident      = qr{
194                         [A-Za-z_][A-Za-z\d_]*
195                         (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
196                 }x;
197 our $Storage    = qr{extern|static|asmlinkage};
198 our $Sparse     = qr{
199                         __force
200                 }x;
201
202 # Notes to $Attribute:
203 our $Attribute  = qr{
204                         const|
205                         volatile|
206                         QEMU_NORETURN|
207                         QEMU_WARN_UNUSED_RESULT|
208                         QEMU_SENTINEL|
209                         QEMU_PACKED|
210                         GCC_FMT_ATTR
211                   }x;
212 our $Modifier;
213 our $Inline     = qr{inline};
214 our $Member     = qr{->$Ident|\.$Ident|\[[^]]*\]};
215 our $Lval       = qr{$Ident(?:$Member)*};
216
217 our $Constant   = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
218 our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
219 our $Compare    = qr{<=|>=|==|!=|<|>};
220 our $Operators  = qr{
221                         <=|>=|==|!=|
222                         =>|->|<<|>>|<|>|!|~|
223                         &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
224                   }x;
225
226 our $NonptrType;
227 our $Type;
228 our $Declare;
229
230 our $NON_ASCII_UTF8     = qr{
231         [\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
232         |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
233         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
234         |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
235         |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
236         | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
237         |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
238 }x;
239
240 our $UTF8       = qr{
241         [\x09\x0A\x0D\x20-\x7E]              # ASCII
242         | $NON_ASCII_UTF8
243 }x;
244
245 # some readers default to ISO-8859-1 when showing email source. detect
246 # when UTF-8 is incorrectly interpreted as ISO-8859-1 and reencoded back.
247 # False positives are possible but very unlikely.
248 our $UTF8_MOJIBAKE = qr{
249         \xC3[\x82-\x9F] \xC2[\x80-\xBF]                    # c2-df 80-bf
250         | \xC3\xA0 \xC2[\xA0-\xBF] \xC2[\x80-\xBF]         # e0 a0-bf 80-bf
251         | \xC3[\xA1-\xAC\xAE\xAF] (?: \xC2[\x80-\xBF]){2}  # e1-ec/ee/ef 80-bf 80-bf
252         | \xC3\xAD \xC2[\x80-\x9F] \xC2[\x80-\xBF]         # ed 80-9f 80-bf
253         | \xC3\xB0 \xC2[\x90-\xBF] (?: \xC2[\x80-\xBF]){2} # f0 90-bf 80-bf 80-bf
254         | \xC3[\xB1-\xB3] (?: \xC2[\x80-\xBF]){3}          # f1-f3 80-bf 80-bf 80-bf
255         | \xC3\xB4 \xC2[\x80-\x8F] (?: \xC2[\x80-\xBF]){2} # f4 80-b8 80-bf 80-bf
256 }x;
257
258 # There are still some false positives, but this catches most
259 # common cases.
260 our $typeTypedefs = qr{(?x:
261         (?![KMGTPE]iB)                      # IEC binary prefix (do not match)
262         [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]*     # camelcase
263         | [A-Z][A-Z\d_]*AIOCB               # all uppercase
264         | [A-Z][A-Z\d_]*CPU                 # all uppercase
265         | QEMUBH                            # all uppercase
266 )};
267
268 our @typeList = (
269         qr{void},
270         qr{(?:unsigned\s+)?char},
271         qr{(?:unsigned\s+)?short},
272         qr{(?:unsigned\s+)?int},
273         qr{(?:unsigned\s+)?long},
274         qr{(?:unsigned\s+)?long\s+int},
275         qr{(?:unsigned\s+)?long\s+long},
276         qr{(?:unsigned\s+)?long\s+long\s+int},
277         qr{unsigned},
278         qr{float},
279         qr{double},
280         qr{bool},
281         qr{struct\s+$Ident},
282         qr{union\s+$Ident},
283         qr{enum\s+$Ident},
284         qr{${Ident}_t},
285         qr{${Ident}_handler},
286         qr{${Ident}_handler_fn},
287         qr{target_(?:u)?long},
288         qr{hwaddr},
289 );
290
291 # This can be modified by sub possible.  Since it can be empty, be careful
292 # about regexes that always match, because they can cause infinite loops.
293 our @modifierList = (
294 );
295
296 sub build_types {
297         my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
298         if (@modifierList > 0) {
299                 my $mods = "(?x:  \n" . join("|\n  ", @modifierList) . "\n)";
300                 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
301         } else {
302                 $Modifier = qr{(?:$Attribute|$Sparse)};
303         }
304         $NonptrType     = qr{
305                         (?:$Modifier\s+|const\s+)*
306                         (?:
307                                 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
308                                 (?:$typeTypedefs\b)|
309                                 (?:${all}\b)
310                         )
311                         (?:\s+$Modifier|\s+const)*
312                   }x;
313         $Type   = qr{
314                         $NonptrType
315                         (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
316                         (?:\s+$Inline|\s+$Modifier)*
317                   }x;
318         $Declare        = qr{(?:$Storage\s+)?$Type};
319 }
320 build_types();
321
322 $chk_signoff = 0 if ($file);
323
324 my @rawlines = ();
325 my @lines = ();
326 my $vname;
327 if ($chk_branch) {
328         my @patches;
329         my %git_commits = ();
330         my $HASH;
331         open($HASH, "-|", "git", "log", "--reverse", "--no-merges", "--format=%H %s", $ARGV[0]) ||
332                 die "$P: git log --reverse --no-merges --format='%H %s' $ARGV[0] failed - $!\n";
333
334         for my $line (<$HASH>) {
335                 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
336                 next if (!defined($1) || !defined($2));
337                 my $sha1 = $1;
338                 my $subject = $2;
339                 push(@patches, $sha1);
340                 $git_commits{$sha1} = $subject;
341         }
342
343         close $HASH;
344
345         die "$P: no revisions returned for revlist '$ARGV[0]'\n"
346             unless @patches;
347
348         my $i = 1;
349         my $num_patches = @patches;
350         for my $hash (@patches) {
351                 my $FILE;
352                 open($FILE, '-|', "git", "show", "--patch-with-stat", $hash) ||
353                         die "$P: git show $hash - $!\n";
354                 while (<$FILE>) {
355                         chomp;
356                         push(@rawlines, $_);
357                 }
358                 close($FILE);
359                 $vname = substr($hash, 0, 12) . ' (' . $git_commits{$hash} . ')';
360                 if ($num_patches > 1 && $quiet == 0) {
361                         my $prefix = "$i/$num_patches";
362                         $prefix = BLUE . BOLD . $prefix . RESET if $color;
363                         print "$prefix Checking commit $vname\n";
364                         $vname = "Patch $i/$num_patches";
365                 } else {
366                         $vname = "Commit " . $vname;
367                 }
368                 if (!process($hash)) {
369                         $exit = 1;
370                         print "\n" if ($num_patches > 1 && $quiet == 0);
371                 }
372                 @rawlines = ();
373                 @lines = ();
374                 $i++;
375         }
376 } else {
377         for my $filename (@ARGV) {
378                 my $FILE;
379                 if ($file) {
380                         open($FILE, '-|', "diff -u /dev/null $filename") ||
381                                 die "$P: $filename: diff failed - $!\n";
382                 } elsif ($filename eq '-') {
383                         open($FILE, '<&STDIN');
384                 } else {
385                         open($FILE, '<', "$filename") ||
386                                 die "$P: $filename: open failed - $!\n";
387                 }
388                 if ($filename eq '-') {
389                         $vname = 'Your patch';
390                 } else {
391                         $vname = $filename;
392                 }
393                 print "Checking $filename...\n" if @ARGV > 1 && $quiet == 0;
394                 while (<$FILE>) {
395                         chomp;
396                         push(@rawlines, $_);
397                 }
398                 close($FILE);
399                 if (!process($filename)) {
400                         $exit = 1;
401                 }
402                 @rawlines = ();
403                 @lines = ();
404         }
405 }
406
407 exit($exit);
408
409 sub top_of_kernel_tree {
410         my ($root) = @_;
411
412         my @tree_check = (
413             "Makefile.inc1", "README.md", "sys",
414             "usr.sbin"
415         );
416
417         foreach my $check (@tree_check) {
418                 if (! -e $root . '/' . $check) {
419                         return 0;
420                 }
421         }
422         return 1;
423 }
424
425 sub expand_tabs {
426         my ($str) = @_;
427
428         my $res = '';
429         my $n = 0;
430         for my $c (split(//, $str)) {
431                 if ($c eq "\t") {
432                         $res .= ' ';
433                         $n++;
434                         for (; ($n % 8) != 0; $n++) {
435                                 $res .= ' ';
436                         }
437                         next;
438                 }
439                 $res .= $c;
440                 $n++;
441         }
442
443         return $res;
444 }
445 sub copy_spacing {
446         (my $res = shift) =~ tr/\t/ /c;
447         return $res;
448 }
449
450 sub line_stats {
451         my ($line) = @_;
452
453         # Drop the diff line leader and expand tabs
454         $line =~ s/^.//;
455         $line = expand_tabs($line);
456
457         # Pick the indent from the front of the line.
458         my ($white) = ($line =~ /^(\s*)/);
459
460         return (length($line), length($white));
461 }
462
463 my $sanitise_quote = '';
464
465 sub sanitise_line_reset {
466         my ($in_comment) = @_;
467
468         if ($in_comment) {
469                 $sanitise_quote = '*/';
470         } else {
471                 $sanitise_quote = '';
472         }
473 }
474 sub sanitise_line {
475         my ($line) = @_;
476
477         my $res = '';
478         my $l = '';
479
480         my $qlen = 0;
481         my $off = 0;
482         my $c;
483
484         # Always copy over the diff marker.
485         $res = substr($line, 0, 1);
486
487         for ($off = 1; $off < length($line); $off++) {
488                 $c = substr($line, $off, 1);
489
490                 # Comments we are wacking completely including the begin
491                 # and end, all to $;.
492                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
493                         $sanitise_quote = '*/';
494
495                         substr($res, $off, 2, "$;$;");
496                         $off++;
497                         next;
498                 }
499                 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
500                         $sanitise_quote = '';
501                         substr($res, $off, 2, "$;$;");
502                         $off++;
503                         next;
504                 }
505                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
506                         $sanitise_quote = '//';
507
508                         substr($res, $off, 2, $sanitise_quote);
509                         $off++;
510                         next;
511                 }
512
513                 # A \ in a string means ignore the next character.
514                 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
515                     $c eq "\\") {
516                         substr($res, $off, 2, 'XX');
517                         $off++;
518                         next;
519                 }
520                 # Regular quotes.
521                 if ($c eq "'" || $c eq '"') {
522                         if ($sanitise_quote eq '') {
523                                 $sanitise_quote = $c;
524
525                                 substr($res, $off, 1, $c);
526                                 next;
527                         } elsif ($sanitise_quote eq $c) {
528                                 $sanitise_quote = '';
529                         }
530                 }
531
532                 #print "c<$c> SQ<$sanitise_quote>\n";
533                 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
534                         substr($res, $off, 1, $;);
535                 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
536                         substr($res, $off, 1, $;);
537                 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
538                         substr($res, $off, 1, 'X');
539                 } else {
540                         substr($res, $off, 1, $c);
541                 }
542         }
543
544         if ($sanitise_quote eq '//') {
545                 $sanitise_quote = '';
546         }
547
548         # The pathname on a #include may be surrounded by '<' and '>'.
549         if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
550                 my $clean = 'X' x length($1);
551                 $res =~ s@\<.*\>@<$clean>@;
552
553         # The whole of a #error is a string.
554         } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
555                 my $clean = 'X' x length($1);
556                 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
557         }
558
559         return $res;
560 }
561
562 sub ctx_statement_block {
563         my ($linenr, $remain, $off) = @_;
564         my $line = $linenr - 1;
565         my $blk = '';
566         my $soff = $off;
567         my $coff = $off - 1;
568         my $coff_set = 0;
569
570         my $loff = 0;
571
572         my $type = '';
573         my $level = 0;
574         my @stack = ();
575         my $p;
576         my $c;
577         my $len = 0;
578
579         my $remainder;
580         while (1) {
581                 @stack = (['', 0]) if ($#stack == -1);
582
583                 #warn "CSB: blk<$blk> remain<$remain>\n";
584                 # If we are about to drop off the end, pull in more
585                 # context.
586                 if ($off >= $len) {
587                         for (; $remain > 0; $line++) {
588                                 last if (!defined $lines[$line]);
589                                 next if ($lines[$line] =~ /^-/);
590                                 $remain--;
591                                 $loff = $len;
592                                 $blk .= $lines[$line] . "\n";
593                                 $len = length($blk);
594                                 $line++;
595                                 last;
596                         }
597                         # Bail if there is no further context.
598                         #warn "CSB: blk<$blk> off<$off> len<$len>\n";
599                         if ($off >= $len) {
600                                 last;
601                         }
602                 }
603                 $p = $c;
604                 $c = substr($blk, $off, 1);
605                 $remainder = substr($blk, $off);
606
607                 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
608
609                 # Handle nested #if/#else.
610                 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
611                         push(@stack, [ $type, $level ]);
612                 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
613                         ($type, $level) = @{$stack[$#stack - 1]};
614                 } elsif ($remainder =~ /^#\s*endif\b/) {
615                         ($type, $level) = @{pop(@stack)};
616                 }
617
618                 # Statement ends at the ';' or a close '}' at the
619                 # outermost level.
620                 if ($level == 0 && $c eq ';') {
621                         last;
622                 }
623
624                 # An else is really a conditional as long as its not else if
625                 if ($level == 0 && $coff_set == 0 &&
626                                 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
627                                 $remainder =~ /^(else)(?:\s|{)/ &&
628                                 $remainder !~ /^else\s+if\b/) {
629                         $coff = $off + length($1) - 1;
630                         $coff_set = 1;
631                         #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
632                         #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
633                 }
634
635                 if (($type eq '' || $type eq '(') && $c eq '(') {
636                         $level++;
637                         $type = '(';
638                 }
639                 if ($type eq '(' && $c eq ')') {
640                         $level--;
641                         $type = ($level != 0)? '(' : '';
642
643                         if ($level == 0 && $coff < $soff) {
644                                 $coff = $off;
645                                 $coff_set = 1;
646                                 #warn "CSB: mark coff<$coff>\n";
647                         }
648                 }
649                 if (($type eq '' || $type eq '{') && $c eq '{') {
650                         $level++;
651                         $type = '{';
652                 }
653                 if ($type eq '{' && $c eq '}') {
654                         $level--;
655                         $type = ($level != 0)? '{' : '';
656
657                         if ($level == 0) {
658                                 if (substr($blk, $off + 1, 1) eq ';') {
659                                         $off++;
660                                 }
661                                 last;
662                         }
663                 }
664                 $off++;
665         }
666         # We are truly at the end, so shuffle to the next line.
667         if ($off == $len) {
668                 $loff = $len + 1;
669                 $line++;
670                 $remain--;
671         }
672
673         my $statement = substr($blk, $soff, $off - $soff + 1);
674         my $condition = substr($blk, $soff, $coff - $soff + 1);
675
676         #warn "STATEMENT<$statement>\n";
677         #warn "CONDITION<$condition>\n";
678
679         #print "coff<$coff> soff<$off> loff<$loff>\n";
680
681         return ($statement, $condition,
682                         $line, $remain + 1, $off - $loff + 1, $level);
683 }
684
685 sub statement_lines {
686         my ($stmt) = @_;
687
688         # Strip the diff line prefixes and rip blank lines at start and end.
689         $stmt =~ s/(^|\n)./$1/g;
690         $stmt =~ s/^\s*//;
691         $stmt =~ s/\s*$//;
692
693         my @stmt_lines = ($stmt =~ /\n/g);
694
695         return $#stmt_lines + 2;
696 }
697
698 sub statement_rawlines {
699         my ($stmt) = @_;
700
701         my @stmt_lines = ($stmt =~ /\n/g);
702
703         return $#stmt_lines + 2;
704 }
705
706 sub statement_block_size {
707         my ($stmt) = @_;
708
709         $stmt =~ s/(^|\n)./$1/g;
710         $stmt =~ s/^\s*\{//;
711         $stmt =~ s/}\s*$//;
712         $stmt =~ s/^\s*//;
713         $stmt =~ s/\s*$//;
714
715         my @stmt_lines = ($stmt =~ /\n/g);
716         my @stmt_statements = ($stmt =~ /;/g);
717
718         my $stmt_lines = $#stmt_lines + 2;
719         my $stmt_statements = $#stmt_statements + 1;
720
721         if ($stmt_lines > $stmt_statements) {
722                 return $stmt_lines;
723         } else {
724                 return $stmt_statements;
725         }
726 }
727
728 sub ctx_statement_full {
729         my ($linenr, $remain, $off) = @_;
730         my ($statement, $condition, $level);
731
732         my (@chunks);
733
734         # Grab the first conditional/block pair.
735         ($statement, $condition, $linenr, $remain, $off, $level) =
736                                 ctx_statement_block($linenr, $remain, $off);
737         #print "F: c<$condition> s<$statement> remain<$remain>\n";
738         push(@chunks, [ $condition, $statement ]);
739         if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
740                 return ($level, $linenr, @chunks);
741         }
742
743         # Pull in the following conditional/block pairs and see if they
744         # could continue the statement.
745         for (;;) {
746                 ($statement, $condition, $linenr, $remain, $off, $level) =
747                                 ctx_statement_block($linenr, $remain, $off);
748                 #print "C: c<$condition> s<$statement> remain<$remain>\n";
749                 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
750                 #print "C: push\n";
751                 push(@chunks, [ $condition, $statement ]);
752         }
753
754         return ($level, $linenr, @chunks);
755 }
756
757 sub ctx_block_get {
758         my ($linenr, $remain, $outer, $open, $close, $off) = @_;
759         my $line;
760         my $start = $linenr - 1;
761         my $blk = '';
762         my @o;
763         my @c;
764         my @res = ();
765
766         my $level = 0;
767         my @stack = ($level);
768         for ($line = $start; $remain > 0; $line++) {
769                 next if ($rawlines[$line] =~ /^-/);
770                 $remain--;
771
772                 $blk .= $rawlines[$line];
773
774                 # Handle nested #if/#else.
775                 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
776                         push(@stack, $level);
777                 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
778                         $level = $stack[$#stack - 1];
779                 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
780                         $level = pop(@stack);
781                 }
782
783                 foreach my $c (split(//, $lines[$line])) {
784                         ##print "C<$c>L<$level><$open$close>O<$off>\n";
785                         if ($off > 0) {
786                                 $off--;
787                                 next;
788                         }
789
790                         if ($c eq $close && $level > 0) {
791                                 $level--;
792                                 last if ($level == 0);
793                         } elsif ($c eq $open) {
794                                 $level++;
795                         }
796                 }
797
798                 if (!$outer || $level <= 1) {
799                         push(@res, $rawlines[$line]);
800                 }
801
802                 last if ($level == 0);
803         }
804
805         return ($level, @res);
806 }
807 sub ctx_block_outer {
808         my ($linenr, $remain) = @_;
809
810         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
811         return @r;
812 }
813 sub ctx_block {
814         my ($linenr, $remain) = @_;
815
816         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
817         return @r;
818 }
819 sub ctx_statement {
820         my ($linenr, $remain, $off) = @_;
821
822         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
823         return @r;
824 }
825 sub ctx_block_level {
826         my ($linenr, $remain) = @_;
827
828         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
829 }
830 sub ctx_statement_level {
831         my ($linenr, $remain, $off) = @_;
832
833         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
834 }
835
836 sub ctx_locate_comment {
837         my ($first_line, $end_line) = @_;
838
839         # Catch a comment on the end of the line itself.
840         my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
841         return $current_comment if (defined $current_comment);
842
843         # Look through the context and try and figure out if there is a
844         # comment.
845         my $in_comment = 0;
846         $current_comment = '';
847         for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
848                 my $line = $rawlines[$linenr - 1];
849                 #warn "           $line\n";
850                 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
851                         $in_comment = 1;
852                 }
853                 if ($line =~ m@/\*@) {
854                         $in_comment = 1;
855                 }
856                 if (!$in_comment && $current_comment ne '') {
857                         $current_comment = '';
858                 }
859                 $current_comment .= $line . "\n" if ($in_comment);
860                 if ($line =~ m@\*/@) {
861                         $in_comment = 0;
862                 }
863         }
864
865         chomp($current_comment);
866         return($current_comment);
867 }
868 sub ctx_has_comment {
869         my ($first_line, $end_line) = @_;
870         my $cmt = ctx_locate_comment($first_line, $end_line);
871
872         ##print "LINE: $rawlines[$end_line - 1 ]\n";
873         ##print "CMMT: $cmt\n";
874
875         return ($cmt ne '');
876 }
877
878 sub raw_line {
879         my ($linenr, $cnt) = @_;
880
881         my $offset = $linenr - 1;
882         $cnt++;
883
884         my $line;
885         while ($cnt) {
886                 $line = $rawlines[$offset++];
887                 next if (defined($line) && $line =~ /^-/);
888                 $cnt--;
889         }
890
891         return $line;
892 }
893
894 sub cat_vet {
895         my ($vet) = @_;
896         my ($res, $coded);
897
898         $res = '';
899         while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
900                 $res .= $1;
901                 if ($2 ne '') {
902                         $coded = sprintf("^%c", unpack('C', $2) + 64);
903                         $res .= $coded;
904                 }
905         }
906         $res =~ s/$/\$/;
907
908         return $res;
909 }
910
911 my $av_preprocessor = 0;
912 my $av_pending;
913 my @av_paren_type;
914 my $av_pend_colon;
915
916 sub annotate_reset {
917         $av_preprocessor = 0;
918         $av_pending = '_';
919         @av_paren_type = ('E');
920         $av_pend_colon = 'O';
921 }
922
923 sub annotate_values {
924         my ($stream, $type) = @_;
925
926         my $res;
927         my $var = '_' x length($stream);
928         my $cur = $stream;
929
930         print "$stream\n" if ($dbg_values > 1);
931
932         while (length($cur)) {
933                 @av_paren_type = ('E') if ($#av_paren_type < 0);
934                 print " <" . join('', @av_paren_type) .
935                                 "> <$type> <$av_pending>" if ($dbg_values > 1);
936                 if ($cur =~ /^(\s+)/o) {
937                         print "WS($1)\n" if ($dbg_values > 1);
938                         if ($1 =~ /\n/ && $av_preprocessor) {
939                                 $type = pop(@av_paren_type);
940                                 $av_preprocessor = 0;
941                         }
942
943                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
944                         print "CAST($1)\n" if ($dbg_values > 1);
945                         push(@av_paren_type, $type);
946                         $type = 'C';
947
948                 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
949                         print "DECLARE($1)\n" if ($dbg_values > 1);
950                         $type = 'T';
951
952                 } elsif ($cur =~ /^($Modifier)\s*/) {
953                         print "MODIFIER($1)\n" if ($dbg_values > 1);
954                         $type = 'T';
955
956                 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
957                         print "DEFINE($1,$2)\n" if ($dbg_values > 1);
958                         $av_preprocessor = 1;
959                         push(@av_paren_type, $type);
960                         if ($2 ne '') {
961                                 $av_pending = 'N';
962                         }
963                         $type = 'E';
964
965                 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
966                         print "UNDEF($1)\n" if ($dbg_values > 1);
967                         $av_preprocessor = 1;
968                         push(@av_paren_type, $type);
969
970                 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
971                         print "PRE_START($1)\n" if ($dbg_values > 1);
972                         $av_preprocessor = 1;
973
974                         push(@av_paren_type, $type);
975                         push(@av_paren_type, $type);
976                         $type = 'E';
977
978                 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
979                         print "PRE_RESTART($1)\n" if ($dbg_values > 1);
980                         $av_preprocessor = 1;
981
982                         push(@av_paren_type, $av_paren_type[$#av_paren_type]);
983
984                         $type = 'E';
985
986                 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
987                         print "PRE_END($1)\n" if ($dbg_values > 1);
988
989                         $av_preprocessor = 1;
990
991                         # Assume all arms of the conditional end as this
992                         # one does, and continue as if the #endif was not here.
993                         pop(@av_paren_type);
994                         push(@av_paren_type, $type);
995                         $type = 'E';
996
997                 } elsif ($cur =~ /^(\\\n)/o) {
998                         print "PRECONT($1)\n" if ($dbg_values > 1);
999
1000                 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1001                         print "ATTR($1)\n" if ($dbg_values > 1);
1002                         $av_pending = $type;
1003                         $type = 'N';
1004
1005                 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1006                         print "SIZEOF($1)\n" if ($dbg_values > 1);
1007                         if (defined $2) {
1008                                 $av_pending = 'V';
1009                         }
1010                         $type = 'N';
1011
1012                 } elsif ($cur =~ /^(if|while|for)\b/o) {
1013                         print "COND($1)\n" if ($dbg_values > 1);
1014                         $av_pending = 'E';
1015                         $type = 'N';
1016
1017                 } elsif ($cur =~/^(case)/o) {
1018                         print "CASE($1)\n" if ($dbg_values > 1);
1019                         $av_pend_colon = 'C';
1020                         $type = 'N';
1021
1022                 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1023                         print "KEYWORD($1)\n" if ($dbg_values > 1);
1024                         $type = 'N';
1025
1026                 } elsif ($cur =~ /^(\()/o) {
1027                         print "PAREN('$1')\n" if ($dbg_values > 1);
1028                         push(@av_paren_type, $av_pending);
1029                         $av_pending = '_';
1030                         $type = 'N';
1031
1032                 } elsif ($cur =~ /^(\))/o) {
1033                         my $new_type = pop(@av_paren_type);
1034                         if ($new_type ne '_') {
1035                                 $type = $new_type;
1036                                 print "PAREN('$1') -> $type\n"
1037                                                         if ($dbg_values > 1);
1038                         } else {
1039                                 print "PAREN('$1')\n" if ($dbg_values > 1);
1040                         }
1041
1042                 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1043                         print "FUNC($1)\n" if ($dbg_values > 1);
1044                         $type = 'V';
1045                         $av_pending = 'V';
1046
1047                 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1048                         if (defined $2 && $type eq 'C' || $type eq 'T') {
1049                                 $av_pend_colon = 'B';
1050                         } elsif ($type eq 'E') {
1051                                 $av_pend_colon = 'L';
1052                         }
1053                         print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1054                         $type = 'V';
1055
1056                 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1057                         print "IDENT($1)\n" if ($dbg_values > 1);
1058                         $type = 'V';
1059
1060                 } elsif ($cur =~ /^($Assignment)/o) {
1061                         print "ASSIGN($1)\n" if ($dbg_values > 1);
1062                         $type = 'N';
1063
1064                 } elsif ($cur =~/^(;|{|})/) {
1065                         print "END($1)\n" if ($dbg_values > 1);
1066                         $type = 'E';
1067                         $av_pend_colon = 'O';
1068
1069                 } elsif ($cur =~/^(,)/) {
1070                         print "COMMA($1)\n" if ($dbg_values > 1);
1071                         $type = 'C';
1072
1073                 } elsif ($cur =~ /^(\?)/o) {
1074                         print "QUESTION($1)\n" if ($dbg_values > 1);
1075                         $type = 'N';
1076
1077                 } elsif ($cur =~ /^(:)/o) {
1078                         print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1079
1080                         substr($var, length($res), 1, $av_pend_colon);
1081                         if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1082                                 $type = 'E';
1083                         } else {
1084                                 $type = 'N';
1085                         }
1086                         $av_pend_colon = 'O';
1087
1088                 } elsif ($cur =~ /^(\[)/o) {
1089                         print "CLOSE($1)\n" if ($dbg_values > 1);
1090                         $type = 'N';
1091
1092                 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1093                         my $variant;
1094
1095                         print "OPV($1)\n" if ($dbg_values > 1);
1096                         if ($type eq 'V') {
1097                                 $variant = 'B';
1098                         } else {
1099                                 $variant = 'U';
1100                         }
1101
1102                         substr($var, length($res), 1, $variant);
1103                         $type = 'N';
1104
1105                 } elsif ($cur =~ /^($Operators)/o) {
1106                         print "OP($1)\n" if ($dbg_values > 1);
1107                         if ($1 ne '++' && $1 ne '--') {
1108                                 $type = 'N';
1109                         }
1110
1111                 } elsif ($cur =~ /(^.)/o) {
1112                         print "C($1)\n" if ($dbg_values > 1);
1113                 }
1114                 if (defined $1) {
1115                         $cur = substr($cur, length($1));
1116                         $res .= $type x length($1);
1117                 }
1118         }
1119
1120         return ($res, $var);
1121 }
1122
1123 sub possible {
1124         my ($possible, $line) = @_;
1125         my $notPermitted = qr{(?:
1126                 ^(?:
1127                         $Modifier|
1128                         $Storage|
1129                         $Type|
1130                         DEFINE_\S+
1131                 )$|
1132                 ^(?:
1133                         goto|
1134                         return|
1135                         case|
1136                         else|
1137                         asm|__asm__|
1138                         do
1139                 )(?:\s|$)|
1140                 ^(?:typedef|struct|enum)\b|
1141                 ^\#
1142             )}x;
1143         warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1144         if ($possible !~ $notPermitted) {
1145                 # Check for modifiers.
1146                 $possible =~ s/\s*$Storage\s*//g;
1147                 $possible =~ s/\s*$Sparse\s*//g;
1148                 if ($possible =~ /^\s*$/) {
1149
1150                 } elsif ($possible =~ /\s/) {
1151                         $possible =~ s/\s*(?:$Type|\#\#)\s*//g;
1152                         for my $modifier (split(' ', $possible)) {
1153                                 if ($modifier !~ $notPermitted) {
1154                                         warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1155                                         push(@modifierList, $modifier);
1156                                 }
1157                         }
1158
1159                 } else {
1160                         warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1161                         push(@typeList, $possible);
1162                 }
1163                 build_types();
1164         } else {
1165                 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1166         }
1167 }
1168
1169 my $prefix = '';
1170
1171 sub report {
1172         my ($level, $msg) = @_;
1173         if (defined $tst_only && $msg !~ /\Q$tst_only\E/) {
1174                 return 0;
1175         }
1176
1177         my $output = '';
1178         my $do_color = $color && !$github;
1179         $output .= BOLD if $do_color;
1180         $output .= $prefix;
1181         $output .= RED if $do_color && $level eq 'ERROR';
1182         $output .= MAGENTA if $do_color && $level eq 'WARNING';
1183         $output .= $level . ':' if !$github;
1184         $output .= RESET if $do_color;
1185         $output .= ' ' if (!$github);
1186         $output .= $msg . "\n";
1187
1188         $output = (split('\n', $output))[0] . "\n" if ($terse);
1189
1190         push(our @report, $output);
1191
1192         return 1;
1193 }
1194 sub report_dump {
1195         our @report;
1196 }
1197 sub ERROR {
1198         if (report("ERROR", $_[0])) {
1199                 our $clean = 0;
1200                 our $cnt_error++;
1201         }
1202 }
1203 sub WARN {
1204         if (report("WARNING", $_[0])) {
1205                 our $clean = 0;
1206                 our $cnt_warn++;
1207         }
1208 }
1209
1210 # According to tests/qtest/bios-tables-test.c: do not
1211 # change expected file in the same commit with adding test
1212 sub checkfilename {
1213         my ($name, $acpi_testexpected, $acpi_nontestexpected) = @_;
1214
1215         # Note: shell script that rebuilds the expected files is in the same
1216         # directory as files themselves.
1217         # Note: allowed diff list can be changed both when changing expected
1218         # files and when changing tests.
1219         if ($name =~ m#^tests/data/acpi/# and not $name =~ m#^\.sh$#) {
1220                 $$acpi_testexpected = $name;
1221         } elsif ($name !~ m#^tests/qtest/bios-tables-test-allowed-diff.h$#) {
1222                 $$acpi_nontestexpected = $name;
1223         }
1224         if (defined $$acpi_testexpected and defined $$acpi_nontestexpected) {
1225                 ERROR("Do not add expected files together with tests, " .
1226                       "follow instructions in " .
1227                       "tests/qtest/bios-tables-test.c: both " .
1228                       $$acpi_testexpected . " and " .
1229                       $$acpi_nontestexpected . " found\n");
1230         }
1231 }
1232
1233 sub process {
1234         my $filename = shift;
1235
1236         my $linenr=0;
1237         my $prevline="";
1238         my $prevrawline="";
1239         my $stashline="";
1240         my $stashrawline="";
1241
1242         my $length;
1243         my $indent;
1244         my $previndent=0;
1245         my $stashindent=0;
1246
1247         our $clean = 1;
1248         my $signoff = 0;
1249         my $is_patch = 0;
1250
1251         my $in_header_lines = $file ? 0 : 1;
1252         my $in_commit_log = 0;          #Scanning lines before patch
1253         my $non_utf8_charset = 0;
1254
1255         our @report = ();
1256         our $cnt_lines = 0;
1257         our $cnt_error = 0;
1258         our $cnt_warn = 0;
1259         our $cnt_chk = 0;
1260
1261         # Trace the real file/line as we go.
1262         my $realfile = '';
1263         my $realline = 0;
1264         my $realcnt = 0;
1265         my $here = '';
1266         my $in_comment = 0;
1267         my $comment_edge = 0;
1268         my $first_line = 0;
1269         my $p1_prefix = '';
1270
1271         my $prev_values = 'E';
1272
1273         # suppression flags
1274         my %suppress_ifbraces;
1275         my %suppress_whiletrailers;
1276         my %suppress_export;
1277
1278         my $acpi_testexpected;
1279         my $acpi_nontestexpected;
1280
1281         # Pre-scan the patch sanitizing the lines.
1282
1283         sanitise_line_reset();
1284         my $line;
1285         foreach my $rawline (@rawlines) {
1286                 $linenr++;
1287                 $line = $rawline;
1288
1289                 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1290                         $realline=$1-1;
1291                         if (defined $2) {
1292                                 $realcnt=$3+1;
1293                         } else {
1294                                 $realcnt=1+1;
1295                         }
1296                         $in_comment = 0;
1297
1298                         # Guestimate if this is a continuing comment.  Run
1299                         # the context looking for a comment "edge".  If this
1300                         # edge is a close comment then we must be in a comment
1301                         # at context start.
1302                         my $edge;
1303                         my $cnt = $realcnt;
1304                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1305                                 next if (defined $rawlines[$ln - 1] &&
1306                                          $rawlines[$ln - 1] =~ /^-/);
1307                                 $cnt--;
1308                                 #print "RAW<$rawlines[$ln - 1]>\n";
1309                                 last if (!defined $rawlines[$ln - 1]);
1310                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1311                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1312                                         ($edge) = $1;
1313                                         last;
1314                                 }
1315                         }
1316                         if (defined $edge && $edge eq '*/') {
1317                                 $in_comment = 1;
1318                         }
1319
1320                         # Guestimate if this is a continuing comment.  If this
1321                         # is the start of a diff block and this line starts
1322                         # ' *' then it is very likely a comment.
1323                         if (!defined $edge &&
1324                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1325                         {
1326                                 $in_comment = 1;
1327                         }
1328
1329                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1330                         sanitise_line_reset($in_comment);
1331
1332                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1333                         # Standardise the strings and chars within the input to
1334                         # simplify matching -- only bother with positive lines.
1335                         $line = sanitise_line($rawline);
1336                 }
1337                 push(@lines, $line);
1338
1339                 if ($realcnt > 1) {
1340                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
1341                 } else {
1342                         $realcnt = 0;
1343                 }
1344
1345                 #print "==>$rawline\n";
1346                 #print "-->$line\n";
1347         }
1348
1349         $prefix = '';
1350
1351         $realcnt = 0;
1352         $linenr = 0;
1353         foreach my $line (@lines) {
1354                 $linenr++;
1355
1356                 my $rawline = $rawlines[$linenr - 1];
1357
1358 #extract the line range in the file after the patch is applied
1359                 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1360                         $is_patch = 1;
1361                         $first_line = $linenr + 1;
1362                         $realline=$1-1;
1363                         if (defined $2) {
1364                                 $realcnt=$3+1;
1365                         } else {
1366                                 $realcnt=1+1;
1367                         }
1368                         annotate_reset();
1369                         $prev_values = 'E';
1370
1371                         %suppress_ifbraces = ();
1372                         %suppress_whiletrailers = ();
1373                         %suppress_export = ();
1374                         next;
1375
1376 # track the line number as we move through the hunk, note that
1377 # new versions of GNU diff omit the leading space on completely
1378 # blank context lines so we need to count that too.
1379                 } elsif ($line =~ /^( |\+|$)/) {
1380                         $realline++;
1381                         $realcnt-- if ($realcnt != 0);
1382
1383                         # Measure the line length and indent.
1384                         ($length, $indent) = line_stats($rawline);
1385
1386                         # Track the previous line.
1387                         ($prevline, $stashline) = ($stashline, $line);
1388                         ($previndent, $stashindent) = ($stashindent, $indent);
1389                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1390
1391                         #warn "line<$line>\n";
1392
1393                 } elsif ($realcnt == 1) {
1394                         $realcnt--;
1395                 }
1396
1397                 my $hunk_line = ($realcnt != 0);
1398
1399 #make up the handle for any error we report on this line
1400                 $prefix = "$filename:$realline: " if ($emacs && $file);
1401                 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1402                 $prefix = "::error file=$filename,line=$realline:\:" if ($github && $file);
1403                 $prefix = "::error file=$realfile,line=$linenr:\:" if ($github && !$file);
1404
1405                 $here = "#$linenr: " if (!$file);
1406                 $here = "#$realline: " if ($file);
1407
1408                 # extract the filename as it passes
1409                 if ($line =~ /^diff --git.*?(\S+)$/) {
1410                         $realfile = $1;
1411                         $realfile =~ s@^([^/]*)/@@ if (!$file);
1412                         checkfilename($realfile, \$acpi_testexpected, \$acpi_nontestexpected);
1413                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1414                         $realfile = $1;
1415                         $realfile =~ s@^([^/]*)/@@ if (!$file);
1416                         checkfilename($realfile, \$acpi_testexpected, \$acpi_nontestexpected);
1417
1418                         $p1_prefix = $1;
1419                         if (!$file && $tree && $p1_prefix ne '' && defined $root &&
1420                             -e "$root/$p1_prefix") {
1421                                 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1422                         }
1423
1424                         next;
1425                 }
1426
1427                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1428
1429                 my $hereline = "$here\n$rawline\n";
1430                 my $herecurr = "$here\n$rawline\n";
1431                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1432
1433                 $cnt_lines++ if ($realcnt != 0);
1434
1435 # Check for incorrect file permissions
1436                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1437                         my $permhere = $here . "FILE: $realfile\n";
1438                         if ($realfile =~ /(\bMakefile(?:\.objs)?|\.c|\.cc|\.cpp|\.h|\.mak|\.[sS])$/) {
1439                                 ERROR("do not set execute permissions for source files\n" . $permhere);
1440                         }
1441                 }
1442
1443 # Accept git diff extended headers as valid patches
1444                 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1445                         $is_patch = 1;
1446                 }
1447
1448 # Filter out bad email addresses.
1449                 if ($line =~ /^(Author|From): .*noreply.*/) {
1450                     ERROR("Real email adress is needed\n" . $herecurr);
1451                 }
1452
1453 #check the patch for a signoff:
1454                 if ($line =~ /^\s*signed-off-by:/i) {
1455                         # This is a signoff, if ugly, so do not double report.
1456                         $in_commit_log = 0;
1457
1458                         if (!($line =~ /^\s*Signed-off-by:/)) {
1459                                 ERROR("The correct form is \"Signed-off-by\"\n" .
1460                                         $herecurr);
1461                         }
1462                         if ($line =~ /^\s*signed-off-by:\S/i) {
1463                                 ERROR("space required after Signed-off-by:\n" .
1464                                         $herecurr);
1465                         }
1466                 }
1467
1468 # Check for wrappage within a valid hunk of the file
1469                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1470                         ERROR("patch seems to be corrupt (line wrapped?)\n" .
1471                                 $herecurr) if (!$emitted_corrupt++);
1472                 }
1473
1474 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1475                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1476                     $rawline !~ m/^$UTF8*$/) {
1477                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1478
1479                         my $blank = copy_spacing($rawline);
1480                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1481                         my $hereptr = "$hereline$ptr\n";
1482
1483                         ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1484                 }
1485
1486                 if ($rawline =~ m/$UTF8_MOJIBAKE/) {
1487                         ERROR("Doubly-encoded UTF-8\n" . $herecurr);
1488                 }
1489 # Check if it's the start of a commit log
1490 # (not a header line and we haven't seen the patch filename)
1491                 if ($in_header_lines && $realfile =~ /^$/ &&
1492                     !($rawline =~ /^\s+\S/ ||
1493                       $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
1494                         $in_header_lines = 0;
1495                         $in_commit_log = 1;
1496                 }
1497
1498 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1499 # declined it, i.e defined some charset where it is missing.
1500                 if ($in_header_lines &&
1501                     $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1502                     $1 !~ /utf-8/i) {
1503                         $non_utf8_charset = 1;
1504                 }
1505
1506                 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1507                     $rawline =~ /$NON_ASCII_UTF8/) {
1508                         WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1509                 }
1510
1511 # ignore non-hunk lines and lines being removed
1512                 next if (!$hunk_line || $line =~ /^-/);
1513
1514 #trailing whitespace
1515                 if ($line =~ /^\+.*\015/) {
1516                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1517                         ERROR("DOS line endings\n" . $herevet);
1518
1519                 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1520                          $realfile =~ /^docs\/.+\.md/) {
1521                     if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1522                         # TODO: properly check we're in a code block
1523                         #       (surrounding text is 4-column aligned)
1524                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1525                         ERROR("code blocks in documentation should have " .
1526                               "empty lines with exactly 4 columns of " .
1527                               "whitespace\n" . $herevet);
1528                     }
1529                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1530                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1531                         ERROR("trailing whitespace\n" . $herevet);
1532                         $rpt_cleaners = 1;
1533                 }
1534
1535 # check we are in a valid source file if not then ignore this hunk
1536                 next if ($realfile !~ /$SrcFile/);
1537
1538 #120 column limit; exempt URLs, if no other words on line
1539                 if ($line =~ /^\+/ &&
1540                     !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1541                     !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1542                     $length > 80 &&
1543                     $realfile !~ /\/tests\//)
1544                 {
1545                         if ($length > 120) {
1546                                 ERROR("line over 120 characters\n" . $herecurr);
1547                         } else {
1548                                 WARN("line over 80 characters\n" . $herecurr);
1549                         }
1550                 }
1551
1552 # check for spaces before a quoted newline
1553                 if ($rawline =~ /^.*\".*\s\\n/) {
1554                         ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1555                 }
1556
1557 # check for adding lines without a newline.
1558                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1559                         ERROR("adding a line without newline at end of file\n" . $herecurr);
1560                 }
1561
1562 # check for RCS/CVS revision markers
1563                 if ($rawline =~ /^\+.*\$(FreeBSD|Revision|Log|Id)(?:\$|\b)/) {
1564                         ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1565                 }
1566
1567 # check we are in a valid C source file if not then ignore this hunk
1568                 next if ($realfile !~ /\.(h|c|cpp)$/);
1569
1570 # Block comment styles
1571
1572                 # Block comments use /* on a line of its own
1573                 if ($rawline !~ m@^\+.*/\*.*\*/[ \t)}]*$@ &&    #inline /*...*/
1574                     $rawline =~ m@^\+.*/\*[*-]?+[ \t]*[^ \t]@) { # /* or /** or /*- non-blank
1575                         WARN("Block comments use a leading /* on a separate line\n" . $herecurr);
1576                 }
1577
1578 # Block comments use * on subsequent lines
1579                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
1580                     $prevrawline =~ /^\+.*?\/\*/ &&             #starting /*
1581                     $prevrawline !~ /\*\/[ \t]*$/ &&            #no trailing */
1582                     $rawline =~ /^\+/ &&                        #line is new
1583                     $rawline !~ /^\+[ \t]*\*/) {                #no leading *
1584                         WARN("Block comments use * on subsequent lines\n" . $hereprev);
1585                 }
1586
1587 # Block comments use */ on trailing lines
1588                 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&       #trailing */
1589                     $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&      #inline /*...*/
1590                     $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&       #trailing **/
1591                     $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {    #non blank */
1592                         WARN("Block comments use a trailing */ on a separate line\n" . $herecurr);
1593                 }
1594
1595 # Block comment * alignment
1596                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
1597                     $line =~ /^\+[ \t]*$;/ &&                   #leading comment
1598                     $rawline =~ /^\+[ \t]*\*/ &&                #leading *
1599                     (($prevrawline =~ /^\+.*?\/\*/ &&           #leading /*
1600                       $prevrawline !~ /\*\/[ \t]*$/) ||         #no trailing */
1601                      $prevrawline =~ /^\+[ \t]*\*/)) {          #leading *
1602                         my $oldindent;
1603                         $prevrawline =~ m@^\+([ \t]*/?)\*@;
1604                         if (defined($1)) {
1605                                 $oldindent = expand_tabs($1);
1606                         } else {
1607                                 $prevrawline =~ m@^\+(.*/?)\*@;
1608                                 $oldindent = expand_tabs($1);
1609                         }
1610                         $rawline =~ m@^\+([ \t]*)\*@;
1611                         my $newindent = $1;
1612                         $newindent = expand_tabs($newindent);
1613                         if (length($oldindent) ne length($newindent)) {
1614                                 WARN("Block comments should align the * on each line\n" . $hereprev);
1615                         }
1616                 }
1617
1618 # Check for potential 'bare' types
1619                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1620                     $realline_next);
1621                 if ($realcnt && $line =~ /.\s*\S/) {
1622                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1623                                 ctx_statement_block($linenr, $realcnt, 0);
1624                         $stat =~ s/\n./\n /g;
1625                         $cond =~ s/\n./\n /g;
1626
1627                         # Find the real next line.
1628                         $realline_next = $line_nr_next;
1629                         if (defined $realline_next &&
1630                             (!defined $lines[$realline_next - 1] ||
1631                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1632                                 $realline_next++;
1633                         }
1634
1635                         my $s = $stat;
1636                         $s =~ s/{.*$//s;
1637
1638                         # Ignore goto labels.
1639                         if ($s =~ /$Ident:\*$/s) {
1640
1641                         # Ignore functions being called
1642                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1643
1644                         } elsif ($s =~ /^.\s*else\b/s) {
1645
1646                         # declarations always start with types
1647                         } elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) {
1648                                 my $type = $1;
1649                                 $type =~ s/\s+/ /g;
1650                                 possible($type, "A:" . $s);
1651
1652                         # definitions in global scope can only start with types
1653                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1654                                 possible($1, "B:" . $s);
1655                         }
1656
1657                         # any (foo ... *) is a pointer cast, and foo is a type
1658                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1659                                 possible($1, "C:" . $s);
1660                         }
1661
1662                         # Check for any sort of function declaration.
1663                         # int foo(something bar, other baz);
1664                         # void (*store_gdt)(x86_descr_ptr *);
1665                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1666                                 my ($name_len) = length($1);
1667
1668                                 my $ctx = $s;
1669                                 substr($ctx, 0, $name_len + 1, '');
1670                                 $ctx =~ s/\)[^\)]*$//;
1671
1672                                 for my $arg (split(/\s*,\s*/, $ctx)) {
1673                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1674
1675                                                 possible($1, "D:" . $s);
1676                                         }
1677                                 }
1678                         }
1679
1680                 }
1681
1682 #
1683 # Checks which may be anchored in the context.
1684 #
1685
1686 # Check for switch () and associated case and default
1687 # statements should be at the same indent.
1688                 if ($line=~/\bswitch\s*\(.*\)/) {
1689                         my $err = '';
1690                         my $sep = '';
1691                         my @ctx = ctx_block_outer($linenr, $realcnt);
1692                         shift(@ctx);
1693                         for my $ctx (@ctx) {
1694                                 my ($clen, $cindent) = line_stats($ctx);
1695                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1696                                                         $indent != $cindent) {
1697                                         $err .= "$sep$ctx\n";
1698                                         $sep = '';
1699                                 } else {
1700                                         $sep = "[...]\n";
1701                                 }
1702                         }
1703                         if ($err ne '') {
1704                                 ERROR("switch and case should be at the same indent\n$hereline$err");
1705                         }
1706                 }
1707
1708 # if/while/etc brace do not go on next line, unless defining a do while loop,
1709 # or if that brace on the next line is for something else
1710                 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1711                         my $pre_ctx = "$1$2";
1712
1713                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1714                         my $ctx_cnt = $realcnt - $#ctx - 1;
1715                         my $ctx = join("\n", @ctx);
1716
1717                         my $ctx_ln = $linenr;
1718                         my $ctx_skip = $realcnt;
1719
1720                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1721                                         defined $lines[$ctx_ln - 1] &&
1722                                         $lines[$ctx_ln - 1] =~ /^-/)) {
1723                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1724                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1725                                 $ctx_ln++;
1726                         }
1727
1728                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1729                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1730
1731                         # The length of the "previous line" is checked against 80 because it
1732                         # includes the + at the beginning of the line (if the actual line has
1733                         # 79 or 80 characters, it is no longer possible to add a space and an
1734                         # opening brace there)
1735                         if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1736                             defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1737                             defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1738                                 ERROR("that open brace { should be on the previous line\n" .
1739                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1740                         }
1741                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1742                             $ctx =~ /\)\s*\;\s*$/ &&
1743                             defined $lines[$ctx_ln - 1])
1744                         {
1745                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1746                                 if ($nindent > $indent) {
1747                                         ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1748                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1749                                 }
1750                         }
1751                 }
1752
1753 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
1754                 if ($line =~ /while\s*\((0|false)\);/) {
1755                         ERROR("suspicious ; after while (0)\n" . $herecurr);
1756                 }
1757
1758 # Check superfluous trailing ';'
1759                 if ($line =~ /;;$/) {
1760                         ERROR("superfluous trailing semicolon\n" . $herecurr);
1761                 }
1762
1763 # Check relative indent for conditionals and blocks.
1764                 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1765                         my ($s, $c) = ($stat, $cond);
1766
1767                         substr($s, 0, length($c), '');
1768
1769                         # Make sure we remove the line prefixes as we have
1770                         # none on the first line, and are going to re-add them
1771                         # where necessary.
1772                         $s =~ s/\n./\n/gs;
1773
1774                         # Find out how long the conditional actually is.
1775                         my @newlines = ($c =~ /\n/gs);
1776                         my $cond_lines = 1 + $#newlines;
1777
1778                         # We want to check the first line inside the block
1779                         # starting at the end of the conditional, so remove:
1780                         #  1) any blank line termination
1781                         #  2) any opening brace { on end of the line
1782                         #  3) any do (...) {
1783                         my $continuation = 0;
1784                         my $check = 0;
1785                         $s =~ s/^.*\bdo\b//;
1786                         $s =~ s/^\s*\{//;
1787                         if ($s =~ s/^\s*\\//) {
1788                                 $continuation = 1;
1789                         }
1790                         if ($s =~ s/^\s*?\n//) {
1791                                 $check = 1;
1792                                 $cond_lines++;
1793                         }
1794
1795                         # Also ignore a loop construct at the end of a
1796                         # preprocessor statement.
1797                         if (($prevline =~ /^.\s*#\s*define\s/ ||
1798                             $prevline =~ /\\\s*$/) && $continuation == 0) {
1799                                 $check = 0;
1800                         }
1801
1802                         my $cond_ptr = -1;
1803                         $continuation = 0;
1804                         while ($cond_ptr != $cond_lines) {
1805                                 $cond_ptr = $cond_lines;
1806
1807                                 # If we see an #else/#elif then the code
1808                                 # is not linear.
1809                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1810                                         $check = 0;
1811                                 }
1812
1813                                 # Ignore:
1814                                 #  1) blank lines, they should be at 0,
1815                                 #  2) preprocessor lines, and
1816                                 #  3) labels.
1817                                 if ($continuation ||
1818                                     $s =~ /^\s*?\n/ ||
1819                                     $s =~ /^\s*#\s*?/ ||
1820                                     $s =~ /^\s*$Ident\s*:/) {
1821                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1822                                         if ($s =~ s/^.*?\n//) {
1823                                                 $cond_lines++;
1824                                         }
1825                                 }
1826                         }
1827
1828                         my (undef, $sindent) = line_stats("+" . $s);
1829                         my $stat_real = raw_line($linenr, $cond_lines);
1830
1831                         # Check if either of these lines are modified, else
1832                         # this is not this patch's fault.
1833                         if (!defined($stat_real) ||
1834                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1835                                 $check = 0;
1836                         }
1837                         if (defined($stat_real) && $cond_lines > 1) {
1838                                 $stat_real = "[...]\n$stat_real";
1839                         }
1840
1841                         #print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n";
1842
1843                         if ($check && (($sindent % 4) != 0 ||
1844                             ($sindent <= $indent && $s ne ''))) {
1845                                 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1846                         }
1847                 }
1848
1849                 # Track the 'values' across context and added lines.
1850                 my $opline = $line; $opline =~ s/^./ /;
1851                 my ($curr_values, $curr_vars) =
1852                                 annotate_values($opline . "\n", $prev_values);
1853                 $curr_values = $prev_values . $curr_values;
1854                 if ($dbg_values) {
1855                         my $outline = $opline; $outline =~ s/\t/ /g;
1856                         print "$linenr > .$outline\n";
1857                         print "$linenr > $curr_values\n";
1858                         print "$linenr >  $curr_vars\n";
1859                 }
1860                 $prev_values = substr($curr_values, -1);
1861
1862 #ignore lines not being added
1863                 if ($line=~/^[^\+]/) {next;}
1864
1865 # check for initialisation to aggregates open brace on the next line
1866                 if ($line =~ /^.\s*\{/ &&
1867                     $prevline =~ /(?:^|[^=])=\s*$/) {
1868                         ERROR("that open brace { should be on the previous line\n" . $hereprev);
1869                 }
1870
1871 #
1872 # Checks which are anchored on the added line.
1873 #
1874
1875 # check for malformed paths in #include statements (uses RAW line)
1876                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1877                         my $path = $1;
1878                         if ($path =~ m{//}) {
1879                                 ERROR("malformed #include filename\n" .
1880                                         $herecurr);
1881                         }
1882                 }
1883
1884 # Remove C99 comments.
1885                 $line =~ s@//.*@@;
1886                 $opline =~ s@//.*@@;
1887
1888 # * goes on variable not on type
1889                 # (char*[ const])
1890                 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
1891                         my ($from, $to) = ($1, $1);
1892
1893                         # Should start with a space.
1894                         $to =~ s/^(\S)/ $1/;
1895                         # Should not end with a space.
1896                         $to =~ s/\s+$//;
1897                         # '*'s should not have spaces between.
1898                         while ($to =~ s/\*\s+\*/\*\*/) {
1899                         }
1900
1901                         #print "from<$from> to<$to>\n";
1902                         if ($from ne $to) {
1903                                 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr);
1904                         }
1905                 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
1906                         my ($from, $to, $ident) = ($1, $1, $2);
1907
1908                         # Should start with a space.
1909                         $to =~ s/^(\S)/ $1/;
1910                         # Should not end with a space.
1911                         $to =~ s/\s+$//;
1912                         # '*'s should not have spaces between.
1913                         while ($to =~ s/\*\s+\*/\*\*/) {
1914                         }
1915                         # Modifiers should have spaces.
1916                         $to =~ s/(\b$Modifier$)/$1 /;
1917
1918                         #print "from<$from> to<$to> ident<$ident>\n";
1919                         if ($from ne $to && $ident !~ /^$Modifier$/) {
1920                                 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr);
1921                         }
1922                 }
1923
1924 # function brace can't be on same line, except for #defines of do while,
1925 # or if closed on same line
1926                 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
1927                     !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
1928                         ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
1929                 }
1930
1931 # missing space after union, struct or enum definition
1932                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
1933                     ERROR("missing space after $1 definition\n" . $herecurr);
1934                 }
1935
1936 # check for spacing round square brackets; allowed:
1937 #  1. with a type on the left -- int [] a;
1938 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
1939 #  3. inside a curly brace -- = { [0...10] = 5 }
1940 #  4. after a comma -- [1] = 5, [2] = 6
1941 #  5. in a macro definition -- #define abc(x) [x] = y
1942                 while ($line =~ /(.*?\s)\[/g) {
1943                         my ($where, $prefix) = ($-[1], $1);
1944                         if ($prefix !~ /$Type\s+$/ &&
1945                             ($where != 0 || $prefix !~ /^.\s+$/) &&
1946                             $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
1947                             $prefix !~ /[,{:]\s+$/) {
1948                                 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
1949                         }
1950                 }
1951
1952 # check for spaces between functions and their parentheses.
1953                 while ($line =~ /($Ident)\s+\(/g) {
1954                         my $name = $1;
1955                         my $ctx_before = substr($line, 0, $-[1]);
1956                         my $ctx = "$ctx_before$name";
1957
1958                         # Ignore those directives where spaces _are_ permitted.
1959                         if ($name =~ /^(?:
1960                                 if|for|while|switch|return|case|
1961                                 volatile|__volatile__|coroutine_fn|
1962                                 __attribute__|format|__extension__|
1963                                 asm|__asm__)$/x)
1964                         {
1965
1966                         # Ignore 'catch (...)' in C++
1967                         } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
1968
1969                         # cpp #define statements have non-optional spaces, ie
1970                         # if there is a space between the name and the open
1971                         # parenthesis it is simply not a parameter group.
1972                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
1973
1974                         # cpp #elif statement condition may start with a (
1975                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
1976
1977                         # If this whole things ends with a type its most
1978                         # likely a typedef for a function.
1979                         } elsif ($ctx =~ /$Type$/) {
1980
1981                         } else {
1982                                 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
1983                         }
1984                 }
1985 # Check operator spacing.
1986                 if (!($line=~/\#\s*include/)) {
1987                         my $ops = qr{
1988                                 <<=|>>=|<=|>=|==|!=|
1989                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
1990                                 =>|->|<<|>>|<|>|=|!|~|
1991                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
1992                                 \?|::|:
1993                         }x;
1994                         my @elements = split(/($ops|;)/, $opline);
1995                         my $off = 0;
1996
1997                         my $blank = copy_spacing($opline);
1998
1999                         for (my $n = 0; $n < $#elements; $n += 2) {
2000                                 $off += length($elements[$n]);
2001
2002                                 # Pick up the preceding and succeeding characters.
2003                                 my $ca = substr($opline, 0, $off);
2004                                 my $cc = '';
2005                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2006                                         $cc = substr($opline, $off + length($elements[$n + 1]));
2007                                 }
2008                                 my $cb = "$ca$;$cc";
2009
2010                                 my $a = '';
2011                                 $a = 'V' if ($elements[$n] ne '');
2012                                 $a = 'W' if ($elements[$n] =~ /\s$/);
2013                                 $a = 'C' if ($elements[$n] =~ /$;$/);
2014                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2015                                 $a = 'O' if ($elements[$n] eq '');
2016                                 $a = 'E' if ($ca =~ /^\s*$/);
2017
2018                                 my $op = $elements[$n + 1];
2019
2020                                 my $c = '';
2021                                 if (defined $elements[$n + 2]) {
2022                                         $c = 'V' if ($elements[$n + 2] ne '');
2023                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2024                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2025                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2026                                         $c = 'O' if ($elements[$n + 2] eq '');
2027                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2028                                 } else {
2029                                         $c = 'E';
2030                                 }
2031
2032                                 my $ctx = "${a}x${c}";
2033
2034                                 my $at = "(ctx:$ctx)";
2035
2036                                 my $ptr = substr($blank, 0, $off) . "^";
2037                                 my $hereptr = "$hereline$ptr\n";
2038
2039                                 # Pull out the value of this operator.
2040                                 my $op_type = substr($curr_values, $off + 1, 1);
2041
2042                                 # Get the full operator variant.
2043                                 my $opv = $op . substr($curr_vars, $off, 1);
2044
2045                                 # Ignore operators passed as parameters.
2046                                 if ($op_type ne 'V' &&
2047                                     $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2048
2049 #                               # Ignore comments
2050 #                               } elsif ($op =~ /^$;+$/) {
2051
2052                                 # ; should have either the end of line or a space or \ after it
2053                                 } elsif ($op eq ';') {
2054                                         if ($ctx !~ /.x[WEBC]/ &&
2055                                             $cc !~ /^\\/ && $cc !~ /^;/) {
2056                                                 ERROR("space required after that '$op' $at\n" . $hereptr);
2057                                         }
2058
2059                                 # // is a comment
2060                                 } elsif ($op eq '//') {
2061
2062                                 # Ignore : used in class declaration in C++
2063                                 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2064                                                  $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2065
2066                                 # No spaces for:
2067                                 #   ->
2068                                 #   :   when part of a bitfield
2069                                 } elsif ($op eq '->' || $opv eq ':B') {
2070                                         if ($ctx =~ /Wx.|.xW/) {
2071                                                 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2072                                         }
2073
2074                                 # , must have a space on the right.
2075                                 # not required when having a single },{ on one line
2076                                 } elsif ($op eq ',') {
2077                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2078                                             ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
2079                                                 ERROR("space required after that '$op' $at\n" . $hereptr);
2080                                         }
2081
2082                                 # '*' as part of a type definition -- reported already.
2083                                 } elsif ($opv eq '*_') {
2084                                         #warn "'*' is part of type\n";
2085
2086                                 # unary operators should have a space before and
2087                                 # none after.  May be left adjacent to another
2088                                 # unary operator, or a cast
2089                                 } elsif ($op eq '!' || $op eq '~' ||
2090                                          $opv eq '*U' || $opv eq '-U' ||
2091                                          $opv eq '&U' || $opv eq '&&U') {
2092                                         if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2093                                                 # '~' used as a name of Destructor
2094
2095                                         } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2096                                                 ERROR("space required before that '$op' $at\n" . $hereptr);
2097                                         }
2098                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2099                                                 # A unary '*' may be const
2100
2101                                         } elsif ($ctx =~ /.xW/) {
2102                                                 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2103                                         }
2104
2105                                 # unary ++ and unary -- are allowed no space on one side.
2106                                 } elsif ($op eq '++' or $op eq '--') {
2107                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2108                                                 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2109                                         }
2110                                         if ($ctx =~ /Wx[BE]/ ||
2111                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2112                                                 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2113                                         }
2114                                         if ($ctx =~ /ExW/) {
2115                                                 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2116                                         }
2117
2118                                 # A colon needs no spaces before when it is
2119                                 # terminating a case value or a label.
2120                                 } elsif ($opv eq ':C' || $opv eq ':L') {
2121                                         if ($ctx =~ /Wx./) {
2122                                                 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2123                                         }
2124
2125                                 # All the others need spaces both sides.
2126                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2127                                         my $ok = 0;
2128
2129                                         if ($realfile =~ /\.cpp|\.h$/) {
2130                                                 # Ignore template arguments <...> in C++
2131                                                 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2132                                                         $ok = 1;
2133                                                 }
2134
2135                                                 # Ignore :: in C++
2136                                                 if ($op eq '::') {
2137                                                         $ok = 1;
2138                                                 }
2139                                         }
2140
2141                                         # Ignore email addresses <foo@bar>
2142                                         if (($op eq '<' &&
2143                                              $cc =~ /^\S+\@\S+>/) ||
2144                                             ($op eq '>' &&
2145                                              $ca =~ /<\S+\@\S+$/))
2146                                         {
2147                                                 $ok = 1;
2148                                         }
2149
2150                                         # Ignore ?:
2151                                         if (($opv eq ':O' && $ca =~ /\?$/) ||
2152                                             ($op eq '?' && $cc =~ /^:/)) {
2153                                                 $ok = 1;
2154                                         }
2155
2156                                         if ($ok == 0) {
2157                                                 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2158                                         }
2159                                 }
2160                                 $off += length($elements[$n + 1]);
2161                         }
2162                 }
2163
2164 #need space before brace following if, while, etc
2165                 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2166                     $line =~ /do\{/) {
2167                         ERROR("space required before the open brace '{'\n" . $herecurr);
2168                 }
2169
2170 # closing brace should have a space following it when it has anything
2171 # on the line
2172                 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2173                         ERROR("space required after that close brace '}'\n" . $herecurr);
2174                 }
2175
2176 # check spacing on square brackets
2177                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2178                         ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2179                 }
2180                 if ($line =~ /\s\]/) {
2181                         ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2182                 }
2183
2184 # check spacing on parentheses
2185                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2186                     $line !~ /for\s*\(\s+;/) {
2187                         ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2188                 }
2189                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2190                     $line !~ /for\s*\(.*;\s+\)/ &&
2191                     $line !~ /:\s+\)/) {
2192                         ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2193                 }
2194
2195                 if ($line =~ /^.\s*(Q(?:S?LIST|SIMPLEQ|TAILQ)_HEAD)\s*\(\s*[^,]/ &&
2196                     $line !~ /^.typedef/) {
2197                     ERROR("named $1 should be typedefed separately\n" . $herecurr);
2198                 }
2199
2200 # Return needs parens
2201                 if ($line =~ /^.\s*return [^(]/) {
2202                     ERROR("parentheses required on return\n" . $herecurr);
2203                 }
2204
2205 # Need a space before open parenthesis after if, while etc
2206                 if ($line=~/\b(if|while|for|switch|return)\(/) {
2207                         ERROR("space required before the open parenthesis '('\n" . $herecurr);
2208                 }
2209
2210 # Check for illegal assignment in if conditional -- and check for trailing
2211 # statements after the conditional.
2212                 if ($line =~ /do\s*(?!{)/) {
2213                         my ($stat_next) = ctx_statement_block($line_nr_next,
2214                                                 $remain_next, $off_next);
2215                         $stat_next =~ s/\n./\n /g;
2216                         ##print "stat<$stat> stat_next<$stat_next>\n";
2217
2218                         if ($stat_next =~ /^\s*while\b/) {
2219                                 # If the statement carries leading newlines,
2220                                 # then count those as offsets.
2221                                 my ($whitespace) =
2222                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2223                                 my $offset =
2224                                         statement_rawlines($whitespace) - 1;
2225
2226                                 $suppress_whiletrailers{$line_nr_next +
2227                                                                 $offset} = 1;
2228                         }
2229                 }
2230                 if (!defined $suppress_whiletrailers{$linenr} &&
2231                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2232                         my ($s, $c) = ($stat, $cond);
2233
2234 #                       if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2235 #                               ERROR("do not use assignment in if condition\n" . $herecurr);
2236 #                       }
2237
2238                         # Find out what is on the end of the line after the
2239                         # conditional.
2240                         substr($s, 0, length($c), '');
2241                         $s =~ s/\n.*//g;
2242                         $s =~ s/$;//g;  # Remove any comments
2243                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2244                             $c !~ /}\s*while\s*/)
2245                         {
2246                                 # Find out how long the conditional actually is.
2247                                 my @newlines = ($c =~ /\n/gs);
2248                                 my $cond_lines = 1 + $#newlines;
2249                                 my $stat_real = '';
2250
2251                                 $stat_real = raw_line($linenr, $cond_lines)
2252                                                         . "\n" if ($cond_lines);
2253                                 if (defined($stat_real) && $cond_lines > 1) {
2254                                         $stat_real = "[...]\n$stat_real";
2255                                 }
2256
2257                                 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2258                         }
2259                 }
2260
2261 # Check for bitwise tests written as boolean
2262                 if ($line =~ /
2263                         (?:
2264                                 (?:\[|\(|\&\&|\|\|)
2265                                 \s*0[xX][0-9]+\s*
2266                                 (?:\&\&|\|\|)
2267                         |
2268                                 (?:\&\&|\|\|)
2269                                 \s*0[xX][0-9]+\s*
2270                                 (?:\&\&|\|\||\)|\])
2271                         )/x)
2272                 {
2273                         ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2274                 }
2275
2276 # if and else should not have general statements after it
2277                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2278                         my $s = $1;
2279                         $s =~ s/$;//g;  # Remove any comments
2280                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2281                                 ERROR("trailing statements should be on next line\n" . $herecurr);
2282                         }
2283                 }
2284 # if should not continue a brace
2285                 if ($line =~ /}\s*if\b/) {
2286                         ERROR("trailing statements should be on next line\n" .
2287                                 $herecurr);
2288                 }
2289 # case and default should not have general statements after them
2290                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2291                     $line !~ /\G(?:
2292                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2293                         \s*return\s+
2294                     )/xg)
2295                 {
2296                         ERROR("trailing statements should be on next line\n" . $herecurr);
2297                 }
2298
2299                 # Check for }<nl>else {, these must be at the same
2300                 # indent level to be relevant to each other.
2301                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2302                                                 $previndent == $indent) {
2303                         ERROR("else should follow close brace '}'\n" . $hereprev);
2304                 }
2305
2306                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2307                                                 $previndent == $indent) {
2308                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2309
2310                         # Find out what is on the end of the line after the
2311                         # conditional.
2312                         substr($s, 0, length($c), '');
2313                         $s =~ s/\n.*//g;
2314
2315                         if ($s =~ /^\s*;/) {
2316                                 ERROR("while should follow close brace '}'\n" . $hereprev);
2317                         }
2318                 }
2319
2320 #no spaces allowed after \ in define
2321                 if ($line=~/\#\s*define.*\\\s$/) {
2322                         ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2323                 }
2324
2325 # multi-statement macros should be enclosed in a do while loop, grab the
2326 # first statement and ensure its the whole macro if its not enclosed
2327 # in a known good container
2328                 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2329                     $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2330                         my $ln = $linenr;
2331                         my $cnt = $realcnt;
2332                         my ($off, $dstat, $dcond, $rest);
2333                         my $ctx = '';
2334
2335                         my $args = defined($1);
2336
2337                         # Find the end of the macro and limit our statement
2338                         # search to that.
2339                         while ($cnt > 0 && defined $lines[$ln - 1] &&
2340                                 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2341                         {
2342                                 $ctx .= $rawlines[$ln - 1] . "\n";
2343                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2344                                 $ln++;
2345                         }
2346                         $ctx .= $rawlines[$ln - 1];
2347
2348                         ($dstat, $dcond, $ln, $cnt, $off) =
2349                                 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2350                         #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2351                         #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2352
2353                         # Extract the remainder of the define (if any) and
2354                         # rip off surrounding spaces, and trailing \'s.
2355                         $rest = '';
2356                         while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2357                                 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2358                                 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2359                                         $rest .= substr($lines[$ln - 1], $off) . "\n";
2360                                         $cnt--;
2361                                 }
2362                                 $ln++;
2363                                 $off = 0;
2364                         }
2365                         $rest =~ s/\\\n.//g;
2366                         $rest =~ s/^\s*//s;
2367                         $rest =~ s/\s*$//s;
2368
2369                         # Clean up the original statement.
2370                         if ($args) {
2371                                 substr($dstat, 0, length($dcond), '');
2372                         } else {
2373                                 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2374                         }
2375                         $dstat =~ s/$;//g;
2376                         $dstat =~ s/\\\n.//g;
2377                         $dstat =~ s/^\s*//s;
2378                         $dstat =~ s/\s*$//s;
2379
2380                         # Flatten any parentheses and braces
2381                         while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2382                                $dstat =~ s/\{[^\{\}]*\}/1/ ||
2383                                $dstat =~ s/\[[^\{\}]*\]/1/)
2384                         {
2385                         }
2386
2387                         my $exceptions = qr{
2388                                 $Declare|
2389                                 module_param_named|
2390                                 MODULE_PARAM_DESC|
2391                                 DECLARE_PER_CPU|
2392                                 DEFINE_PER_CPU|
2393                                 __typeof__\(|
2394                                 union|
2395                                 struct|
2396                                 \.$Ident\s*=\s*|
2397                                 ^\"|\"$
2398                         }x;
2399                         #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2400                         if ($rest ne '' && $rest ne ',') {
2401                                 if ($rest !~ /while\s*\(/ &&
2402                                     $dstat !~ /$exceptions/)
2403                                 {
2404                                         ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2405                                 }
2406
2407                         } elsif ($ctx !~ /;/) {
2408                                 if ($dstat ne '' &&
2409                                     $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2410                                     $dstat !~ /$exceptions/ &&
2411                                     $dstat !~ /^\.$Ident\s*=/ &&
2412                                     $dstat =~ /$Operators/)
2413                                 {
2414                                         ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2415                                 }
2416                         }
2417                 }
2418
2419 # check for missing bracing around if etc
2420                 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2421                         $line !~ /\#\s*if/) {
2422                         my $allowed = 0;
2423
2424                         # Check the pre-context.
2425                         if ($line =~ /(\}.*?)$/) {
2426                                 my $pre = $1;
2427
2428                                 if ($line !~ /else/) {
2429                                         print "APW: ALLOWED: pre<$pre> line<$line>\n"
2430                                                 if $dbg_adv_apw;
2431                                         $allowed = 1;
2432                                 }
2433                         }
2434                         my ($level, $endln, @chunks) =
2435                                 ctx_statement_full($linenr, $realcnt, 1);
2436                         if ($dbg_adv_apw) {
2437                             print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2438                             print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2439                                 if $#chunks >= 1;
2440                         }
2441                         if ($#chunks >= 0 && $level == 0) {
2442                                 my $seen = 0;
2443                                 my $herectx = $here . "\n";
2444                                 my $ln = $linenr - 1;
2445                                 for my $chunk (@chunks) {
2446                                         my ($cond, $block) = @{$chunk};
2447
2448                                         # If the condition carries leading newlines, then count those as offsets.
2449                                         my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2450                                         my $offset = statement_rawlines($whitespace) - 1;
2451
2452                                         #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2453
2454                                         # We have looked at and allowed this specific line.
2455                                         $suppress_ifbraces{$ln + $offset} = 1;
2456
2457                                         $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2458                                         $ln += statement_rawlines($block) - 1;
2459
2460                                         substr($block, 0, length($cond), '');
2461
2462                                         my $spaced_block = $block;
2463                                         $spaced_block =~ s/\n\+/ /g;
2464
2465                                         $seen++ if ($spaced_block =~ /^\s*\{/);
2466
2467                                         print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2468                                             if $dbg_adv_apw;
2469                                         if (statement_lines($cond) > 1) {
2470                                             print "APW: ALLOWED: cond<$cond>\n"
2471                                                 if $dbg_adv_apw;
2472                                             $allowed = 1;
2473                                         }
2474                                         if ($block =~/\b(?:if|for|while)\b/) {
2475                                             print "APW: ALLOWED: block<$block>\n"
2476                                                 if $dbg_adv_apw;
2477                                             $allowed = 1;
2478                                         }
2479                                         if (statement_block_size($block) > 1) {
2480                                             print "APW: ALLOWED: lines block<$block>\n"
2481                                                 if $dbg_adv_apw;
2482                                             $allowed = 1;
2483                                         }
2484                                 }
2485                                 $allowed=1; # disable for now.
2486                                 if ($seen != ($#chunks + 1) && !$allowed) {
2487                                         ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2488                                 }
2489                         }
2490                 }
2491                 if (!defined $suppress_ifbraces{$linenr - 1} &&
2492                                         $line =~ /\b(if|while|for|else)\b/ &&
2493                                         $line !~ /\#\s*if/ &&
2494                                         $line !~ /\#\s*else/) {
2495                         my $allowed = 0;
2496
2497                         # Check the pre-context.
2498                         if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2499                             my $pre = $1;
2500
2501                             if ($line !~ /else/) {
2502                                 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2503                                     if $dbg_adv_apw;
2504                                 $allowed = 1;
2505                             }
2506                         }
2507
2508                         my ($level, $endln, @chunks) =
2509                                 ctx_statement_full($linenr, $realcnt, $-[0]);
2510
2511                         # Check the condition.
2512                         my ($cond, $block) = @{$chunks[0]};
2513                         print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2514                             if $dbg_adv_checking;
2515                         if (defined $cond) {
2516                                 substr($block, 0, length($cond), '');
2517                         }
2518                         if (statement_lines($cond) > 1) {
2519                             print "APW: ALLOWED: cond<$cond>\n"
2520                                 if $dbg_adv_apw;
2521                             $allowed = 1;
2522                         }
2523                         if ($block =~/\b(?:if|for|while)\b/) {
2524                             print "APW: ALLOWED: block<$block>\n"
2525                                 if $dbg_adv_apw;
2526                             $allowed = 1;
2527                         }
2528                         if (statement_block_size($block) > 1) {
2529                             print "APW: ALLOWED: lines block<$block>\n"
2530                                 if $dbg_adv_apw;
2531                             $allowed = 1;
2532                         }
2533                         # Check the post-context.
2534                         if (defined $chunks[1]) {
2535                                 my ($cond, $block) = @{$chunks[1]};
2536                                 if (defined $cond) {
2537                                         substr($block, 0, length($cond), '');
2538                                 }
2539                                 if ($block =~ /^\s*\{/) {
2540                                     print "APW: ALLOWED: chunk-1 block<$block>\n"
2541                                         if $dbg_adv_apw;
2542                                     $allowed = 1;
2543                                 }
2544                         }
2545                         print "DCS: level=$level block<$block> allowed=$allowed\n"
2546                             if $dbg_adv_dcs;
2547                         if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2548                                 my $herectx = $here . "\n";;
2549                                 my $cnt = statement_rawlines($block);
2550
2551                                 for (my $n = 0; $n < $cnt; $n++) {
2552                                         $herectx .= raw_line($linenr, $n) . "\n";;
2553                                 }
2554
2555                                 WARN("braces {} are encouraged even for single statement blocks\n" . $herectx);
2556                         }
2557                 }
2558
2559 # warn about #if 0
2560                 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2561                         ERROR("if this code is redundant consider removing it\n" .
2562                                 $herecurr);
2563                 }
2564
2565 # Check that the storage class is at the beginning of a declaration
2566                 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2567                         ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2568                 }
2569
2570 # check the location of the inline attribute, that it is between
2571 # storage class and type.
2572                 if ($line =~ /\b$Type\s+$Inline\b/ ||
2573                     $line =~ /\b$Inline\s+$Storage\b/) {
2574                         ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2575                 }
2576
2577 # check for sizeof(&)
2578                 if ($line =~ /\bsizeof\s*\(\s*\&/) {
2579                         ERROR("sizeof(& should be avoided\n" . $herecurr);
2580                 }
2581
2582 # check for new externs in .c files.
2583                 if ($realfile =~ /\.c$/ && defined $stat &&
2584                     $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2585                 {
2586                         my $function_name = $1;
2587                         my $paren_space = $2;
2588
2589                         my $s = $stat;
2590                         if (defined $cond) {
2591                                 substr($s, 0, length($cond), '');
2592                         }
2593                         if ($s =~ /^\s*;/ &&
2594                             $function_name ne 'uninitialized_var')
2595                         {
2596                                 ERROR("externs should be avoided in .c files\n" .  $herecurr);
2597                         }
2598
2599                         if ($paren_space =~ /\n/) {
2600                                 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2601                         }
2602
2603                 } elsif ($realfile =~ /\.c$/ && defined $stat &&
2604                     $stat =~ /^.\s*extern\s+/)
2605                 {
2606                         ERROR("externs should be avoided in .c files\n" .  $herecurr);
2607                 }
2608
2609 # check for gcc specific __FUNCTION__
2610                 if ($line =~ /__FUNCTION__/) {
2611                         ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr);
2612                 }
2613
2614 # recommend sigaction over signal for portability, when establishing a handler
2615                 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2616                         ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2617                 }
2618
2619 # format strings checks
2620                 my $string;
2621                 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2622                         $string = substr($rawline, $-[1], $+[1] - $-[1]);
2623                         $string =~ s/%%/__/g;
2624                         # check for %L{u,d,i} in strings
2625                         if ($string =~ /(?<!%)%L[udi]/) {
2626                                 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2627                         }
2628                 }
2629
2630         # Continue checking for error messages that contains newlines. This
2631         # check handles cases where string literals are spread over multiple lines.
2632         # Example:
2633         # error_report("Error msg line #1"
2634         #              "Error msg line #2\n");
2635         my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2636         my $continued_str_literal = qr{\+\s*\".*\"};
2637
2638         if ($rawline =~ /$quoted_newline_regex/) {
2639                 # Backtrack to first line that does not contain only a quoted literal
2640                 # and assume that it is the start of the statement.
2641                 my $i = $linenr - 2;
2642
2643                 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2644                         $i--;
2645                 }
2646         }
2647
2648         }
2649
2650         # If we have no input at all, then there is nothing to report on
2651         # so just keep quiet.
2652         if ($#rawlines == -1) {
2653                 return 1;
2654         }
2655
2656         # In mailback mode only produce a report in the negative, for
2657         # things that appear to be patches.
2658         if ($mailback && ($clean == 1 || !$is_patch)) {
2659                 return 1;
2660         }
2661
2662         # This is not a patch, and we are are in 'no-patch' mode so
2663         # just keep quiet.
2664         if (!$chk_patch && !$is_patch) {
2665                 return 1;
2666         }
2667
2668         if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
2669                 ERROR("Does not appear to be a unified-diff format patch\n");
2670         }
2671
2672         print report_dump();
2673         if ($summary && !($clean == 1 && $quiet == 1)) {
2674                 print "$filename " if ($summary_file);
2675                 print "total: $cnt_error errors, $cnt_warn warnings, " .
2676                         "$cnt_lines lines checked\n";
2677                 print "\n" if ($quiet == 0);
2678         }
2679
2680         if ($quiet == 0) {
2681                 # If there were whitespace errors which cleanpatch can fix
2682                 # then suggest that.
2683 #               if ($rpt_cleaners) {
2684 #                       print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
2685 #                       print "      scripts/cleanfile\n\n";
2686 #               }
2687         }
2688
2689         if ($clean == 1 && $quiet == 0) {
2690                 print "$vname has no obvious style problems and is ready for submission.\n"
2691         }
2692
2693         return ($no_warnings ? $clean : $cnt_error == 0);
2694 }