1#! /usr/bin/env perl 2# 3# Copyright 2020-2025 The OpenSSL Project Authors. All Rights Reserved. 4# Copyright Siemens AG 2019-2022 5# 6# Licensed under the Apache License 2.0 (the "License"). 7# You may not use this file except in compliance with the License. 8# You can obtain a copy in the file LICENSE in the source distribution 9# or at https://www.openssl.org/source/license.html 10# 11# check-format.pl 12# - check formatting of C source according to OpenSSL coding style 13# 14# usage: 15# check-format.pl [-l|--strict-len] [-b|--sloppy-bodylen] 16# [-s|--sloppy-space] [-c|--sloppy-comment] 17# [-m|--sloppy-macro] [-h|--sloppy-hang] 18# [-e|--eol-comment] [-1|--1-stmt] 19# <files> 20# 21# run self-tests: 22# util/check-format.pl util/check-format-test-positives.c 23# util/check-format.pl util/check-format-test-negatives.c 24# 25# checks adherence to the formatting rules of the OpenSSL coding guidelines 26# assuming that the input files contain syntactically correct C code. 27# This pragmatic tool is incomplete and yields some false positives. 28# Still it should be useful for detecting most typical glitches. 29# 30# options: 31# -l | --strict-len decrease accepted max line length from 100 to 80 32# -b | --sloppy-bodylen do not report function body length > 200 33# -s | --sloppy-space do not report whitespace nits 34# -c | --sloppy-comment do not report indentation of comments 35# Otherwise for each multi-line comment the indentation of 36# its lines is checked for consistency. For each comment 37# that does not begin to the right of normal code its 38# indentation must be as for normal code, while in case it 39# also has no normal code to its right it is considered to 40# refer to the following line and may be indented equally. 41# -m | --sloppy-macro allow missing extra indentation of macro bodies 42# -h | --sloppy-hang when checking hanging indentation, do not report 43# * same indentation as on line before 44# * same indentation as non-hanging indent level 45# * indentation moved left (not beyond non-hanging indent) 46# just to fit contents within the line length limit 47# -e | --eol-comment report needless intermediate multiple consecutive spaces also before end-of-line comments 48# -1 | --1-stmt do more aggressive checks for { 1 stmt } - see below 49# 50# There are non-trivial false positives and negatives such as the following. 51# 52# * When a line contains several issues of the same kind only one is reported. 53# 54# * When a line contains more than one statement this is (correctly) reported 55# but in some situations the indentation checks for subsequent lines go wrong. 56# 57# * There is the special OpenSSL rule not to unnecessarily use braces around 58# single statements: 59# { 60# stmt; 61# } 62# except within if ... else constructs where some branch contains more than one 63# statement. Since the exception is hard to recognize when such branches occur 64# after the current position (such that false positives would be reported) 65# the tool checks for this rule by default only for do/while/for bodies 66# and for 'if' without 'else'. 67# Yet with the --1-stmt option false positives are preferred over negatives. 68# False negatives occur if the braces are more than two non-blank lines apart. 69# 70# * The presence of multiple consecutive spaces is regarded a coding style nit 71# except when this is before end-of-line comments (unless the --eol-comment is given) and 72# except when done in order to align certain columns over multiple lines, e.g.: 73# # define AB 1 74# # define CDE 22 75# # define F 3333 76# This pattern is recognized - and consequently extra space not reported - 77# for a given line if in the non-blank line before or after (if existing) 78# for each occurrence of " \S" (where \S means non-space) in the given line 79# there is " \S" in the other line in the respective column position. 80# This may lead to both false negatives (in case of coincidental " \S") 81# and false positives (in case of more complex multi-column alignment). 82# 83# * When just part of control structures depend on #if(n)(def), which can be 84# considered bad programming style, indentation false positives occur, e.g.: 85# #if X 86# if (1) /* bad style */ 87# #else 88# if (2) /* bad style resulting in false positive */ 89# #endif 90# c; /* resulting further false positive */ 91 92use strict; 93# use List::Util qw[min max]; 94use POSIX; 95 96use constant INDENT_LEVEL => 4; 97use constant MAX_LINE_LENGTH => 100; 98use constant STRICT_LINE_LENGTH => 80; 99use constant MAX_BODY_LENGTH => 200; 100 101# global variables @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 102 103# command-line options 104my $max_length = MAX_LINE_LENGTH; 105my $sloppy_bodylen = 0; 106my $sloppy_SPC = 0; 107my $sloppy_hang = 0; 108my $sloppy_cmt = 0; 109my $sloppy_macro = 0; 110my $eol_cmt = 0; 111my $extended_1_stmt = 0; 112 113while ($ARGV[0] =~ m/^-(\w|-[\w\-]+)$/) { 114 my $arg = $1; shift; 115 if ($arg =~ m/^(l|-strict-len)$/) { 116 $max_length = STRICT_LINE_LENGTH; 117 } elsif ($arg =~ m/^(b|-sloppy-bodylen)$/) { 118 $sloppy_bodylen = 1; 119 } elsif ($arg =~ m/^(s|-sloppy-space)$/) { 120 $sloppy_SPC= 1; 121 } elsif ($arg =~ m/^(c|-sloppy-comment)$/) { 122 $sloppy_cmt = 1; 123 } elsif ($arg =~ m/^(m|-sloppy-macro)$/) { 124 $sloppy_macro = 1; 125 } elsif ($arg =~ m/^(h|-sloppy-hang)$/) { 126 $sloppy_hang = 1; 127 } elsif ($arg =~ m/^(e|-eol-comment)$/) { 128 $eol_cmt = 1; 129 } elsif ($arg =~ m/^(1|-1-stmt)$/) { 130 $extended_1_stmt = 1; 131 } else { 132 die("unknown option: -$arg"); 133 } 134} 135 136# state variables 137my $self_test; # whether the current input file is regarded to contain (positive/negative) self-tests 138 139my $in_comment; # number of lines so far within multi-line comment, 0 if no comment, < 0 when end is on current line 140my $leading_comment; # multi-line comment has no code before its beginning delimiter, if $in_comment != 0 141my $formatted_comment; # multi-line comment beginning with "/*-", which indicates/allows special formatting, if $in_comment != 0 142my $comment_indent; # comment indent, if $in_comment != 0 143 144my $ifdef__cplusplus; # line before contained '#ifdef __cplusplus' (used in header files) 145my $preproc_if_nesting; # currently required indentation of preprocessor directive according to #if(n)(def) 146my $in_preproc; # 0 or number of lines so far within preprocessor directive, e.g., macro definition 147my $preproc_directive; # name of current preprocessor directive, if $in_preproc != 0 148my $preproc_offset; # offset to $block_indent within multi-line preprocessor directive, else 0 149my $in_macro_header; # number of open parentheses + 1 in (multi-line) header of #define, if $in_preproc != 0 150 151my $line; # current line number 152my $line_before; # number of previous not essentially blank line (containing at most whitespace and '\') 153my $line_before2; # number of not essentially blank line before previous not essentially blank line 154 155# indentation state 156my $contents; # contents of current line (without blinding) 157# $_ # current line, where comments etc. get blinded 158my $code_contents_before; # contents of previous non-comment non-preprocessor-directive line (without blinding), initially "" 159my $contents_before; # contents of $line_before (without blinding), if $line_before > 0 160my $contents_before_; # contents of $line_before after blinding comments etc., if $line_before > 0 161my $contents_before2; # contents of $line_before2 (without blinding), if $line_before2 > 0 162my $contents_before_2; # contents of $line_before2 after blinding comments etc., if $line_before2 > 0 163my $in_multiline_string; # line starts within multi-line string literal 164my $count; # -1 or number of leading whitespace characters (except newline) in current line, 165 # which should be $block_indent + $hanging_offset + $local_offset or $expr_indent 166my $count_before; # number of leading whitespace characters (except line ending chars) in $contents_before 167my $has_label; # current line contains label 168my $local_offset; # current extra indent due to label, switch case/default, or leading closing brace(s) 169my $line_body_start; # number of line where last function body started, or 0 170my $line_function_start; # number of line where last function definition started, used for $line_body_start 171my $last_function_header; # header containing name of last function defined, used if $line_body_start != 0 172my $line_opening_brace; # number of previous line with opening brace after if/do/while/for, partly for 'else/else if' - used for detection of { 1 stmt } 173 174my $keyword_opening_brace; # name of keyword (or combination 'else if') just before '{', used if $line_opening_brace != 0 175my $block_indent; # currently required normal indentation at block/statement level 176my $hanging_offset; # extra indent, which may be nested, for just one hanging statement or expr or typedef 177my @in_do_hanging_offsets; # stack of hanging offsets for nested 'do' ... 'while' 178my @in_if_hanging_offsets; # stack of hanging offsets for nested 'if' (but not its potential 'else' branch) 179my $if_maybe_terminated; # 'if' ends and $hanging_offset should be reset unless the next line starts with 'else' 180my @nested_block_indents; # stack of indentations at block/statement level, needed due to hanging statements 181my @nested_hanging_offsets;# stack of nested $hanging_offset values, in parallel to @nested_block_indents 182my @nested_in_typedecl; # stack of nested $in_typedecl values, partly in parallel to @nested_block_indents 183my @nested_indents; # stack of hanging indents due to parentheses, braces, brackets, or conditionals 184my @nested_symbols; # stack of hanging symbols '(', '{', '[', or '?', in parallel to @nested_indents 185my @nested_conds_indents; # stack of hanging indents due to conditionals ('?' ... ':') 186my $expr_indent; # resulting hanging indent within (multi-line) expressions including type exprs, else 0 187my $hanging_symbol; # character ('(', '{', '[', not: '?') responsible for $expr_indent, if $expr_indent != 0 188my $in_block_decls; # number of local declaration lines after block opening before normal statements, or -1 if no block opening 189my $in_expr; # in expression after if/while/for/switch/return/enum/LHS of assignment 190my $in_paren_expr; # in parenthesized if/while/for condition and switch expression, if $expr_indent != 0 191my $in_typedecl; # nesting level of typedef/struct/union/enum 192 193my $num_reports_line = 0; # number of issues found on current line 194my $num_reports = 0; # total number of issues found 195my $num_indent_reports = 0;# total number of indentation issues found 196my $num_nesting_issues = 0;# total number of preprocessor #if nesting issues found 197my $num_syntax_issues = 0; # total number of syntax issues found during sanity checks 198my $num_SPC_reports = 0; # total number of whitespace issues found 199my $num_length_reports = 0;# total number of line length issues found 200 201sub reset_file_state { 202 $in_comment = 0; 203 $ifdef__cplusplus = 0; 204 $preproc_if_nesting = 0; 205 $in_preproc = 0; 206 $line = 0; 207 $line_before = 0; 208 $line_before2 = 0; 209 reset_indentation_state(); 210} 211sub reset_indentation_state { 212 $code_contents_before = ""; 213 @nested_block_indents = (); 214 @nested_hanging_offsets = (); 215 @nested_in_typedecl = (); 216 @nested_symbols = (); 217 @nested_indents = (); 218 @nested_conds_indents = (); 219 $expr_indent = 0; 220 $in_block_decls = -1; 221 $in_expr = 0; 222 $in_paren_expr = 0; 223 $hanging_offset = 0; 224 @in_do_hanging_offsets = (); 225 @in_if_hanging_offsets = (); 226 $if_maybe_terminated = 0; 227 $block_indent = 0; 228 $in_multiline_string = 0; 229 $line_body_start = 0; 230 $line_opening_brace = 0; 231 $in_typedecl = 0; 232} 233my $bak_line_before; 234my $bak_line_before2; 235my $bak_code_contents_before; 236my @bak_nested_block_indents; 237my @bak_nested_hanging_offsets; 238my @bak_nested_in_typedecl; 239my @bak_nested_symbols; 240my @bak_nested_indents; 241my @bak_nested_conds_indents; 242my $bak_expr_indent; 243my $bak_in_block_decls; 244my $bak_in_expr; 245my $bak_in_paren_expr; 246my $bak_hanging_offset; 247my @bak_in_do_hanging_offsets; 248my @bak_in_if_hanging_offsets; 249my $bak_if_maybe_terminated; 250my $bak_block_indent; 251my $bak_in_multiline_string; 252my $bak_line_body_start; 253my $bak_line_opening_brace; 254my $bak_in_typedecl; 255sub backup_indentation_state { 256 $bak_code_contents_before = $code_contents_before; 257 @bak_nested_block_indents = @nested_block_indents; 258 @bak_nested_hanging_offsets = @nested_hanging_offsets; 259 @bak_nested_in_typedecl = @nested_in_typedecl; 260 @bak_nested_symbols = @nested_symbols; 261 @bak_nested_indents = @nested_indents; 262 @bak_nested_conds_indents = @nested_conds_indents; 263 $bak_expr_indent = $expr_indent; 264 $bak_in_block_decls = $in_block_decls; 265 $bak_in_expr = $in_expr; 266 $bak_in_paren_expr = $in_paren_expr; 267 $bak_hanging_offset = $hanging_offset; 268 @bak_in_do_hanging_offsets = @in_do_hanging_offsets; 269 @bak_in_if_hanging_offsets = @in_if_hanging_offsets; 270 $bak_if_maybe_terminated = $if_maybe_terminated; 271 $bak_block_indent = $block_indent; 272 $bak_in_multiline_string = $in_multiline_string; 273 $bak_line_body_start = $line_body_start; 274 $bak_line_opening_brace = $line_opening_brace; 275 $bak_in_typedecl = $in_typedecl; 276} 277sub restore_indentation_state { 278 $code_contents_before = $bak_code_contents_before; 279 @nested_block_indents = @bak_nested_block_indents; 280 @nested_hanging_offsets = @bak_nested_hanging_offsets; 281 @nested_in_typedecl = @bak_nested_in_typedecl; 282 @nested_symbols = @bak_nested_symbols; 283 @nested_indents = @bak_nested_indents; 284 @nested_conds_indents = @bak_nested_conds_indents; 285 $expr_indent = $bak_expr_indent; 286 $in_block_decls = $bak_in_block_decls; 287 $in_expr = $bak_in_expr; 288 $in_paren_expr = $bak_in_paren_expr; 289 $hanging_offset = $bak_hanging_offset; 290 @in_do_hanging_offsets = @bak_in_do_hanging_offsets; 291 @in_if_hanging_offsets = @bak_in_if_hanging_offsets; 292 $if_maybe_terminated = $bak_if_maybe_terminated; 293 $block_indent = $bak_block_indent; 294 $in_multiline_string = $bak_in_multiline_string; 295 $line_body_start = $bak_line_body_start; 296 $line_opening_brace = $bak_line_opening_brace; 297 $in_typedecl = $bak_in_typedecl; 298} 299 300# auxiliary submodules @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 301 302sub report_flexibly { 303 my $line = shift; 304 my $msg = shift; 305 my $contents = shift; 306 my $report_SPC = $msg =~ /space|blank/; 307 return if $report_SPC && $sloppy_SPC; 308 309 print "$ARGV:$line:$msg:$contents" unless $self_test; 310 $num_reports_line++; 311 $num_reports++; 312 $num_indent_reports++ if $msg =~ m/:indent /; 313 $num_nesting_issues++ if $msg =~ m/ nesting indent /; 314 $num_syntax_issues++ if $msg =~ m/unclosed|unexpected/; 315 $num_SPC_reports++ if $report_SPC; 316 $num_length_reports++ if $msg =~ m/length/; 317} 318 319sub report { 320 my $msg = shift; 321 report_flexibly($line, $msg, $contents); 322} 323 324sub parens_balance { # count balance of opening parentheses - closing parentheses 325 my $str = shift; 326 return $str =~ tr/\(// - $str =~ tr/\)//; 327} 328 329sub blind_nonspace { # blind non-space text of comment as @, preserving length and spaces 330 # the @ character is used because it cannot occur in normal program code so there is no confusion 331 # comment text is not blinded to whitespace in order to be able to check extra SPC also in comments 332 my $comment_text = shift; 333 $comment_text =~ s/([\.\?\!])\s\s/$1. /g; # in extra SPC checks allow one extra SPC after period '.', '?', or '!' in comments 334 return $comment_text =~ tr/ /@/cr; 335} 336 337# submodule for indentation checking/reporting @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 338 339sub check_indent { # used for lines outside multi-line string literals 340 my $stmt_indent = $block_indent + $hanging_offset + $local_offset; 341 # print "DEBUG: expr_indent $expr_indent; stmt_indent $stmt_indent = block_indent $block_indent + hanging_offset $hanging_offset + local_offset $local_offset\n"; 342 $stmt_indent = 0 if $stmt_indent < 0; # TODO maybe give warning/error 343 my $stmt_desc = $contents =~ 344 m/^\s*\/\*/ ? "intra-line comment" : 345 $has_label ? "label" : 346 ($hanging_offset != 0 ? "hanging " : ""). 347 ($hanging_offset != 0 ? "stmt/expr" : "stmt/decl"); # $in_typedecl is not fully to the point here 348 my ($ref_desc, $ref_indent) = $expr_indent == 0 ? ($stmt_desc, $stmt_indent) 349 : ("hanging '$hanging_symbol'", $expr_indent); 350 my ($alt_desc, $alt_indent) = ("", $ref_indent); 351 352 # allow indent 1 for labels - this cannot happen for leading ':' 353 ($alt_desc, $alt_indent) = ("outermost position", 1) if $expr_indent == 0 && $has_label; 354 355 if (@nested_conds_indents != 0 && substr($_, $count, 1) eq ":") { 356 # leading ':' within stmt/expr/decl - this cannot happen for labels, leading '&&', or leading '||' 357 # allow special indent at level of corresponding "?" 358 ($alt_desc, $alt_indent) = ("leading ':'", @nested_conds_indents[-1]); 359 } 360 # allow extra indent offset leading '&&' or '||' - this cannot happen for leading ":" 361 ($alt_desc, $alt_indent) = ("leading '$1'", $ref_indent + INDENT_LEVEL) if $contents =~ m/^[\s@]*(\&\&|\|\|)/; 362 363 if ($expr_indent < 0) { # implies @nested_symbols != 0 && @nested_symbols[0] eq "{" && @nested_indents[-1] < 0 364 # allow normal stmt indentation level for hanging initializer/enum expressions after trailing '{' 365 # this cannot happen for labels and overrides special treatment of ':', '&&' and '||' for this line 366 ($alt_desc, $alt_indent) = ("lines after '{'", $stmt_indent); 367 # decide depending on current actual indentation, preventing forth and back 368 @nested_indents[-1] = $count == $stmt_indent ? $stmt_indent : -@nested_indents[-1]; # allow $stmt_indent 369 $ref_indent = $expr_indent = @nested_indents[-1]; 370 } 371 372 # check consistency of indentation within multi-line comment (i.e., between its first, inner, and last lines) 373 if ($in_comment != 0 && $in_comment != 1) { # in multi-line comment but not on its first line 374 if (!$sloppy_cmt) { 375 if ($in_comment > 0) { # not at its end 376 report("indent = $count != $comment_indent within multi-line comment") 377 if $count != $comment_indent; 378 } else { 379 my $tweak = $in_comment == -2 ? 1 : 0; 380 report("indent = ".($count + $tweak)." != $comment_indent at end of multi-line comment") 381 if $count + $tweak != $comment_indent; 382 } 383 } 384 # do not check indentation of last line of non-leading multi-line comment 385 if ($in_comment < 0 && !$leading_comment) { 386 s/^(\s*)@/$1*/; # blind first '@' as '*' to prevent below delayed check for the line before 387 return; 388 } 389 return if $in_comment > 0; # not on its last line 390 # $comment_indent will be checked by the below checks for end of multi-line comment 391 } 392 393 # else check indentation of entire-line comment or entire-line end of multi-line comment 394 # ... w.r.t. indent of the following line by delayed check for the line before 395 if (($in_comment == 0 || $in_comment == 1) # no comment, intra-line comment, or begin of multi-line comment 396 && $line_before > 0 # there is a line before 397 && $contents_before_ =~ m/^(\s*)@[\s@]*$/) { # line before begins with '@', no code follows (except '\') 398 report_flexibly($line_before, "entire-line comment indent = $count_before != $count (of following line)", 399 $contents_before) if !$sloppy_cmt && $count_before != -1 && $count_before != $count; 400 } 401 # ... but allow normal indentation for the current line, else above check will be done for the line before 402 if (($in_comment == 0 || $in_comment < 0) # (no comment,) intra-line comment or end of multi-line comment 403 && m/^(\s*)@[\s@]*$/) { # line begins with '@', no code follows (except '\') 404 if ($count == $ref_indent) { # indentation is like for (normal) code in this line 405 s/^(\s*)@/$1*/; # blind first '@' as '*' to prevent above delayed check for the line before 406 return; 407 } 408 return if !eof; # defer check of entire-line comment to next line 409 } 410 411 # else check indentation of leading intra-line comment or end of multi-line comment 412 if (m/^(\s*)@/) { # line begins with '@', i.e., any (remaining type of) comment 413 if (!$sloppy_cmt && $count != $ref_indent) { 414 report("intra-line comment indent = $count != $ref_indent") if $in_comment == 0; 415 report("multi-line comment indent = $count != $ref_indent") if $in_comment < 0; 416 } 417 return; 418 } 419 420 if ($sloppy_hang && ($hanging_offset != 0 || $expr_indent != 0)) { 421 # do not report same indentation as on the line before (potentially due to same violations) 422 return if $line_before > 0 && $count == $count_before; 423 424 # do not report indentation at normal indentation level while hanging expression indent would be required 425 return if $expr_indent != 0 && $count == $stmt_indent; 426 427 # do not report if contents have been shifted left of nested expr indent (but not as far as stmt indent) 428 # apparently aligned to the right in order to fit within line length limit 429 return if $stmt_indent < $count && $count < $expr_indent && 430 length($contents) == $max_length + length("\n"); 431 } 432 433 report("indent = $count != $ref_indent for $ref_desc". 434 ($alt_desc eq "" 435 || $alt_indent == $ref_indent # prevent showing alternative that happens to have equal value 436 ? "" : " or $alt_indent for $alt_desc")) 437 if $count != $ref_indent && $count != $alt_indent; 438} 439 440# submodules handling indentation within expressions @@@@@@@@@@@@@@@@@@@@@@@@@@@ 441 442sub update_nested_indents { # may reset $in_paren_expr and in this case also resets $in_expr 443 my $str = shift; 444 my $start = shift; # defaults to 0 445 my $terminator_position = -1; 446 for (my $i = $start; $i < length($str); $i++) { 447 my $c; 448 my $curr = substr($str, $i); 449 if ($curr =~ m/^(.*?)([{}()?:;\[\]])(.*)$/) { # match from position $i the first {}()?:;[] 450 $c = $2; 451 } else { 452 last; 453 } 454 my ($head, $tail) = (substr($str, 0, $i).$1, $3); 455 $i += length($1) + length($2) - 1; 456 457 # stop at terminator outside 'for (..;..;..)', assuming that 'for' is followed by '(' 458 return $i if $c eq ";" && (!$in_paren_expr || @nested_indents == 0); 459 460 my $in_stmt = $in_expr || @nested_symbols != 0; # not: || $in_typedecl != 0 461 if ($c =~ m/[{([?]/) { # $c is '{', '(', '[', or '?' 462 if ($c eq "{") { # '{' in any context 463 $in_block_decls = 0 if !$in_expr && $in_typedecl == 0; 464 # cancel newly hanging_offset if opening brace '{' is after non-whitespace non-comment: 465 $hanging_offset -= INDENT_LEVEL if $hanging_offset > 0 && $head =~ m/[^\s\@]/; 466 push @nested_block_indents, $block_indent; 467 push @nested_hanging_offsets, $in_expr ? $hanging_offset : 0; 468 push @nested_in_typedecl, $in_typedecl if $in_typedecl != 0; 469 my $indent_inc = INDENT_LEVEL; 470 $indent_inc = 0 if (m/^[\s@]*(case|default)\W.*\{[\s@]*$/); # leading 'case' or 'default' and trailing '{' 471 $block_indent += $indent_inc + $hanging_offset; 472 $hanging_offset = 0; 473 } 474 if ($c ne "{" || $in_stmt) { # for '{' inside stmt/expr (not: decl), for '(', '[', or '?' anywhere 475 $tail =~ m/^([\s@]*)([^\s\@])/; 476 push @nested_indents, defined $2 477 ? $i + 1 + length($1) # actual indentation of following non-space non-comment 478 : $c ne "{" ? +($i + 1) # just after '(' or '[' if only whitespace thereafter 479 : -($i + 1); # allow also $stmt_indent if '{' with only whitespace thereafter 480 push @nested_symbols, $c; # done also for '?' to be able to check correct nesting 481 push @nested_conds_indents, $i if $c eq "?"; # remember special alternative indent for ':' 482 } 483 } elsif ($c =~ m/[})\]:]/) { # $c is '}', ')', ']', or ':' 484 my $opening_c = ($c =~ tr/})]:/{([/r); 485 if (($c ne ":" || $in_stmt # ignore ':' outside stmt/expr/decl 486 # in the presence of ':', one could add this sanity check: 487 # && !(# ':' after initial label/case/default 488 # $head =~ m/^([\s@]*)(case\W.*$|\w+$)/ || # this matching would not work for 489 # # multi-line expr after 'case' 490 # # bitfield length within unsigned type decl 491 # $tail =~ m/^[\s@]*\d+/ # this matching would need improvement 492 # ) 493 )) { 494 if ($c ne "}" || $in_stmt) { # for '}' inside stmt/expr/decl, ')', ']', or ':' 495 if (@nested_symbols != 0 && 496 @nested_symbols[-1] == $opening_c) { # for $c there was a corresponding $opening_c 497 pop @nested_indents; 498 pop @nested_symbols; 499 pop @nested_conds_indents if $opening_c eq "?"; 500 } else { 501 report("unexpected '$c' @ ".($in_paren_expr ? "(expr)" : "expr")); 502 next; 503 } 504 } 505 if ($c eq "}") { # '}' at block level but also inside stmt/expr/decl 506 if (@nested_block_indents == 0) { 507 report("unexpected '}'"); 508 } else { 509 $block_indent = pop @nested_block_indents; 510 $hanging_offset = pop @nested_hanging_offsets; 511 $in_typedecl = pop @nested_in_typedecl if @nested_in_typedecl != 0; 512 } 513 } 514 if ($in_paren_expr && !grep(/\(/, @nested_symbols)) { # end of (expr) 515 check_nested_nonblock_indents("(expr)"); 516 $in_paren_expr = $in_expr = 0; 517 report("code after (expr)") 518 if $tail =~ m/^([^{]*)/ && $1 =~ m/[^\s\@;]/; # non-space non-';' before any '{' 519 } 520 } 521 } 522 } 523 return -1; 524} 525 526sub check_nested_nonblock_indents { 527 my $position = shift; 528 while (@nested_symbols != 0) { 529 my $symbol = pop @nested_symbols; 530 report("unclosed '$symbol' in $position"); 531 if ($symbol eq "{") { # repair stack of blocks 532 $block_indent = pop @nested_block_indents; 533 $hanging_offset = pop @nested_hanging_offsets; 534 $in_typedecl = pop @nested_in_typedecl if @nested_in_typedecl != 0; 535 } 536 } 537 @nested_indents = (); 538 @nested_conds_indents = (); 539} 540 541# start of main program @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 542 543reset_file_state(); 544 545while (<>) { # loop over all lines of all input files 546 $self_test = $ARGV =~ m/check-format-test/; 547 $_ = "" if $self_test && m/ blank line within local decls /; 548 $line++; 549 s/\r$//; # strip any trailing CR '\r' (which are typical on Windows systems) 550 $contents = $_; 551 552 # check for illegal characters 553 if (m/(.*?)([\x00-\x09\x0B-\x1F\x7F-\xFF])/) { 554 my $col = length($1); 555 report(($2 eq "\x09" ? "TAB" : $2 eq "\x0D" ? "CR " : $2 =~ m/[\x00-\x1F]/ ? "non-printable" 556 : "non-7bit char") . " at column $col") ; 557 } 558 559 # check for whitespace at EOL 560 report("trailing whitespace at EOL") if m/\s\n$/; 561 562 # assign to $count the actual indentation level of the current line 563 chomp; # remove trailing NL '\n' 564 m/^(\s*)/; 565 $count = length($1); # actual indentation 566 $has_label = 0; 567 $local_offset = 0; 568 569 # character/string literals @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 570 571 s/\\["']/@@/g; # blind all '"' and "'" escaped by '\' (typically within character literals or string literals) 572 573 # handle multi-line string literals to avoid confusion on starting/ending '"' and trailing '\' 574 if ($in_multiline_string) { 575 if (s#^([^"]*)"#($1 =~ tr/"/@/cr).'@'#e) { # string literal terminated by '"' 576 # string contents and its terminating '"' have been blinded as '@' 577 $count = -1; # do not check indentation 578 } else { 579 report("multi-line string literal not terminated by '\"' and trailing '\' is missing") 580 unless s#^([^\\]*)\s*\\\s*$#$1#; # strip trailing '\' plus any whitespace around 581 goto LINE_FINISHED; 582 } 583 } 584 585 # blind contents of character and string literals as @, preserving length (but not spaces) 586 # this prevents confusing any of the matching below, e.g., of whitespace and comment delimiters 587 s#('[^']*')#$1 =~ tr/'/@/cr#eg; # handle all intra-line character literals 588 s#("[^"]*")#$1 =~ tr/"/@/cr#eg; # handle all intra-line string literals 589 $in_multiline_string = # handle trailing string literal terminated by '\' 590 s#^(([^"]*"[^"]*")*[^"]*)("[^"]*)\\(\s*)$#$1.($3 =~ tr/"/@/cr).'"'.$4#e; 591 # its contents have been blinded and the trailing '\' replaced by '"' 592 593 # strip any other trailing '\' along with any whitespace around it such that it does not interfere with various matching below 594 my $trailing_backslash = s#^(.*?)\s*\\\s*$#$1#; # trailing '\' possibly preceded or followed by whitespace 595 my $essentially_blank_line = m/^\s*$/; # just whitespace and maybe a '\' 596 597 # comments @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 598 599 # do/prepare checks within multi-line comments 600 my $self_test_exception = $self_test ? "@" : ""; 601 if ($in_comment > 0) { # this still includes the last line of multi-line comment 602 my ($head, $any_symbol, $cmt_text) = m/^(\s*)(.?)(.*)$/; 603 if ($any_symbol eq "*") { 604 report("missing space or '*' after leading '*' in multi-line comment") if $cmt_text =~ m|^[^*\s/$self_test_exception]|; 605 } else { 606 report("missing leading '*' in multi-line comment"); 607 } 608 $in_comment++; 609 } 610 611 # detect end of comment, must be within multi-line comment, check if it is preceded by non-whitespace text 612 if ((my ($head, $tail) = m|^(.*?)\*/(.*)$|) && $1 ne '/') { # ending comment: '*/' 613 report("missing space or '*' before '*/'") if $head =~ m/[^*\s]$/; 614 report("missing space (or ',', ';', ')', '}', ']') after '*/'") if $tail =~ m/^[^\s,;)}\]]/; # no space or ,;)}] after '*/' 615 if (!($head =~ m|/\*|)) { # not begin of comment '/*', which is is handled below 616 if ($in_comment == 0) { 617 report("unexpected '*/' outside comment"); 618 $_ = "$head@@".$tail; # blind the "*/" 619 } else { 620 report("text before '*/' in multi-line comment") if ($head =~ m/[^*\s]/); # non-SPC before '*/' 621 $in_comment = -1; # indicate that multi-line comment ends on current line 622 if ($count > 0) { 623 # make indentation of end of multi-line comment appear like of leading intra-line comment 624 $head =~ s/^(\s*)\s/$1@/; # replace the last leading space by '@' 625 $count--; 626 $in_comment = -2; # indicate that multi-line comment ends on current line, with tweak 627 } 628 my $cmt_text = $head; 629 $_ = blind_nonspace($cmt_text)."@@".$tail; 630 } 631 } 632 } 633 634 # detect begin of comment, check if it is followed by non-space text 635 MATCH_COMMENT: 636 if (my ($head, $opt_minus, $tail) = m|^(.*?)/\*(-?)(.*)$|) { # begin of comment: '/*' 637 report("missing space before '/*'") 638 if $head =~ m/[^\s(\*]$/; # not space, '(', or or '*' (needed to allow '*/') before comment delimiter 639 report("missing space, '*', or '!' after '/*$opt_minus'") if $tail =~ m/^[^\s*!$self_test_exception]/; 640 my $cmt_text = $opt_minus.$tail; # preliminary 641 if ($in_comment > 0) { 642 report("unexpected '/*' inside multi-line comment"); 643 } elsif ($tail =~ m|^(.*?)\*/(.*)$|) { # comment end: */ on same line 644 report("unexpected '/*' inside intra-line comment") if $1 =~ /\/\*/; 645 # blind comment text, preserving length and spaces 646 ($cmt_text, my $rest) = ($opt_minus.$1, $2); 647 $_ = "$head@@".blind_nonspace($cmt_text)."@@".$rest; 648 goto MATCH_COMMENT; 649 } else { # begin of multi-line comment 650 my $self_test_exception = $self_test ? "(@\d?)?" : ""; 651 report("text after '/*' in multi-line comment") 652 unless $tail =~ m/^$self_test_exception.?[*\s]*$/; 653 # tail not essentially blank, first char already checked 654 # adapt to actual indentation of first line 655 $comment_indent = length($head) + 1; 656 $_ = "$head@@".blind_nonspace($cmt_text); 657 $in_comment = 1; 658 $leading_comment = $head =~ m/^\s*$/; # there is code before beginning delimiter 659 $formatted_comment = $opt_minus eq "-"; 660 } 661 } elsif (($head, $tail) = m|^\{-(.*)$|) { # begin of Perl pragma: '{-' 662 } 663 664 if ($in_comment > 1) { # still inside multi-line comment (not at its begin or end) 665 m/^(\s*)\*?(\s*)(.*)$/; 666 $_ = $1."@".$2.blind_nonspace($3); 667 } 668 669 # handle special case of line after '#ifdef __cplusplus' (which typically appears in header files) 670 if ($ifdef__cplusplus) { 671 $ifdef__cplusplus = 0; 672 $_ = "$1 $2" if $contents =~ m/^(\s*extern\s*"C"\s*)\{(\s*)$/; # ignore opening brace in 'extern "C" {' 673 goto LINE_FINISHED if m/^\s*\}\s*$/; # ignore closing brace '}' 674 } 675 676 # check for over-long lines, 677 # while allowing trailing (also multi-line) string literals to go past $max_length 678 my $len = length; # total line length (without trailing '\n') 679 if ($len > $max_length && 680 !(m/^(.*)"[^"]*"\s*[\)\}\]]*[,;]?\s*$/ # string literal terminated by '"' (or '\'), then maybe )}],; 681 && length($1) < $max_length) 682 # this allows over-long trailing string literals with beginning col before $max_length 683 ) { 684 report("line length = $len > ".$max_length); 685 } 686 687 # handle C++ / C99 - style end-of-line comments 688 if (my ($head, $cmt_text) = m|^(.*?)//(.*$)|) { 689 report("'//' end-of-line comment"); # the '//' comment style is not allowed for C90 690 # blind comment text, preserving length and spaces 691 $_ = "$head@@".blind_nonspace($cmt_text); 692 } 693 694 # at this point all non-space portions of any types of comments have been blinded as @ 695 696 goto LINE_FINISHED if $essentially_blank_line; 697 698 # handle preprocessor directives @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 699 700 if (s/^(\s*#)(\s*)(\w+)//) { # line beginning with '#' and directive name; 701 # blank these portions to prevent confusion with C-level 'if', 'else', etc. 702 my ($lead, $space) = ($1, $2); 703 $preproc_directive = $3; 704 $_ = "$lead$space$preproc_directive$_" if $preproc_directive =~ m/^(define|include)$/; # yet do not blank #define or #include to prevent confusing the indentation or whitespace checks, resp. 705 $_ = blind_nonspace($_) if $preproc_directive eq "error"; # blind error message 706 if ($in_preproc != 0) { 707 report("preprocessor directive within multi-line directive"); 708 reset_indentation_state(); 709 } 710 $in_preproc++; 711 report("indent = $count != 0 for '#'") if $count != 0; 712 report("'#$preproc_directive' with constant condition") 713 if $preproc_directive =~ m/^(if|elif)$/ && m/^[\W0-9]+$/ && !$trailing_backslash; 714 $preproc_if_nesting-- if $preproc_directive =~ m/^(else|elif|endif)$/; 715 if ($preproc_if_nesting < 0) { 716 $preproc_if_nesting = 0; 717 report("unexpected '#$preproc_directive' according to '#if' nesting"); 718 } 719 my $space_count = length($space); # maybe could also use indentation before '#' 720 report("'#if' nesting indent = $space_count != $preproc_if_nesting") if $space_count != $preproc_if_nesting; 721 $preproc_if_nesting++ if $preproc_directive =~ m/^(if|ifdef|ifndef|else|elif)$/; 722 $ifdef__cplusplus = $preproc_directive eq "ifdef" && m/\s+__cplusplus\s*$/; 723 724 # handle indentation of preprocessor directive independently of surrounding normal code 725 $count = -1; # do not check indentation of first line of preprocessor directive 726 backup_indentation_state(); 727 reset_indentation_state(); 728 } 729 730 # intra-line whitespace nits @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 731 732 my $in_multiline_comment = ($in_comment > 1 || $in_comment < 0); # $in_multiline_comment refers to line before 733 if (!$sloppy_SPC && !($in_multiline_comment && $formatted_comment)) { 734 sub extra_SPC { 735 my $intra_line = shift; 736 return "extra space".($intra_line =~ m/@\s\s/ ? 737 $in_comment != 0 ? " in multi-line comment" 738 : " in intra-line comment" : ""); 739 } 740 sub split_line_head { # split line contents into header containing leading spaces and the first non-space char, and the rest of the line 741 my $comment_symbol = 742 $in_comment != 0 ? "@" : ""; # '@' will match the blinded leading '*' in multi-line comment 743 # $in_comment may pertain to the following line due to delayed check 744 # do not check for extra SPC in leading spaces including any '#' (or '*' within multi-line comment) 745 shift =~ m/^(\s*([#$comment_symbol]\s*)?)(.*?)\s*$/; 746 return ($1, $3); 747 } 748 my ($head , $intra_line ) = split_line_head($_); 749 my ($head1, $intra_line1) = split_line_head($contents_before_ ) if $line_before > 0; 750 my ($head2, $intra_line2) = split_line_head($contents_before_2) if $line_before2 > 0; 751 if ($line_before > 0) { # check with one line delay, such that at least $contents_before is available 752 sub column_alignments_only { # return 1 if the given line has multiple consecutive spaces only at columns that match the reference line 753 # all parameter strings are assumed to contain contents after blinding comments etc. 754 my $head = shift; # leading spaces and the first non-space char 755 my $intra = shift; # the rest of the line contents 756 my $contents = shift; # reference line 757 # check if all extra SPC in $intra is used only for multi-line column alignment with $contents 758 my $offset = length($head); 759 for (my $col = 0; $col < length($intra) - 2; $col++) { 760 my $substr = substr($intra, $col); 761 next unless $substr =~ m/^\s\s\S/; # extra SPC (but not in leading spaces of the line) 762 next if !$eol_cmt && $substr =~ m/^[@\s]+$/; # end-of-line comment 763 return 0 unless substr($contents, $col + $offset + 1, 2) =~ m/\s\S/; # reference line contents do not match 764 } 765 return 1; 766 } 767 report_flexibly($line_before, extra_SPC($intra_line1), $contents_before) if $intra_line1 =~ m/\s\s\S/ && 768 !( column_alignments_only($head1, $intra_line1, $_ ) # compare with $line 769 || ($line_before2 > 0 && 770 column_alignments_only($head1, $intra_line1, $contents_before_2))); # compare w/ $line_before2 771 report(extra_SPC($intra_line)) if $intra_line =~ m/\s\s\S/ && eof 772 && ! column_alignments_only($head , $intra_line , $contents_before_ ) ; # compare w/ $line_before 773 } elsif (eof) { # special case: just one line exists 774 report(extra_SPC($intra_line)) if $intra_line =~ m/\s\s\S/; 775 } 776 # ignore paths in #include 777 $intra_line =~ s/^(include\s*)(".*?"|<.*?>)/$1/e if $head =~ m/#/; 778 report("missing space before '$2'") 779 if $intra_line =~ m/(\S)((<<|>>)=)/ # '<<=' or >>=' without preceding space 780 || ($intra_line =~ m/(\S)([\+\-\*\/\/%\&\|\^\!<>=]=)/ 781 && "$1$2" ne "<<=" && "$1$2" ne ">>=") # other <op>= or (in)equality without preceding space 782 || ($intra_line =~ m/(\S)=/ 783 && !($1 =~ m/[\+\-\*\/\/%\&\|\^\!<>=]/) 784 && $intra_line =~ m/(\S)(=)/); # otherwise, '=' without preceding space 785 # treat op= and comparison operators as simple '=', simplifying matching below 786 $intra_line =~ s/(<<|>>|[\+\-\*\/\/%\&\|\^\!<>=])=/=/g; 787 # treat (type) variables within macro, indicated by trailing '\', as 'int' simplifying matching below 788 $intra_line =~ s/[A-Z_]+/int/g if $trailing_backslash; 789 # treat double &&, ||, <<, and >> as single ones, simplifying matching below 790 $intra_line =~ s/(&&|\|\||<<|>>)/substr($1, 0, 1)/eg; 791 # remove blinded comments etc. directly after [{( 792 while ($intra_line =~ s/([\[\{\(])@+\s?/$1/e) {} # /g does not work here 793 # remove blinded comments etc. directly before ,;)}] 794 while ($intra_line =~ s/\s?@+([,;\)\}\]])/$1/e) {} # /g does not work here 795 # treat remaining blinded comments and string literal contents as (single) space during matching below 796 $intra_line =~ s/@+/ /g; # note that extra SPC has already been handled above 797 $intra_line =~ s/\s+$//; # strip any (resulting) space at EOL 798 # replace ';;' or '; ;' by ';' in "for (;;)" and in "for (...)" unless "..." contains just SPC and ';' characters: 799 $intra_line =~ s/((^|\W)for\s*\()([^;]*?)(\s*)(;\s?);(\s*)([^;]*)(\))/ 800 "$1$3$4".("$3$4$5$6$7" eq ";" || $3 ne "" || $7 ne "" ? "" : $5).";$6$7$8"/eg; 801 # strip trailing ';' or '; ' in "for (...)" except in "for (;;)" or "for (;; )": 802 $intra_line =~ s/((^|\W)for\s*\()([^;]*(;[^;]*)?)(;\s?)(\))/ 803 "$1$3".($3 eq ";" ? $5 : "")."$6"/eg; 804 $intra_line =~ s/(=\s*)\{ /"$1@ "/eg; # do not report {SPC in initializers such as ' = { 0, };' 805 $intra_line =~ s/, \};/, @;/g; # do not report SPC} in initializers such as ' = { 0, };' 806 report("space before '$1'") if $intra_line =~ m/[\w)\]]\s+(\+\+|--)/; # postfix ++/-- with preceding space 807 report("space after '$1'") if $intra_line =~ m/(\+\+|--)\s+[a-zA-Z_(]/; # prefix ++/-- with following space 808 $intra_line =~ s/\.\.\./@/g; # blind '...' 809 report("space before '$1'") if $intra_line =~ m/\s(\.|->)/; # '.' or '->' with preceding space 810 report("space after '$1'") if $intra_line =~ m/(\.|->)\s/; # '.' or '->' with following space 811 $intra_line =~ s/\-\>|\+\+|\-\-/@/g; # blind '->,', '++', and '--' 812 report("space before '$1'") if $intra_line =~ m/[^:)]\s+(;)/; # space before ';' but not after ':' or ')' # note that 813 # exceptions for "for (;; )" are handled above 814 report("space before '$1'") if $intra_line =~ m/\s([,)\]])/; # space before ,)] 815 report("space after '$1'") if $intra_line =~ m/([(\[~!])\s/; # space after ([~! 816 report("space after '$1'") if $intra_line =~ m/(defined)\s/; # space after 'defined' 817 report("missing space before '$1'") if $intra_line =~ m/\S([|\/%<>^\?])/; # |/%<>^? without preceding space 818 # TODO ternary ':' without preceding SPC, while allowing no SPC before ':' after 'case' 819 report("missing space before binary '$2'") if $intra_line =~ m/([^\s{()\[e])([+\-])/; # '+'/'-' without preceding space or {()[e 820 # ')' may be used for type casts or before "->", 'e' may be used for numerical literals such as "1e-6" 821 report("missing space before binary '$1'") if $intra_line =~ m/[^\s{()\[*!]([*])/; # '*' without preceding space or {()[*! 822 report("missing space before binary '$1'") if $intra_line =~ m/[^\s{()\[]([&])/; # '&' without preceding space or {()[ 823 report("missing space after ternary '$1'") if $intra_line =~ m/(:)[^\s\d]/; # ':' without following space or digit 824 report("missing space after '$1'") if $intra_line =~ m/([,;=|\/%<>^\?])\S/; # ,;=|/%<>^? without following space 825 report("missing space after binary '$1'") if $intra_line=~m/[^{(\[]([*])[^\sa-zA-Z_(),*]/;# '*' w/o space or \w(),* after 826 # TODO unary '*' must not be followed by SPC 827 report("missing space after binary '$1'") if $intra_line=~m/([&])[^\sa-zA-Z_(]/; # '&' w/o following space or \w( 828 # TODO unary '&' must not be followed by SPC 829 report("missing space after binary '$1'") if $intra_line=~m/[^{(\[]([+\-])[^\s\d(]/; # +/- w/o following space or \d( 830 # TODO unary '+' and '-' must not be followed by SPC 831 report("missing space after '$2'") if $intra_line =~ m/(^|\W)(if|while|for|switch|case)[^\w\s]/; # kw w/o SPC 832 report("missing space after '$2'") if $intra_line =~ m/(^|\W)(return)[^\w\s;]/; # return w/o SPC or ';' 833 report("space after function/macro name") 834 if $intra_line =~ m/(\w+)\s+\(/ # fn/macro name with space before '(' 835 && !($1 =~ m/^(sizeof|if|else|while|do|for|switch|case|default|break|continue|goto|return|void|char|signed|unsigned|int|short|long|float|double|typedef|enum|struct|union|auto|extern|static|const|volatile|register)$/) # not keyword 836 && !(m/^\s*#\s*define\s+\w+\s+\(/) # not a macro without parameters having a body that starts with '(' 837 && !(m/^\s*typedef\W/); # not a typedef 838 report("missing space before '{'") if $intra_line =~ m/[^\s{(\[]\{/; # '{' without preceding space or {([ 839 report("missing space after '}'") if $intra_line =~ m/\}[^\s,;\])}]/; # '}' without following space or ,;])} 840 } 841 842 # adapt required indentation @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 843 844 s/(\w*ASN1_[A-Z_]+END\w*([^(]|\(.*?\)|$))/$1;/g; # treat *ASN1_*END*(..) macro calls as if followed by ';' 845 846 my $nested_indents_position = 0; 847 848 # update indents according to leading closing brace(s) '}' or label or switch case 849 my $in_stmt = $in_expr || @nested_symbols != 0 || $in_typedecl != 0; 850 if ($in_stmt) { # expr/stmt/type decl/var def/fn hdr, i.e., not at block level 851 if (m/^([\s@]*\})/) { # leading '}' within stmt, any preceding blinded comment must not be matched 852 $in_block_decls = -1; 853 my $head = $1; 854 update_nested_indents($head); 855 $nested_indents_position = length($head); 856 if (@nested_symbols >= 1) { 857 $hanging_symbol = @nested_symbols[-1]; 858 $expr_indent = @nested_indents[-1]; 859 } else { # typically end of initialiizer expr or enum 860 $expr_indent = 0; 861 } 862 } elsif (m/^([\s@]*)(static_)?ASN1_ITEM_TEMPLATE_END(\W|$)/) { # workaround for ASN1 macro indented as '}' 863 $local_offset = -INDENT_LEVEL; 864 $expr_indent = 0; 865 } elsif (m/;.*?\}/) { # expr ends with ';' before '}' 866 report("code before '}'"); 867 } 868 } 869 if (@in_do_hanging_offsets != 0 && # note there is nothing like "unexpected 'while'" 870 m/^[\s@]*while(\W|$)/) { # leading 'while' 871 $hanging_offset = pop @in_do_hanging_offsets; 872 } 873 if ($if_maybe_terminated) { 874 if (m/(^|\W)else(\W|$)/) { # (not necessarily leading) 'else' 875 if (@in_if_hanging_offsets == 0) { 876 report("unexpected 'else'"); 877 } else { 878 $hanging_offset = pop @in_if_hanging_offsets; 879 } 880 } else { 881 @in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'" 882 $hanging_offset = 0; 883 } 884 } 885 if (!$in_stmt) { # at block level, i.e., outside expr/stmt/type decl/var def/fn hdr 886 $if_maybe_terminated = 0; 887 if (my ($head, $before, $tail) = m/^([\s@]*([^{}]*)\})[\s@]*(.*)$/) { # leading closing '}', but possibly 888 # with non-whitespace non-'{' before 889 report("code after '}'") unless $tail eq "" || $tail =~ m/(else|while|OSSL_TRACE_END)(\W|$)/; 890 my $outermost_level = @nested_block_indents == 1 && @nested_block_indents[0] == 0; 891 if (!$sloppy_bodylen && $outermost_level && $line_body_start != 0) { 892 my $body_len = $line - $line_body_start - 1; 893 report_flexibly($line_function_start, "function body length = $body_len > ".MAX_BODY_LENGTH." lines", 894 $last_function_header) if $body_len > MAX_BODY_LENGTH; 895 $line_body_start = 0; 896 } 897 if ($before ne "") { # non-whitespace non-'{' before '}' 898 report("code before '}'"); 899 } else { # leading '}' outside stmt, any preceding blinded comment must not be matched 900 $in_block_decls = -1; 901 $local_offset = $block_indent + $hanging_offset - INDENT_LEVEL; 902 update_nested_indents($head); 903 $nested_indents_position = length($head); 904 $local_offset -= ($block_indent + $hanging_offset); 905 # in effect $local_offset = -INDENT_LEVEL relative to $block_indent + $hanging_offset values before 906 } 907 } 908 909 # handle opening brace '{' after if/else/while/for/switch/do on line before 910 if ($hanging_offset > 0 && m/^[\s@]*{/ && # leading opening '{' 911 $line_before > 0 && 912 $contents_before_ =~ m/(^|^.*\W)(if|else|while|for|(OSSL_)?LIST_FOREACH(_\w+)?|switch|do)(\W.*$|$)/) { 913 $keyword_opening_brace = $1; 914 $hanging_offset -= INDENT_LEVEL; # cancel newly hanging_offset 915 } 916 917 if (m/^[\s@]*(case|default)(\W.*$|$)/) { # leading 'case' or 'default' 918 my ($keyword, $rest) = ($1, $2); 919 report("code after $keyword: ") if $rest =~ /:.*[^\s@]/ && ! 920 ($rest =~ /:[\s@]*\{[\s@]*$/); # after, ':', trailing '{'; 921 $local_offset = -INDENT_LEVEL; 922 } else { 923 if (m/^([\s@]*)(\w+):/) { # (leading) label, cannot be "default" 924 $local_offset = -INDENT_LEVEL; 925 $has_label = 1; 926 } 927 } 928 } 929 930 # potential adaptations of indent in first line of macro body in multi-line macro definition 931 if ($in_preproc != 0 && $in_macro_header > 0) { 932 if ($in_macro_header > 1) { # still in macro definition header 933 $in_macro_header += parens_balance($_); 934 } else { # begin of macro body 935 $in_macro_header = 0; 936 if ($count == $block_indent - $preproc_offset # body began with same indentation as preceding code 937 && $sloppy_macro) { # workaround for this situation is enabled 938 $block_indent -= $preproc_offset; 939 $preproc_offset = 0; 940 } 941 } 942 } 943 944 # check required indentation @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 945 946 check_indent() if $count >= 0; # not for start of preprocessor directive and not if multi-line string literal is continued 947 948 # check for blank lines within/after local decls @@@@@@@@@@@@@@@@@@@@@@@@@@@ 949 950 if ($in_block_decls >= 0 && 951 $in_comment == 0 && !m/^\s*\*?@/ && # not in a multi-line or intra-line comment 952 !$in_expr && $expr_indent == 0 && $in_typedecl == 0) { 953 my $blank_line_before = $line > 1 && $code_contents_before =~ m/^\s*(\\\s*)?$/; 954 # essentially blank line before: just whitespace and maybe a '\' 955 if (m/^[\s(]*(char|signed|unsigned|int|short|long|float|double|enum|struct|union|auto|extern|static|const|volatile|register)(\W|$)/ # clear start of local decl 956 || (m/^(\s*(\w+|\[\]|[\*()]))+?\s+[\*\(]*\w+(\s*(\)|\[[^\]]*\]))*\s*[;,=]/ # weak check for decl involving user-defined type 957 && !m/^\s*(\}|sizeof|if|else|while|do|for|switch|case|default|break|continue|goto|return)(\W|$)/)) { 958 $in_block_decls++; 959 report_flexibly($line - 1, "blank line within local decls, before", $contents) if $blank_line_before; 960 } else { 961 report_flexibly($line, "missing blank line after local decls", "\n$contents_before$contents") 962 if $in_block_decls > 0 && !$blank_line_before; 963 $in_block_decls = -1 unless 964 m/^\s*(\\\s*)?$/ # essentially blank line: just whitespace (and maybe a trailing '\') 965 || $in_comment != 0 || m/^\s*\*?@/; # in multi-line comment or an intra-line comment 966 } 967 } 968 969 $in_comment = 0 if $in_comment < 0; # multi-line comment has ended 970 971 # do some further checks @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 972 973 my $outermost_level = $block_indent - $preproc_offset == 0; 974 975 report("more than one stmt") if !m/(^|\W)(for|(OSSL_)?LIST_FOREACH(_\w+)?)(\W.*|$)/ && # no 'for' - TODO improve matching 976 m/;.*;/; # two or more terminators ';', so more than one statement 977 978 # check for code block containing a single line/statement 979 if ($line_before2 > 0 && !$outermost_level && # within function body 980 $in_typedecl == 0 && @nested_indents == 0 && # neither within type declaration nor inside stmt/expr 981 m/^[\s@]*\}\s*(\w*)/) { # leading closing brace '}', any preceding blinded comment must not be matched 982 # TODO extend detection from single-line to potentially multi-line statement 983 my $next_word = $1; 984 if ($line_opening_brace > 0 && 985 ($keyword_opening_brace ne "if" || 986 $extended_1_stmt || $next_word ne "else") && # --1-stmt or 'if' without 'else' 987 ($line_opening_brace == $line_before2 || 988 $line_opening_brace == $line_before) 989 && $contents_before =~ m/;/) { # there is at least one terminator ';', so there is some stmt 990 # TODO do not report cases where a further else branch 991 # follows with a block containing more than one line/statement 992 report_flexibly($line_before, "'$keyword_opening_brace' { 1 stmt }", $contents_before); 993 } 994 } 995 996 report("single-letter name '$2'") if (m/(^|.*\W)([IO])(\W.*|$)/); # single-letter name 'I' or 'O' # maybe re-add 'l'? 997 # constant on LHS of comparison or assignment, e.g., NULL != x or 'a' < c, but not a + 1 == b 998 report("constant on LHS of '$3'") 999 if (m/(['"]|([\+\-\*\/\/%\&\|\^<>]\s*)?\W[0-9]+L?|\WNULL)\s*([\!<>=]=|[<=>])([<>]?)/ && 1000 $2 eq "" && (($3 ne "<" && $3 ne "='" && $3 ne ">") || $4 eq "")); 1001 1002 # TODO report needless use of parentheses, while 1003 # macro parameters should always be in parens (except when passed on), e.g., '#define ID(x) (x)' 1004 1005 # adapt required indentation for following lines @@@@@@@@@@@@@@@@@@@@@@@@@@@ 1006 1007 # set $in_expr, $in_paren_expr, and $hanging_offset for if/while/for/switch, return/enum, and assignment RHS 1008 my $paren_expr_start = 0; 1009 my $return_enum_start = 0; 1010 my $assignment_start = 0; 1011 my $tmp = $_; 1012 $tmp =~ s/[\!<>=]=/@@/g; # blind (in-)equality symbols like '<=' as '@@' to prevent matching them as '=' below 1013 if (m/^((^|.*\W)(if|while|for|(OSSL_)?LIST_FOREACH(_\w+)?|switch))(\W.*|$)$/) { # (last) if/for/while/switch 1014 $paren_expr_start = 1; 1015 } elsif (m/^((^|.*\W)(return|enum))(\W.*|$)/ # (last) return/enum 1016 && !$in_expr && @nested_indents == 0 && parens_balance($1) == 0) { # not nested enum 1017 $return_enum_start = 1; 1018 } elsif ($tmp =~ m/^(([^=]*)(=))(.*)$/ # (last) '=', i.e., assignment 1019 && !$in_expr && @nested_indents == 0 && parens_balance($1) == 0) { # not nested assignment 1020 $assignment_start = 1; 1021 } 1022 if ($paren_expr_start || $return_enum_start || $assignment_start) 1023 { 1024 my ($head, $pre, $mid, $tail) = ($1, $2, $3, $4); 1025 $keyword_opening_brace = $mid if $mid ne "="; 1026 $keyword_opening_brace = "else if" if $pre =~ m/(^|\W)else[\s@]+$/ && $mid eq "if" && !$extended_1_stmt; # prevent reporting "{ 1 stmt }" on "else if" unless --1-stmt 1027 # to cope with multi-line expressions, do this also if !($tail =~ m/\{/) 1028 push @in_if_hanging_offsets, $hanging_offset if $mid eq "if"; 1029 1030 # already handle $head, i.e., anything before expression 1031 update_nested_indents($head, $nested_indents_position); 1032 $nested_indents_position = length($head); 1033 # now can set $in_expr and $in_paren_expr 1034 $in_expr = 1; 1035 $in_paren_expr = 1 if $paren_expr_start; 1036 if ($mid eq "while" && @in_do_hanging_offsets != 0) { 1037 $hanging_offset = pop @in_do_hanging_offsets; 1038 } else { 1039 $hanging_offset += INDENT_LEVEL; # tentatively set hanging_offset, may be canceled by following '{' 1040 } 1041 } 1042 1043 # set $hanging_offset and $keyword_opening_brace for do/else 1044 if (my ($head, $mid, $tail) = m/(^|^.*\W)(else|do)(\W.*|$)$/) { # last else/do, where 'do' is preferred, but not #else 1045 my $code_before = $head =~ m/[^\s\@}]/; # leading non-whitespace non-comment non-'}' 1046 report("code before '$mid'") if $code_before; 1047 report("code after '$mid'" ) if $tail =~ m/[^\s\@{]/# trailing non-whitespace non-comment non-'{' (non-'\') 1048 && !($mid eq "else" && $tail =~ m/[\s@]*if(\W|$)/); 1049 if ($mid eq "do") { # workarounds for code before 'do' 1050 if ($head =~ m/(^|^.*\W)(else)(\W.*$|$)/) { # 'else' ... 'do' 1051 $hanging_offset += INDENT_LEVEL; # tentatively set hanging_offset, may be canceled by following '{' 1052 } 1053 if ($head =~ m/;/) { # terminator ';' ... 'do' 1054 @in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'" 1055 $hanging_offset = 0; 1056 } 1057 } 1058 push @in_do_hanging_offsets, $hanging_offset if $mid eq "do"; 1059 if ($code_before && $mid eq "do") { 1060 $hanging_offset = length($head) - $block_indent; 1061 } 1062 if (!$in_paren_expr) { 1063 $keyword_opening_brace = $mid if $tail =~ m/\{/; 1064 $hanging_offset += INDENT_LEVEL; 1065 } 1066 } 1067 1068 # set $in_typedecl and potentially $hanging_offset for type declaration 1069 if (!$in_expr && @nested_indents == 0 # not in expression 1070 && m/(^|^.*\W)(typedef|enum|struct|union)(\W.*|$)$/ 1071 && parens_balance($1) == 0 # not in newly started expression or function arg list 1072 && ($2 eq "typedef" || !($3 =~ m/\s*\w++\s*(.)/ && $1 ne "{")) # 'struct'/'union'/'enum' <name> not followed by '{' 1073 # not needed: && $keyword_opening_brace = $2 if $3 =~ m/\{/; 1074 ) { 1075 $in_typedecl++; 1076 $hanging_offset += INDENT_LEVEL if m/\*.*\(/; # '*' followed by '(' - seems consistent with Emacs C mode 1077 } 1078 1079 my $local_in_expr = $in_expr; 1080 my $terminator_position = update_nested_indents($_, $nested_indents_position); 1081 1082 if ($local_in_expr) { 1083 # on end of non-if/while/for/switch (multi-line) expression (i.e., return/enum/assignment) and 1084 # on end of statement/type declaration/variable definition/function header 1085 if ($terminator_position >= 0 && ($in_typedecl == 0 || @nested_indents == 0)) { 1086 check_nested_nonblock_indents("expr"); 1087 $in_expr = 0; 1088 } 1089 } else { 1090 check_nested_nonblock_indents($in_typedecl == 0 ? "stmt" : "decl") if $terminator_position >= 0; 1091 } 1092 1093 # on ';', which terminates the current statement/type declaration/variable definition/function declaration 1094 if ($terminator_position >= 0) { 1095 my $tail = substr($_, $terminator_position + 1); 1096 if (@in_if_hanging_offsets != 0) { 1097 if ($tail =~ m/\s*else(\W|$)/) { 1098 pop @in_if_hanging_offsets; 1099 $hanging_offset -= INDENT_LEVEL; 1100 } elsif ($tail =~ m/[^\s@]/) { # code (not just comment) follows 1101 @in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'" 1102 $hanging_offset = 0; 1103 } else { 1104 $if_maybe_terminated = 1; 1105 } 1106 } elsif ($tail =~ m/^[\s@]*$/) { # ';' has been trailing, i.e. there is nothing but whitespace and comments 1107 $hanging_offset = 0; # reset in case of terminated assignment ('=') etc. 1108 } 1109 $in_typedecl-- if $in_typedecl != 0 && @nested_in_typedecl == 0; # TODO handle multiple type decls per line 1110 m/(;[^;]*)$/; # match last ';' 1111 $terminator_position = length($_) - length($1) if $1; 1112 # new $terminator_position value may be after the earlier one in case multiple terminators on current line 1113 # TODO check treatment in case of multiple terminators on current line 1114 update_nested_indents($_, $terminator_position + 1); 1115 } 1116 1117 # set hanging expression indent according to nested indents - TODO maybe do better in update_nested_indents() 1118 # also if $in_expr is 0: in statement/type declaration/variable definition/function header 1119 $expr_indent = 0; 1120 for (my $i = -1; $i >= -@nested_symbols; $i--) { 1121 if (@nested_symbols[$i] ne "?") { # conditionals '?' ... ':' are treated specially in check_indent() 1122 $hanging_symbol = @nested_symbols[$i]; 1123 $expr_indent = $nested_indents[$i]; 1124 # $expr_indent is guaranteed to be != 0 unless @nested_indents contains just outer conditionals 1125 last; 1126 } 1127 } 1128 1129 # remember line number and header containing name of last function defined for reports w.r.t. MAX_BODY_LENGTH 1130 if ($in_preproc == 0 && $outermost_level && m/(\w+)\s*\(/ && $1 ne "STACK_OF") { 1131 $line_function_start = $line; 1132 $last_function_header = $contents; 1133 } 1134 1135 # special checks for last, typically trailing opening brace '{' in line 1136 if (my ($head, $tail) = m/^(.*)\{(.*)$/) { # match last ... '{' 1137 if (!$in_expr && $in_typedecl == 0) { 1138 if ($outermost_level) { 1139 if (!$assignment_start && !$local_in_expr) { 1140 # at end of function definition header (or stmt or var definition) 1141 report("'{' not at line start") if length($head) != $preproc_offset && $head =~ m/\)\s*/; # at end of function definition header 1142 $line_body_start = $contents =~ m/LONG BODY/ ? 0 : $line if $line_function_start != 0; 1143 } 1144 } else { # prepare detection of { 1 stmt } 1145 $line_opening_brace = $line if $keyword_opening_brace =~ m/^(if|do|while|for|(OSSL_)?LIST_FOREACH(_\w+)?)$/; 1146 # using, not assigning, $keyword_opening_brace here because it could be on an earlier line 1147 $line_opening_brace = $line if $keyword_opening_brace =~ m/else|else if/ && $extended_1_stmt && 1148 # TODO prevent false positives for if/else where braces around single-statement branches 1149 # should be avoided but only if all branches have just single statements 1150 # The following helps detecting the exception when handling multiple 'if ... else' branches: 1151 !($keyword_opening_brace eq "else" && $line_opening_brace < $line_before2); 1152 } 1153 report("code after '{'") if $tail=~ m/[^\s\@]/ && # trailing non-whitespace non-comment (non-'\') 1154 !($tail=~ m/\}/); # missing '}' after last '{' 1155 } 1156 } 1157 1158 # check for opening brace after if/while/for/switch/do missing on same line 1159 # note that "missing '{' on same line after '} else'" is handled further below 1160 if (/^[\s@]*{/ && # leading '{' 1161 $line_before > 0 && !($contents_before_ =~ m/^\s*#/) && # not preprocessor directive '#if 1162 (my ($head, $mid, $tail) = ($contents_before_ =~ m/(^|^.*\W)(if|while|for|(OSSL_)?LIST_FOREACH(_\w+)?|switch|do)(\W.*$|$)/))) { 1163 my $brace_after = $tail =~ /^[\s@]*{/; # any whitespace or comments then '{' 1164 report("'{' not on same line as preceding '$mid'") if !$brace_after; 1165 } 1166 # check for closing brace on line before 'else' not followed by leading '{' 1167 elsif (my ($head, $tail) = m/(^|^.*\W)else(\W.*$|$)/) { 1168 if (parens_balance($tail) == 0 && # avoid false positive due to unfinished expr on current line 1169 !($tail =~ m/{/) && # after 'else' missing '{' on same line 1170 !($head =~ m/}[\s@]*$/) && # not: '}' then any whitespace or comments before 'else' 1171 $line_before > 0 && $contents_before_ =~ /}[\s@]*$/) { # trailing '}' on line before 1172 report("missing '{' on same line after '} else'"); 1173 } 1174 } 1175 1176 # check for closing brace before 'while' not on same line 1177 if (my ($head, $tail) = m/(^|^.*\W)while(\W.*$|$)/) { 1178 my $brace_before = $head =~ m/}[\s@]*$/; # '}' then any whitespace or comments 1179 # possibly 'if (...)' (with potentially inner '(' and ')') then any whitespace or comments then '{' 1180 if (!$brace_before && 1181 # does not work here: @in_do_hanging_offsets != 0 && #'while' terminates loop 1182 parens_balance($tail) == 0 && # avoid false positive due to unfinished expr on current line 1183 $tail =~ /;/ && # 'while' terminates loop (by ';') 1184 $line_before > 0 && 1185 $contents_before_ =~ /}[\s@]*$/) { # on line before: '}' then any whitespace or comments 1186 report("'while' not on same line as preceding '}'"); 1187 } 1188 } 1189 1190 # check for missing brace on same line before or after 'else' 1191 if (my ($head, $tail) = m/(^|^.*\W)else(\W.*$|$)/) { 1192 my $brace_before = $head =~ /}[\s@]*$/; # '}' then any whitespace or comments 1193 my $brace_after = $tail =~ /^[\s@]*if[\s@]*\(.*\)[\s@]*{|[\s@]*{/; 1194 # possibly 'if (...)' (with potentially inner '(' and ')') then any whitespace or comments then '{' 1195 if (!$brace_before) { 1196 if ($line_before > 0 && $contents_before_ =~ /}[\s@]*$/) { 1197 report("'else' not on same line as preceding '}'"); 1198 } elsif (parens_balance($tail) == 0) { # avoid false positive due to unfinished expr on current line 1199 report("missing '}' on same line before 'else ... {'") if $brace_after; 1200 } 1201 } elsif (parens_balance($tail) == 0) { # avoid false positive due to unfinished expr on current line 1202 report("missing '{' on same line after '} else'") if $brace_before && !$brace_after; 1203 } 1204 } 1205 1206 # on begin of multi-line preprocessor directive, adapt indent 1207 if ($in_comment == 0 && $trailing_backslash) { 1208 # trailing '\'typically used in preprocessor directive like '#define' 1209 if ($in_preproc == 1) { # start of multi-line preprocessor directive 1210 # note that backup+reset_indentation_state() has already been called 1211 $in_macro_header = m/^\s*#\s*define(\W|$)?(.*)/ ? 1 + parens_balance($2) : 0; # '#define' is beginning 1212 $preproc_offset = INDENT_LEVEL; 1213 $block_indent = $preproc_offset; 1214 } 1215 $in_preproc += 1; 1216 } 1217 1218 # post-processing at end of line @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1219 1220 LINE_FINISHED: 1221 $code_contents_before = $contents if 1222 !m/^\s*#(\s*)(\w+)/ && # not single-line preprocessor directive 1223 $in_comment == 0 && !m/^\s*\*?@/; # not in a multi-line comment nor in an intra-line comment 1224 1225 # on end of (possibly multi-line) preprocessor directive, adapt indent 1226 if ($in_preproc != 0 && !$trailing_backslash) { # no trailing '\' 1227 $in_preproc = 0; 1228 $preproc_offset = 0; 1229 restore_indentation_state(); 1230 } 1231 1232 if ($essentially_blank_line) { 1233 report("leading ".($1 eq "" ? "blank" :"whitespace")." line") if $line == 1 && !$sloppy_SPC; 1234 } else { 1235 if ($line_before > 0) { 1236 my $linediff = $line - $line_before - 1; 1237 report("$linediff blank lines before") if $linediff > 1 && !$sloppy_SPC; 1238 } 1239 $line_before2 = $line_before; 1240 $contents_before2 = $contents_before; 1241 $contents_before_2 = $contents_before_; 1242 $line_before = $line; 1243 $contents_before = $contents; 1244 $contents_before_ = $_; 1245 $count_before = $count; 1246 } 1247 1248 if ($self_test) { # debugging 1249 my $should_report = $contents =~ m/\*@(\d)?/ ? 1 : 0; 1250 $should_report = +$1 if $should_report != 0 && defined $1; 1251 print("$ARGV:$line:$num_reports_line reports on:$contents") 1252 if $num_reports_line != $should_report; 1253 } 1254 $num_reports_line = 0; 1255 1256 # post-processing at end of file @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1257 1258 if (eof) { 1259 # check for essentially blank line (which may include a '\') just before EOF 1260 report(($1 eq "\n" ? "blank line" : $2 ne "" ? "'\\'" : "whitespace")." at EOF") 1261 if $contents =~ m/^(\s*(\\?)\s*)$/ && !$sloppy_SPC; 1262 1263 # report unclosed expression-level nesting 1264 check_nested_nonblock_indents("expr at EOF"); # also adapts @nested_block_indents 1265 1266 # sanity-check balance of block-level { ... } via final $block_indent at end of file 1267 report_flexibly($line, +@nested_block_indents." unclosed '{'", "(EOF)\n") if @nested_block_indents != 0; 1268 1269 # sanity-check balance of #if ... #endif via final preprocessor directive indent at end of file 1270 report_flexibly($line, "$preproc_if_nesting unclosed '#if'", "(EOF)\n") if $preproc_if_nesting != 0; 1271 1272 reset_file_state(); 1273 } 1274} 1275 1276# final summary report @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1277 1278my $num_other_reports = $num_reports - $num_indent_reports - $num_nesting_issues 1279 - $num_syntax_issues - $num_SPC_reports - $num_length_reports; 1280print "$num_reports ($num_indent_reports indentation, $num_nesting_issues '#if' nesting indent, ". 1281 "$num_syntax_issues syntax, $num_SPC_reports whitespace, $num_length_reports length, $num_other_reports other)". 1282 " issues have been found by $0\n" if $num_reports != 0 && !$self_test; 1283