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