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