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