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