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