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