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