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