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