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