check-format.pl 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. #!/usr/bin/perl
  2. #
  3. # Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
  4. # Copyright Siemens AG 2019-2020
  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|--sloppy-len] [-l|--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 | --sloppy-len increase accepted max line length from 80 to 84
  32. # -l | --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 by checks for this rule by defaul only for do/while/for bodies.
  66. # Yet with the --1-stmt option false positives are preferred over negatives.
  67. # False negatives occur if the braces are more than two non-empty lines apart.
  68. #
  69. # * The presence of multiple consecutive spaces is regarded a coding style nit
  70. # except when this is before end-of-line comments (unless the --eol-comment is given) and
  71. # except when done in order to align certain columns over multiple lines, e.g.:
  72. # # define AB 1
  73. # # define CDE 22
  74. # # define F 3333
  75. # This pattern is recognized - and consequently extra space not reported -
  76. # for a given line if in the nonempty line before or after (if existing)
  77. # for each occurrence of " \S" (where \S means non-space) in the given line
  78. # there is " \S" in the other line in the respective column position.
  79. # This may lead to both false negatives (in case of coincidental " \S")
  80. # and false positives (in case of more complex multi-column alignment).
  81. #
  82. # * When just part of control structures depend on #if(n)(def), which can be
  83. # considered bad programming style, indentation false positives occur, e.g.:
  84. # #if X
  85. # if (1) /* bad style */
  86. # #else
  87. # if (2) /* bad style resulting in false positive */
  88. # #endif
  89. # c; /* resulting further false positive */
  90. use strict;
  91. # use List::Util qw[min max];
  92. use POSIX;
  93. use constant INDENT_LEVEL => 4;
  94. use constant MAX_LINE_LENGTH => 80;
  95. use constant MAX_BODY_LENGTH => 200;
  96. # global variables @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  97. # command-line options
  98. my $max_length = MAX_LINE_LENGTH;
  99. my $sloppy_bodylen = 0;
  100. my $sloppy_SPC = 0;
  101. my $sloppy_hang = 0;
  102. my $sloppy_cmt = 0;
  103. my $sloppy_macro = 0;
  104. my $eol_cmt = 0;
  105. my $extended_1_stmt = 0;
  106. while ($ARGV[0] =~ m/^-(\w|-[\w\-]+)$/) {
  107. my $arg = $1; shift;
  108. if ($arg =~ m/^(l|-sloppy-len)$/) {
  109. $max_length += INDENT_LEVEL;
  110. } elsif ($arg =~ m/^(b|-sloppy-bodylen)$/) {
  111. $sloppy_bodylen = 1;
  112. } elsif ($arg =~ m/^(s|-sloppy-space)$/) {
  113. $sloppy_SPC= 1;
  114. } elsif ($arg =~ m/^(c|-sloppy-comment)$/) {
  115. $sloppy_cmt = 1;
  116. } elsif ($arg =~ m/^(m|-sloppy-macro)$/) {
  117. $sloppy_macro = 1;
  118. } elsif ($arg =~ m/^(h|-sloppy-hang)$/) {
  119. $sloppy_hang = 1;
  120. } elsif ($arg =~ m/^(e|-eol-comment)$/) {
  121. $eol_cmt = 1;
  122. } elsif ($arg =~ m/^(1|-1-stmt)$/) {
  123. $extended_1_stmt = 1;
  124. } else {
  125. die("unknown option: -$arg");
  126. }
  127. }
  128. # status variables
  129. my $self_test; # whether the current input file is regarded to contain (positive/negative) self-tests
  130. my $line; # current line number
  131. my $line_before; # number of previous not essentially empty line (containing at most whitespace and '\')
  132. my $line_before2; # number of not essentially empty line before previous not essentially empty line
  133. my $contents; # contents of current line (without blinding)
  134. # $_ # current line, where comments etc. get blinded
  135. my $contents_before; # contents of $line_before (without blinding), if $line_before > 0
  136. my $contents_before_; # contents of $line_before after blinding comments etc., if $line_before > 0
  137. my $contents_before2; # contents of $line_before2 (without blinding), if $line_before2 > 0
  138. my $contents_before_2; # contents of $line_before2 after blinding comments etc., if $line_before2 > 0
  139. my $in_multiline_string; # line starts within multi-line string literal
  140. my $count; # -1 or number of leading whitespace characters (except newline) in current line,
  141. # which should be $block_indent + $hanging_offset + $local_offset or $expr_indent
  142. my $count_before; # number of leading whitespace characters (except line ending chars) in $contents_before
  143. my $has_label; # current line contains label
  144. my $local_offset; # current extra indent due to label, switch case/default, or leading closing brace(s)
  145. my $line_body_start; # number of line where last function body started, or 0
  146. my $line_function_start; # number of line where last function definition started, used if $line_body_start != 0
  147. my $last_function_header; # header containing name of last function defined, used if $line_function_start != 0
  148. my $line_opening_brace; # number of previous line with opening brace after do/while/for, optionally for if/else
  149. my $keyword_opening_brace; # name of previous keyword, used if $line_opening_brace != 0
  150. my $ifdef__cplusplus; # line before contained '#ifdef __cplusplus' (used in header files)
  151. my $block_indent; # currently required normal indentation at block/statement level
  152. my $hanging_offset; # extra indent, which may be nested, for just one hanging statement or expr or typedef
  153. my @in_do_hanging_offsets; # stack of hanging offsets for nested 'do' ... 'while'
  154. my @in_if_hanging_offsets; # stack of hanging offsets for nested 'if' (but not its potential 'else' branch)
  155. my $if_maybe_terminated; # 'if' ends and $hanging_offset should be reset unless the next line starts with 'else'
  156. my @nested_block_indents; # stack of indentations at block/statement level, needed due to hanging statements
  157. my @nested_hanging_offsets;# stack of nested $hanging_offset values, in parallel to @nested_block_indents
  158. my @nested_in_typedecl; # stack of nested $in_typedecl values, partly in parallel to @nested_block_indents
  159. my @nested_indents; # stack of hanging indents due to parentheses, braces, brackets, or conditionals
  160. my @nested_symbols; # stack of hanging symbols '(', '{', '[', or '?', in parallel to @nested_indents
  161. my @nested_conds_indents; # stack of hanging indents due to conditionals ('?' ... ':')
  162. my $expr_indent; # resulting hanging indent within (multi-line) expressions including type exprs, else 0
  163. my $hanging_symbol; # character ('(', '{', '[', not: '?') responsible for $expr_indent, if $expr_indent != 0
  164. my $in_expr; # in expression after if/while/for/switch/return/enum/LHS of assignment
  165. my $in_paren_expr; # in parenthesized if/while/for condition and switch expression, if $expr_indent != 0
  166. my $in_typedecl; # nesting level of typedef/struct/union/enum
  167. my $in_directive; # number of lines so far within preprocessor directive, e.g., macro definition
  168. my $directive_nesting; # currently required indentation of preprocessor directive according to #if(n)(def)
  169. my $directive_offset; # indent offset within multi-line preprocessor directive, if $in_directive > 0
  170. my $in_macro_header; # number of open parentheses + 1 in (multi-line) header of #define, if $in_directive > 0
  171. my $in_comment; # number of lines so far within multi-line comment, or < 0 when end is on current line
  172. my $leading_comment; # multi-line comment has no code before its beginning delimiter
  173. my $formatted_comment; # multi-line comment beginning with "/*-", which indicates/allows special formatting
  174. my $comment_indent; # comment indent, if $in_comment != 0
  175. my $num_reports_line = 0; # number of issues found on current line
  176. my $num_reports = 0; # total number of issues found
  177. my $num_indent_reports = 0;# total number of indentation issues found
  178. my $num_nesting_issues = 0;# total number of directive nesting issues found
  179. my $num_syntax_issues = 0; # total number of syntax issues found during sanity checks
  180. my $num_SPC_reports = 0; # total number of whitespace issues found
  181. my $num_length_reports = 0;# total number of line length issues found
  182. sub reset_file_state {
  183. $line = 0;
  184. $line_before = 0;
  185. $line_before2 = 0;
  186. @nested_block_indents = ();
  187. @nested_hanging_offsets = ();
  188. @nested_in_typedecl = ();
  189. @nested_symbols = ();
  190. @nested_indents = ();
  191. @nested_conds_indents = ();
  192. $expr_indent = 0;
  193. $in_paren_expr = 0;
  194. $in_expr = 0;
  195. $hanging_offset = 0;
  196. @in_do_hanging_offsets = ();
  197. @in_if_hanging_offsets = ();
  198. $if_maybe_terminated = 0;
  199. $block_indent = 0;
  200. $ifdef__cplusplus = 0;
  201. $in_multiline_string = 0;
  202. $line_body_start = 0;
  203. $line_opening_brace = 0;
  204. $in_typedecl = 0;
  205. $in_directive = 0;
  206. $directive_nesting = 0;
  207. $in_comment = 0;
  208. }
  209. # auxiliary submodules @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  210. sub report_flexibly {
  211. my $line = shift;
  212. my $msg = shift;
  213. my $contents = shift;
  214. my $report_SPC = $msg =~ /space/;
  215. return if $report_SPC && $sloppy_SPC;
  216. print "$ARGV:$line:$msg:$contents" unless $self_test;
  217. $num_reports_line++;
  218. $num_reports++;
  219. $num_indent_reports++ if $msg =~ m/indent/;
  220. $num_nesting_issues++ if $msg =~ m/directive nesting/;
  221. $num_syntax_issues++ if $msg =~ m/unclosed|unexpected/;
  222. $num_SPC_reports++ if $report_SPC;
  223. $num_length_reports++ if $msg =~ m/length/;
  224. }
  225. sub report {
  226. my $msg = shift;
  227. report_flexibly($line, $msg, $contents);
  228. }
  229. sub parens_balance { # count balance of opening parentheses - closing parentheses
  230. my $str = shift;
  231. return $str =~ tr/\(// - $str =~ tr/\)//;
  232. }
  233. sub blind_nonspace { # blind non-space text of comment as @, preserving length and spaces
  234. # the @ character is used because it cannot occur in normal program code so there is no confusion
  235. # comment text is not blinded to whitespace in order to be able to check extra SPC also in comments
  236. my $comment_text = shift;
  237. $comment_text =~ s/([\.\?\!])\s\s/$1. /g; # in extra SPC checks allow one extra SPC after period '.', '?', or '!' in comments
  238. return $comment_text =~ tr/ /@/cr;
  239. }
  240. # submodule for indentation checking/reporting @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  241. sub check_indent { # used for lines outside multi-line string literals
  242. my $stmt_indent = $block_indent + $hanging_offset + $local_offset;
  243. $stmt_indent = 0 if $stmt_indent < 0; # TODO maybe give warning/error
  244. my $stmt_desc = $contents =~
  245. m/^\s*\/\*/ ? "intra-line comment" :
  246. $has_label ? "label" :
  247. ($hanging_offset != 0 ? "hanging " : "").
  248. ($hanging_offset != 0 ? "stmt/expr" : "stmt/decl"); # $in_typedecl is not fully to the point here
  249. my ($ref_desc, $ref_indent) = $expr_indent == 0 ? ($stmt_desc, $stmt_indent)
  250. : ("hanging '$hanging_symbol'", $expr_indent);
  251. my ($alt_desc, $alt_indent) = ("", $ref_indent);
  252. # allow indent 1 for labels - this cannot happen for leading ':'
  253. ($alt_desc, $alt_indent) = ("outermost position", 1) if $expr_indent == 0 && $has_label;
  254. if (@nested_conds_indents != 0 && substr($_, $count, 1) eq ":") {
  255. # leading ':' within stmt/expr/decl - this cannot happen for labels, leading '&&', or leading '||'
  256. # allow special indent at level of corresponding "?"
  257. ($alt_desc, $alt_indent) = ("leading ':'", @nested_conds_indents[-1]);
  258. }
  259. # allow extra indent offset leading '&&' or '||' - this cannot happen for leading ":"
  260. ($alt_desc, $alt_indent) = ("leading '$1'", $ref_indent + INDENT_LEVEL) if $contents =~ m/^[\s@]*(\&\&|\|\|)/;
  261. if ($expr_indent < 0) { # implies @nested_symbols != 0 && @nested_symbols[0] eq "{" && @nested_indents[-1] < 0
  262. # allow normal stmt indentation level for hanging initializer/enum expressions after trailing '{'
  263. # this cannot happen for labels and overrides special treatment of ':', '&&' and '||' for this line
  264. ($alt_desc, $alt_indent) = ("lines after '{'", $stmt_indent);
  265. # decide depending on current actual indentation, preventing forth and back
  266. @nested_indents[-1] = $count == $stmt_indent ? $stmt_indent : -@nested_indents[-1]; # allow $stmt_indent
  267. $ref_indent = $expr_indent = @nested_indents[-1];
  268. }
  269. # check consistency of indentation within multi-line comment (i.e., between its first, inner, and last lines)
  270. if ($in_comment != 0 && $in_comment != 1) { # in multi-line comment but not on its first line
  271. if (!$sloppy_cmt) {
  272. if ($in_comment > 0) { # not at its end
  273. report("indent = $count != $comment_indent within multi-line comment")
  274. if $count != $comment_indent;
  275. } else {
  276. my $tweak = $in_comment == -2 ? 1 : 0;
  277. report("indent = ".($count + $tweak)." != $comment_indent at end of multi-line comment")
  278. if $count + $tweak != $comment_indent;
  279. }
  280. }
  281. # do not check indentation of last line of non-leading multi-line comment
  282. if ($in_comment < 0 && !$leading_comment) {
  283. s/^(\s*)@/$1*/; # blind first '@' as '*' to prevent below delayed check for the line before
  284. return;
  285. }
  286. return if $in_comment > 0; # not on its last line
  287. # $comment_indent will be checked by the below checks for end of multi-line comment
  288. }
  289. # else check indentation of entire-line comment or entire-line end of multi-line comment
  290. # ... w.r.t. indent of the following line by delayed check for the line before
  291. if (($in_comment == 0 || $in_comment == 1) # no comment, intra-line comment, or begin of multi-line comment
  292. && $line_before > 0 # there is a line before
  293. && $contents_before_ =~ m/^(\s*)@[\s@]*$/) { # line before begins with '@', no code follows (except '\')
  294. report_flexibly($line_before, "entire-line comment indent = $count_before != $count (of following line)",
  295. $contents_before) if !$sloppy_cmt && $count_before != $count;
  296. }
  297. # ... but allow normal indentation for the current line, else above check will be done for the line before
  298. if (($in_comment == 0 || $in_comment < 0) # (no commment,) intra-line comment or end of multi-line comment
  299. && m/^(\s*)@[\s@]*$/) { # line begins with '@', no code follows (except '\')
  300. if ($count == $ref_indent) { # indentation is like for (normal) code in this line
  301. s/^(\s*)@/$1*/; # blind first '@' as '*' to prevent above delayed check for the line before
  302. return;
  303. }
  304. return if !eof; # defer check of entire-line comment to next line
  305. }
  306. # else check indentation of leading intra-line comment or end of multi-line comment
  307. if (m/^(\s*)@/) { # line begins with '@', i.e., any (remaining type of) comment
  308. if (!$sloppy_cmt && $count != $ref_indent) {
  309. report("intra-line comment indent = $count != $ref_indent") if $in_comment == 0;
  310. report("multi-line comment indent = $count != $ref_indent") if $in_comment < 0;
  311. }
  312. return;
  313. }
  314. if ($sloppy_hang && ($hanging_offset != 0 || $expr_indent != 0)) {
  315. # do not report same indentation as on the line before (potentially due to same violations)
  316. return if $line_before > 0 && $count == $count_before;
  317. # do not report indentation at normal indentation level while hanging expression indent would be required
  318. return if $expr_indent != 0 && $count == $stmt_indent;
  319. # do not report if contents have been shifted left of nested expr indent (but not as far as stmt indent)
  320. # apparently aligned to the right in order to fit within line length limit
  321. return if $stmt_indent < $count && $count < $expr_indent &&
  322. length($contents) == MAX_LINE_LENGTH + length("\n");
  323. }
  324. report("indent = $count != $ref_indent for $ref_desc".
  325. ($alt_desc eq ""
  326. || $alt_indent == $ref_indent # prevent showing alternative that happens to have equal value
  327. ? "" : " or $alt_indent for $alt_desc"))
  328. if $count != $ref_indent && $count != $alt_indent;
  329. }
  330. # submodules handling indentation within expressions @@@@@@@@@@@@@@@@@@@@@@@@@@@
  331. sub update_nested_indents { # may reset $in_paren_expr and in this case also resets $in_expr
  332. my $str = shift;
  333. my $start = shift; # defaults to 0
  334. my $terminator_position = -1;
  335. for (my $i = $start; $i < length($str); $i++) {
  336. my $c;
  337. my $curr = substr($str, $i);
  338. if ($curr =~ m/^(.*?)([{}()?:;\[\]])(.*)$/) { # match from position $i the first {}()?:;[]
  339. $c = $2;
  340. } else {
  341. last;
  342. }
  343. my ($head, $tail) = (substr($str, 0, $i).$1, $3);
  344. $i += length($1) + length($2) - 1;
  345. # stop at terminator outside 'for(..;..;..)', assuming that 'for' is followed by '('
  346. return $i if $c eq ";" && (!$in_paren_expr || @nested_indents == 0);
  347. my $in_stmt = $in_expr || @nested_symbols != 0; # not: || $in_typedecl != 0
  348. if ($c =~ m/[{([?]/) { # $c is '{', '(', '[', or '?'
  349. if ($c eq "{") { # '{' in any context
  350. # cancel newly hanging_offset if opening brace '{' is after non-whitespace non-comment:
  351. $hanging_offset -= INDENT_LEVEL if $hanging_offset > 0 && $head =~ m/[^\s\@]/;
  352. push @nested_block_indents, $block_indent;
  353. push @nested_hanging_offsets, $in_expr ? $hanging_offset : 0;
  354. push @nested_in_typedecl, $in_typedecl if $in_typedecl != 0;
  355. $block_indent += INDENT_LEVEL + $hanging_offset;
  356. $hanging_offset = 0;
  357. }
  358. if ($c ne "{" || $in_stmt) { # for '{' inside stmt/expr (not: decl), for '(', '[', or '?' anywhere
  359. $tail =~ m/^([\s@]*)([^\s\@])/;
  360. push @nested_indents, defined $2
  361. ? $i + 1 + length($1) # actual indentation of following non-space non-comment
  362. : $c ne "{" ? +($i + 1) # just after '(' or '[' if only whitespace thereafter
  363. : -($i + 1); # allow also $stmt_indent if '{' with only whitespace thereafter
  364. push @nested_symbols, $c; # done also for '?' to be able to check correct nesting
  365. push @nested_conds_indents, $i if $c eq "?"; # remember special alternative indent for ':'
  366. }
  367. } elsif ($c =~ m/[})\]:]/) { # $c is '}', ')', ']', or ':'
  368. my $opening_c = ($c =~ tr/})]:/{([/r);
  369. if (($c ne ":" || $in_stmt # ignore ':' outside stmt/expr/decl
  370. # in the presence of ':', one could add this sanity check:
  371. # && !(# ':' after initial label/case/default
  372. # $head =~ m/^([\s@]*)(case\W.*$|\w+$)/ || # this matching would not work for
  373. # # multi-line expr after 'case'
  374. # # bitfield length within unsigned type decl
  375. # $tail =~ m/^[\s@]*\d+/ # this matching would need improvement
  376. # )
  377. )) {
  378. if ($c ne "}" || $in_stmt) { # for '}' inside stmt/expr/decl, ')', ']', or ':'
  379. if (@nested_symbols != 0 &&
  380. @nested_symbols[-1] == $opening_c) { # for $c there was a corresponding $opening_c
  381. pop @nested_indents;
  382. pop @nested_symbols;
  383. pop @nested_conds_indents if $opening_c eq "?";
  384. } else {
  385. report("unexpected '$c' @ ".($in_paren_expr ? "(expr)" : "expr"));
  386. next;
  387. }
  388. }
  389. if ($c eq "}") { # '}' at block level but also inside stmt/expr/decl
  390. if (@nested_block_indents == 0) {
  391. report("unexpected '}'");
  392. } else {
  393. $block_indent = pop @nested_block_indents;
  394. $hanging_offset = pop @nested_hanging_offsets;
  395. $in_typedecl = pop @nested_in_typedecl if @nested_in_typedecl != 0;
  396. }
  397. }
  398. if ($in_paren_expr && !grep(/\(/, @nested_symbols)) { # end of (expr)
  399. check_nested_nonblock_indents("(expr)");
  400. $in_paren_expr = $in_expr = 0;
  401. report("code after (expr)")
  402. if $tail =~ m/^([^{]*)/ && $1 =~ m/[^\s\@;]/; # non-space non-';' before any '{'
  403. }
  404. }
  405. }
  406. }
  407. return -1;
  408. }
  409. sub check_nested_nonblock_indents {
  410. my $position = shift;
  411. while (@nested_symbols != 0) {
  412. my $symbol = pop @nested_symbols;
  413. report("unclosed '$symbol' in $position");
  414. if ($symbol eq "{") { # repair stack of blocks
  415. $block_indent = pop @nested_block_indents;
  416. $hanging_offset = pop @nested_hanging_offsets;
  417. $in_typedecl = pop @nested_in_typedecl if @nested_in_typedecl != 0;
  418. }
  419. }
  420. @nested_indents = ();
  421. @nested_conds_indents = ();
  422. }
  423. # start of main program @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  424. reset_file_state();
  425. while (<>) { # loop over all lines of all input files
  426. $self_test = $ARGV =~ m/check-format-test/;
  427. $line++;
  428. s/\r$//; # strip any trailing CR '\r' (which are typical on Windows systems)
  429. $contents = $_;
  430. # check for illegal characters
  431. if (m/(.*?)([\x00-\x09\x0B-\x1F\x7F-\xFF])/) {
  432. my $col = length($1);
  433. report(($2 eq "\x09" ? "TAB" : $2 eq "\x0D" ? "CR " : $2 =~ m/[\x00-\x1F]/ ? "non-printable"
  434. : "non-7bit char") . " at column $col") ;
  435. }
  436. # check for whitespace at EOL
  437. report("trailing whitespace at EOL") if m/\s\n$/;
  438. # assign to $count the actual indentation level of the current line
  439. chomp; # remove trailing NL '\n'
  440. m/^(\s*)/;
  441. $count = length($1); # actual indentation
  442. $has_label = 0;
  443. $local_offset = 0;
  444. # character/string literals @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  445. s/\\["']/@@/g; # blind all '"' and "'" escaped by '\' (typically within character literals or string literals)
  446. # handle multi-line string literals to avoid confusion on starting/ending '"' and trailing '\'
  447. if ($in_multiline_string) {
  448. if (s#^([^"]*)"#($1 =~ tr/"/@/cr).'@'#e) { # string literal terminated by '"'
  449. # string contents and its terminating '"' have been blinded as '@'
  450. $count = -1; # do not check indentation
  451. } else {
  452. report("multi-line string literal not terminated by '\"' and trailing '\' is missing")
  453. unless s#^([^\\]*)\s*\\\s*$#$1#; # strip trailing '\' plus any whitespace around
  454. goto LINE_FINISHED;
  455. }
  456. }
  457. # blind contents of character and string literals as @, preserving length (but not spaces)
  458. # this prevents confusing any of the matching below, e.g., of whitespace and comment delimiters
  459. s#('[^']*')#$1 =~ tr/'/@/cr#eg; # handle all intra-line character literals
  460. s#("[^"]*")#$1 =~ tr/"/@/cr#eg; # handle all intra-line string literals
  461. $in_multiline_string = # handle trailing string literal terminated by '\'
  462. s#^(([^"]*"[^"]*")*[^"]*)("[^"]*)\\(\s*)$#$1.($3 =~ tr/"/@/cr).'"'.$4#e;
  463. # its contents have been blinded and the trailing '\' replaced by '"'
  464. # strip any other trailing '\' along with any whitespace around it such that it does not interfere with various
  465. # matching below; the later handling of multi-line macro definitions uses $contents where it is not stripped
  466. s#^(.*?)\s*\\\s*$#$1#; # trailing '\' possibly preceded and/or followed by whitespace
  467. # comments @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  468. # do/prepare checks within multi-line comments
  469. my $self_test_exception = $self_test ? "@" : "";
  470. if ($in_comment > 0) { # this still includes the last line of multi-line commment
  471. my ($head, $any_symbol, $cmt_text) = m/^(\s*)(.?)(.*)$/;
  472. if ($any_symbol eq "*") {
  473. report("no space after leading '*' in multi-line comment") if $cmt_text =~ m|^[^/\s$self_test_exception]|;
  474. } else {
  475. report("no leading '*' in multi-line comment");
  476. }
  477. $in_comment++;
  478. }
  479. # detect end of comment, must be within multi-line comment, check if it is preceded by non-whitespace text
  480. if ((my ($head, $tail) = m|^(.*?)\*/(.*)$|) && $1 ne '/') { # ending comment: '*/'
  481. report("neither space nor '*' before '*/'") if $head =~ m/[^*\s]$/;
  482. report("no space after '*/'") if $tail =~ m/^[^\s,;)}\]]/; # no space or ,;)}] after '*/'
  483. if (!($head =~ m|/\*|)) { # not begin of comment '/*', which is is handled below
  484. if ($in_comment == 0) {
  485. report("unexpected '*/' outside comment");
  486. $_ = "$head@@".$tail; # blind the "*/"
  487. } else {
  488. report("text before '*/' in multi-line comment") if ($head =~ m/\S/); # non-SPC before '*/'
  489. $in_comment = -1; # indicate that multi-line comment ends on current line
  490. if ($count > 0) {
  491. # make indentation of end of multi-line comment appear like of leading intra-line comment
  492. $head =~ s/^(\s*)\s/$1@/; # replace the last leading space by '@'
  493. $count--;
  494. $in_comment = -2; # indicate that multi-line comment ends on current line, with tweak
  495. }
  496. my $cmt_text = $head;
  497. $_ = blind_nonspace($cmt_text)."@@".$tail;
  498. }
  499. }
  500. }
  501. # detect begin of comment, check if it is followed by non-space text
  502. MATCH_COMMENT:
  503. if (my ($head, $opt_minus, $tail) = m|^(.*?)/\*(-?)(.*)$|) { # begin of comment: '/*'
  504. report("no space before '/*'")
  505. if $head =~ m/[^\s(\*]$/; # not space, '(', or or '*' (needed to allow '*/') before comment delimiter
  506. report("neither space nor '*' after '/*' or '/*-'") if $tail =~ m/^[^\s*$self_test_exception]/;
  507. my $cmt_text = $opt_minus.$tail; # preliminary
  508. if ($in_comment > 0) {
  509. report("unexpected '/*' inside multi-line comment");
  510. } elsif ($tail =~ m|^(.*?)\*/(.*)$|) { # comment end: */ on same line
  511. report("unexpected '/*' inside intra-line comment") if $1 =~ /\/\*/;
  512. # blind comment text, preserving length and spaces
  513. ($cmt_text, my $rest) = ($opt_minus.$1, $2);
  514. $_ = "$head@@".blind_nonspace($cmt_text)."@@".$rest;
  515. goto MATCH_COMMENT;
  516. } else { # begin of multi-line comment
  517. my $self_test_exception = $self_test ? "(@\d?)?" : "";
  518. report("text after '/*' in multi-line comment")
  519. unless $tail =~ m/^$self_test_exception.?\s*$/;
  520. # tail not essentially empty, first char already checked
  521. # adapt to actual indentation of first line
  522. $comment_indent = length($head) + 1;
  523. $_ = "$head@@".blind_nonspace($cmt_text);
  524. $in_comment = 1;
  525. $leading_comment = $head =~ m/^\s*$/; # there is code before beginning delimiter
  526. $formatted_comment = $opt_minus eq "-";
  527. }
  528. }
  529. if ($in_comment > 1) { # still inside multi-line comment (not at its begin or end)
  530. m/^(\s*)\*?(\s*)(.*)$/;
  531. $_ = $1."@".$2.blind_nonspace($3);
  532. }
  533. # handle special case of line after '#ifdef __cplusplus' (which typically appears in header files)
  534. if ($ifdef__cplusplus) {
  535. $ifdef__cplusplus = 0;
  536. $_ = "$1 $2" if $contents =~ m/^(\s*extern\s*"C"\s*)\{(\s*)$/; # ignore opening brace in 'extern "C" {'
  537. goto LINE_FINISHED if m/^\s*\}\s*$/; # ignore closing brace '}'
  538. }
  539. # check for over-long lines,
  540. # while allowing trailing (also multi-line) string literals to go past $max_length
  541. my $len = length; # total line length (without trailing '\n')
  542. if ($len > $max_length &&
  543. !(m/^(.*)"[^"]*"\s*[\)\}\]]*[,;]?\s*$/ # string literal terminated by '"' (or '\'), then maybe )}],;
  544. && length($1) < $max_length)
  545. # this allows over-long trailing string literals with beginning col before $max_length
  546. ) {
  547. report("line length = $len > ".MAX_LINE_LENGTH);
  548. }
  549. # handle C++ / C99 - style end-of-line comments
  550. if (my ($head, $cmt_text) = m|^(.*?)//(.*$)|) {
  551. report("'//' end-of-line comment"); # the '//' comment style is not allowed for C90
  552. # blind comment text, preserving length and spaces
  553. $_ = "$head@@".blind_nonspace($cmt_text);
  554. }
  555. # at this point all non-space portions of any types of comments have been blinded as @
  556. goto LINE_FINISHED if m/^\s*$/; # essentially empty line: just whitespace (and maybe a trailing '\')
  557. # intra-line whitespace nits @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  558. my $in_multiline_comment = ($in_comment > 1 || $in_comment < 0); # $in_multiline_comment refers to line before
  559. if (!$sloppy_SPC && !($in_multiline_comment && $formatted_comment)) {
  560. sub extra_SPC {
  561. my $intra_line = shift;
  562. return "extra space".($intra_line =~ m/@\s\s/ ?
  563. $in_comment != 0 ? " in multi-line comment"
  564. : " in intra-line comment" : "");
  565. }
  566. sub split_line_head { # split line contents into header containing leading spaces and the first non-space char, and the rest of the line
  567. my $comment_symbol =
  568. $in_comment != 0 ? "@" : ""; # '@' will match the blinded leading '*' in multi-line comment
  569. # $in_comment may pertain to the following line due to delayed check
  570. # do not check for extra SPC in leading spaces including any '#' (or '*' within multi-line comment)
  571. shift =~ m/^(\s*([#$comment_symbol]\s*)?)(.*?)\s*$/;
  572. return ($1, $3);
  573. }
  574. my ($head , $intra_line ) = split_line_head($_);
  575. my ($head1, $intra_line1) = split_line_head($contents_before_ ) if $line_before > 0;
  576. my ($head2, $intra_line2) = split_line_head($contents_before_2) if $line_before2 > 0;
  577. if ($line_before > 0) { # check with one line delay, such that at least $contents_before is available
  578. sub column_alignments_only { # return 1 if the given line has multiple consecutive spaces only at columns that match the reference line
  579. # all parameter strings are assumed to contain contents after blinding comments etc.
  580. my $head = shift; # leading spaces and the first non-space char
  581. my $intra = shift; # the rest of the line contents
  582. my $contents = shift; # reference line
  583. # check if all extra SPC in $intra is used only for multi-line column alignment with $contents
  584. my $offset = length($head);
  585. for (my $col = 0; $col < length($intra) - 2; $col++) {
  586. my $substr = substr($intra, $col);
  587. next unless $substr =~ m/^\s\s\S/; # extra SPC (but not in leading spaces of the line)
  588. next if !$eol_cmt && $substr =~ m/^[@\s]+$/; # end-of-line comment
  589. return 0 unless substr($contents, $col + $offset + 1, 2) =~ m/\s\S/; # reference line contents do not match
  590. }
  591. return 1;
  592. }
  593. report_flexibly($line_before, extra_SPC($intra_line1), $contents_before) if $intra_line1 =~ m/\s\s\S/ &&
  594. !( column_alignments_only($head1, $intra_line1, $_ ) # compare with $line
  595. || ($line_before2 > 0 &&
  596. column_alignments_only($head1, $intra_line1, $contents_before_2))); # compare w/ $line_before2
  597. report(extra_SPC($intra_line)) if $intra_line =~ m/\s\s\S/ && eof
  598. && ! column_alignments_only($head , $intra_line , $contents_before_ ) ; # compare w/ $line_before
  599. } elsif (eof) { # special case: just one line exists
  600. report(extra_SPC($intra_line)) if $intra_line =~ m/\s\s\S/;
  601. }
  602. # ignore paths in #include
  603. $intra_line =~ s/^(include\s*)(".*?"|<.*?>)/$1/e if $head =~ m/#/;
  604. # treat op= and comparison operators as simple '=', simplifying matching below
  605. $intra_line =~ s/([\+\-\*\/\/%\&\|\^\!<>=]|<<|>>)=/=/g;
  606. # treat (type) variables within macro, indicated by trailing '\', as 'int' simplifying matching below
  607. $intra_line =~ s/[A-Z_]+/int/g if $contents =~ m/^(.*?)\s*\\\s*$/;
  608. # treat double &&, ||, <<, and >> as single ones, simplifying matching below
  609. $intra_line =~ s/(&&|\|\||<<|>>)/substr($1, 0, 1)/eg;
  610. # remove blinded comments etc. directly after [{(
  611. while ($intra_line =~ s/([\[\{\(])@+\s?/$1/e) {} # /g does not work here
  612. # remove blinded comments etc. directly before ,;)}]
  613. while ($intra_line =~ s/\s?@+([,;\)\}\]])/$1/e) {} # /g does not work here
  614. # treat remaining blinded comments and string literal contents as (single) space during matching below
  615. $intra_line =~ s/@+/ /g; # note that extra SPC has already been handled above
  616. $intra_line =~ s/\s+$//; # strip any (resulting) space at EOL
  617. $intra_line =~ s/(for\s*\([^;]*);;(\))/"$1$2"/eg; # strip trailing ';;' in for (;;)
  618. $intra_line =~ s/(for\s*\([^;]+;[^;]+);(\))/"$1$2"/eg; # strip trailing ';' in for (;;)
  619. $intra_line =~ s/(=\s*)\{ /"$1@ "/eg; # do not report {SPC in initializers such as ' = { 0, };'
  620. $intra_line =~ s/, \};/, @;/g; # do not report SPC} in initializers such as ' = { 0, };'
  621. report("space before '$1'") if $intra_line =~ m/[\w)\]]\s+(\+\+|--)/; # postfix ++/-- with preceding space
  622. report("space after '$1'") if $intra_line =~ m/(\+\+|--)\s+[a-zA-Z_(]/; # prefix ++/-- with following space
  623. $intra_line =~ s/\.\.\./@/g; # blind '...'
  624. report("space before '$1'") if $intra_line =~ m/\s(\.|->)/; # '.' or '->' with preceding space
  625. report("space after '$1'") if $intra_line =~ m/(\.|->)\s/; # '.' or '->' with following space
  626. $intra_line =~ s/\-\>|\+\+|\-\-/@/g; # blind '->,', '++', and '--'
  627. report("space before '$2'") if $intra_line =~ m/[^:]\s+(;)/; # space before ';' but not after ':'
  628. report("space before '$1'") if $intra_line =~ m/\s([,)\]])/; # space before ,)]
  629. report("space after '$1'") if $intra_line =~ m/([(\[~!])\s/; # space after ([~!
  630. report("space after '$1'") if $intra_line =~ m/(defined)\s/; # space after 'defined'
  631. report("no space before '=' or '<op>='") if $intra_line =~ m/\S(=)/; # '=' etc. without preceding space
  632. report("no space before '$1'") if $intra_line =~ m/\S([|\/%<>^\?])/; # |/%<>^? without preceding space
  633. # TODO ternary ':' without preceding SPC, while allowing no SPC before ':' after 'case'
  634. report("no space before binary '$1'") if $intra_line =~ m/[^\s{()\[]([+\-])/;# +/- without preceding space or {()[
  635. # or ')' (which is used f type casts)
  636. report("no space before binary '$1'") if $intra_line =~ m/[^\s{()\[*!]([*])/; # '*' without preceding space or {()[*!
  637. report("no space before binary '$1'") if $intra_line =~ m/[^\s{()\[]([&])/; # '&' without preceding space or {()[
  638. report("no space after ternary '$1'") if $intra_line =~ m/(:)[^\s\d]/; # ':' without following space or digit
  639. report("no space after '$1'") if $intra_line =~ m/([,;=|\/%<>^\?])\S/; # ,;=|/%<>^? without following space
  640. report("no space after binary '$1'") if $intra_line=~m/[^{(\[]([*])[^\sa-zA-Z_(),*]/;# '*' w/o space or \w(),* after
  641. # TODO unary '*' must not be followed by SPC
  642. report("no space after binary '$1'") if $intra_line=~m/([&])[^\sa-zA-Z_(]/; # '&' w/o following space or \w(
  643. # TODO unary '&' must not be followed by SPC
  644. report("no space after binary '$1'") if $intra_line=~m/[^{(\[]([+\-])[^\s\d(]/; # +/- w/o following space or \d(
  645. # TODO unary '+' and '-' must not be followed by SPC
  646. report("no space after '$2'") if $intra_line =~ m/(^|\W)(if|while|for|switch|case)[^\w\s]/; # kw w/o SPC
  647. report("no space after '$2'") if $intra_line =~ m/(^|\W)(return)[^\w\s;]/; # return w/o SPC or ';'
  648. report("space after function/macro name")
  649. if $intra_line =~ m/(\w+)\s+\(/ # fn/macro name with space before '('
  650. && !($1 =~ m/^(if|while|for|switch|return|typedef|void|char|unsigned|int|long|float|double)$/) # not keyword
  651. && !(m/^\s*#\s*define\s/); # we skip macro definitions here because macros
  652. # without parameters but with body beginning with '(', e.g., '#define X (1)',
  653. # would lead to false positives - TODO also check for macros with parameters
  654. report("no space before '{'") if $intra_line =~ m/[^\s{(\[]\{/; # '{' without preceding space or {([
  655. report("no space after '}'") if $intra_line =~ m/\}[^\s,;\])}]/; # '}' without following space or ,;])}
  656. }
  657. # preprocessor directives @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  658. # handle preprocessor directives
  659. if (m/^\s*#(\s*)(\w+)/) { # line beginning with '#'
  660. my $space_count = length($1); # maybe could also use indentation before '#'
  661. my $directive = $2;
  662. report("indent = $count != 0 for '#'") if $count != 0;
  663. $directive_nesting-- if $directive =~ m/^(else|elif|endif)$/;
  664. if ($directive_nesting < 0) {
  665. $directive_nesting = 0;
  666. report("unexpected '#$directive'");
  667. }
  668. report("'#' directive nesting = $space_count != $directive_nesting") if $space_count != $directive_nesting;
  669. $directive_nesting++ if $directive =~ m/^if|ifdef|ifndef|else|elif$/;
  670. $ifdef__cplusplus = m/^\s*#\s*ifdef\s+__cplusplus\s*$/;
  671. goto POSTPROCESS_DIRECTIVE unless $directive =~ m/^define$/; # skip normal code handling except for #define
  672. # TODO improve handling of indents of preprocessor directives ('\', $in_directive != 0) vs. normal C code
  673. $count = -1; # do not check indentation of #define
  674. }
  675. # adapt required indentation @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  676. s/(\w*ASN1_[A-Z_]+END\w*([^(]|\(.*?\)|$))/$1;/g; # treat *ASN1_*END*(..) macro calls as if followed by ';'
  677. my $nested_indents_position = 0;
  678. # update indents according to leading closing brace(s) '}' or label or switch case
  679. my $in_stmt = $in_expr || @nested_symbols != 0 || $in_typedecl != 0;
  680. if ($in_stmt) { # expr/stmt/type decl/var def/fn hdr, i.e., not at block level
  681. if (m/^([\s@]*\})/) { # leading '}', any preceding blinded comment must not be matched
  682. my $head = $1;
  683. update_nested_indents($head);
  684. $nested_indents_position = length($head);
  685. if (@nested_symbols >= 1) {
  686. $hanging_symbol = @nested_symbols[-1];
  687. $expr_indent = @nested_indents[-1];
  688. } else { # typically end of initialiizer expr or enum
  689. $expr_indent = 0;
  690. }
  691. } elsif (m/^([\s@]*)(static_)?ASN1_ITEM_TEMPLATE_END(\W|$)/) { # workaround for ASN1 macro indented as '}'
  692. $local_offset = -INDENT_LEVEL;
  693. $expr_indent = 0;
  694. } elsif (m/;.*?\}/) { # expr ends with ';' before '}'
  695. report("code before '}'");
  696. }
  697. }
  698. if (@in_do_hanging_offsets != 0 && # note there is nothing like "unexpected 'while'"
  699. m/^[\s@]*while(\W|$)/) { # leading 'while'
  700. $hanging_offset = pop @in_do_hanging_offsets;
  701. }
  702. if ($if_maybe_terminated) {
  703. if (m/(^|\W)else(\W|$)/) { # (not necessarily leading) 'else'
  704. if (@in_if_hanging_offsets == 0) {
  705. report("unexpected 'else'");
  706. } else {
  707. $hanging_offset = pop @in_if_hanging_offsets;
  708. }
  709. } else {
  710. @in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'"
  711. $hanging_offset = 0;
  712. }
  713. }
  714. if (!$in_stmt) { # at block level, i.e., outside expr/stmt/type decl/var def/fn hdr
  715. $if_maybe_terminated = 0;
  716. if (my ($head, $before, $tail) = m/^([\s@]*([^{}]*)\})[\s@]*(.*)$/) { # leading closing '}', but possibly
  717. # with non-whitespace non-'{' before
  718. report("code after '}'") unless $tail eq "" || $tail =~ m/(else|while|OSSL_TRACE_END)(\W|$)/;
  719. my $outermost_level = @nested_block_indents == 1 && @nested_block_indents[0] == 0;
  720. if (!$sloppy_bodylen && $outermost_level && $line_body_start != 0) {
  721. my $body_len = $line - $line_body_start - 1;
  722. report_flexibly($line_function_start, "function body length = $body_len > ".MAX_BODY_LENGTH." lines",
  723. $last_function_header) if $body_len > MAX_BODY_LENGTH;
  724. $line_body_start = 0;
  725. }
  726. if ($before ne "") { # non-whitespace non-'{' before '}'
  727. report("code before '}'");
  728. } else { # leading '}', any preceding blinded comment must not be matched
  729. $local_offset = $block_indent + $hanging_offset - INDENT_LEVEL;
  730. update_nested_indents($head);
  731. $nested_indents_position = length($head);
  732. $local_offset -= ($block_indent + $hanging_offset);
  733. # in effect $local_offset = -INDENT_LEVEL relative to $block_indent + $hanging_offset values before
  734. }
  735. }
  736. # handle opening brace '{' after if/else/while/for/switch/do on line before
  737. if ($hanging_offset > 0 && m/^[\s@]*{/ && # leading opening '{'
  738. $line_before > 0 &&
  739. $contents_before_ =~ m/(^|^.*\W)(if|else|while|for|switch|do)(\W.*$|$)/) {
  740. $keyword_opening_brace = $1;
  741. $hanging_offset -= INDENT_LEVEL; # cancel newly hanging_offset
  742. }
  743. if (m/^[\s@]*(case|default)(\W.*$|$)/) { # leading 'case' or 'default'
  744. my $keyword = $1;
  745. report("code after $keyword: ") if $2 =~ /:.*[^\s@].*$/;
  746. $local_offset = -INDENT_LEVEL;
  747. } else {
  748. if (m/^([\s@]*)(\w+):/) { # (leading) label, cannot be "default"
  749. $local_offset = -INDENT_LEVEL;
  750. $has_label = 1;
  751. }
  752. }
  753. }
  754. # potential adaptations of indent in first line of macro body in multi-line macro definition
  755. if ($in_directive > 0 && $in_macro_header > 0) {
  756. if ($in_macro_header > 1) { # still in macro definition header
  757. $in_macro_header += parens_balance($_);
  758. } else { # begin of macro body
  759. $in_macro_header = 0;
  760. if ($count == $block_indent - $directive_offset # body began with same indentation as preceding code
  761. && $sloppy_macro) { # workaround for this situation is enabled
  762. $block_indent -= $directive_offset;
  763. $directive_offset = 0;
  764. }
  765. }
  766. }
  767. # check required indentation @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  768. check_indent() if $count >= 0; # not for #define and not if multi-line string literal is continued
  769. $in_comment = 0 if $in_comment < 0; # multi-line comment has ended
  770. # do some further checks @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  771. my $outermost_level = $block_indent == 0 + ($in_directive > 0 ? $directive_offset : 0);
  772. report("more than one stmt") if !m/(^|\W)for(\W.*|$)/ && # no 'for' - TODO improve matching
  773. m/;.*;/; # two or more terminators ';', so more than one statement
  774. # check for code block containing a single line/statement
  775. if ($line_before2 > 0 && !$outermost_level && # within function body
  776. $in_typedecl == 0 && @nested_indents == 0 && # neither within type declaration nor inside stmt/expr
  777. m/^[\s@]*\}/) { # leading closing brace '}', any preceding blinded comment must not be matched
  778. # TODO extend detection from single-line to potentially multi-line statement
  779. if ($line_opening_brace > 0 &&
  780. ($line_opening_brace == $line_before2 ||
  781. $line_opening_brace == $line_before)
  782. && $contents_before =~ m/;/) { # there is at least one terminator ';', so there is some stmt
  783. # TODO do not report cases where a further else branch
  784. # follows with a block containg more than one line/statement
  785. report_flexibly($line_before, "'$keyword_opening_brace' { 1 stmt }", $contents_before);
  786. }
  787. }
  788. report("single-letter name '$2'") if (m/(^|.*\W)([IO])(\W.*|$)/); # single-letter name 'I' or 'O' # maybe re-add 'l'?
  789. # constant on LHS of comparison or assignment, e.g., NULL != x or 'a' < c, but not a + 1 == b
  790. report("constant on LHS of '$2'")
  791. if (m/(['"]|([\+\-\*\/\/%\&\|\^<>]\s*)?\W[0-9]+L?|NULL)\s*([\!<>=]=|[<=>][^<>])/ && $2 eq "");
  792. # TODO report #if 0 and #if 1
  793. # TODO report empty line within local variable definitions
  794. # TODO report missing empty line after local variable definitions
  795. # TODO report needless use of parentheses, while
  796. # macro parameters should always be in parens (except when passed on), e.g., '#define ID(x) (x)'
  797. # adapt required indentation for following lines @@@@@@@@@@@@@@@@@@@@@@@@@@@
  798. # set $in_expr, $in_paren_expr, and $hanging_offset for if/while/for/switch, return/enum, and assignment RHS
  799. my $paren_expr_start = 0;
  800. my $return_enum_start = 0;
  801. my $assignment_start = 0;
  802. my $tmp = $_;
  803. $tmp =~ s/[\!<>=]=/@@/g; # blind (in-)equality symbols like '<=' as '@@' to prevent matching them as '=' below
  804. if (m/^((^|.*\W)(if|while|for|switch))(\W.*|$)$/) { # (last) if/for/while/switch
  805. $paren_expr_start = 1;
  806. } elsif (m/^((^|.*\W)(return|enum))(\W.*|$)/ # (last) return/enum
  807. && !$in_expr && @nested_indents == 0 && parens_balance($1) == 0) { # not nested enum
  808. $return_enum_start = 1;
  809. } elsif ($tmp =~ m/^(([^=]*)(=))(.*)$/ # (last) '=', i.e., assignment
  810. && !$in_expr && @nested_indents == 0 && parens_balance($1) == 0) { # not nested assignment
  811. $assignment_start = 1;
  812. }
  813. if ($paren_expr_start || $return_enum_start || $assignment_start)
  814. {
  815. my ($head, $mid, $tail) = ($1, $3, $4);
  816. $keyword_opening_brace = $mid if $mid ne "=";
  817. # to cope with multi-line expressions, do this also if !($tail =~ m/\{/)
  818. push @in_if_hanging_offsets, $hanging_offset if $mid eq "if";
  819. # already handle $head, i.e., anything before expression
  820. update_nested_indents($head, $nested_indents_position);
  821. $nested_indents_position = length($head);
  822. # now can set $in_expr and $in_paren_expr
  823. $in_expr = 1;
  824. $in_paren_expr = 1 if $paren_expr_start;
  825. if ($mid eq "while" && @in_do_hanging_offsets != 0) {
  826. $hanging_offset = pop @in_do_hanging_offsets;
  827. } else {
  828. $hanging_offset += INDENT_LEVEL; # tentatively set hanging_offset, may be canceled by following '{'
  829. }
  830. }
  831. # set $hanging_offset and $keyword_opening_brace for do/else
  832. if (my ($head, $mid, $tail) = m/(^|^.*\W)(else|do)(\W.*|$)$/) { # last else/do, where 'do' is preferred
  833. my $code_before = $head =~ m/[^\s\@}]/; # leading non-whitespace non-comment non-'}'
  834. report("code before '$mid'") if $code_before;
  835. report("code after '$mid'" ) if $tail =~ m/[^\s\@{]/# trailing non-whitespace non-comment non-'{' (non-'\')
  836. && !($mid eq "else" && $tail =~ m/[\s@]*if(\W|$)/);
  837. if ($mid eq "do") { # workarounds for code before 'do'
  838. if ($head =~ m/(^|^.*\W)(else)(\W.*$|$)/) { # 'else' ... 'do'
  839. $hanging_offset += INDENT_LEVEL; # tentatively set hanging_offset, may be canceled by following '{'
  840. }
  841. if ($head =~ m/;/) { # terminator ';' ... 'do'
  842. @in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'"
  843. $hanging_offset = 0;
  844. }
  845. }
  846. push @in_do_hanging_offsets, $hanging_offset if $mid eq "do";
  847. if ($code_before && $mid eq "do") {
  848. $hanging_offset = length($head) - $block_indent;
  849. }
  850. if (!$in_paren_expr) {
  851. $keyword_opening_brace = $mid if $tail =~ m/\{/;
  852. $hanging_offset += INDENT_LEVEL;
  853. }
  854. }
  855. # set $in_typedecl and potentially $hanging_offset for type declaration
  856. if (!$in_expr && @nested_indents == 0 # not in expression
  857. && m/(^|^.*\W)(typedef|struct|union|enum)(\W.*|$)$/
  858. && parens_balance($1) == 0 # not in newly started expression or function arg list
  859. && ($2 eq "typedef" || !($3 =~ m/\s*\w++\s*(.)/ && $1 ne "{")) # 'struct'/'union'/'enum' <name> not followed by '{'
  860. # not needed: && $keyword_opening_brace = $2 if $3 =~ m/\{/;
  861. ) {
  862. $in_typedecl++;
  863. $hanging_offset += INDENT_LEVEL if m/\*.*\(/; # '*' followed by '(' - seems consistent with Emacs C mode
  864. }
  865. my $bak_in_expr = $in_expr;
  866. my $terminator_position = update_nested_indents($_, $nested_indents_position);
  867. if ($bak_in_expr) {
  868. # on end of non-if/while/for/switch (multi-line) expression (i.e., return/enum/assignment) and
  869. # on end of statement/type declaration/variable definition/function header
  870. if ($terminator_position >= 0 && ($in_typedecl == 0 || @nested_indents == 0)) {
  871. check_nested_nonblock_indents("expr");
  872. $in_expr = 0;
  873. }
  874. } else {
  875. check_nested_nonblock_indents($in_typedecl == 0 ? "stmt" : "decl") if $terminator_position >= 0;
  876. }
  877. # on ';', which terminates the current statement/type declaration/variable definition/function declaration
  878. if ($terminator_position >= 0) {
  879. my $tail = substr($_, $terminator_position + 1);
  880. if (@in_if_hanging_offsets != 0) {
  881. if ($tail =~ m/\s*else(\W|$)/) {
  882. pop @in_if_hanging_offsets;
  883. $hanging_offset -= INDENT_LEVEL;
  884. } elsif ($tail =~ m/[^\s@]/) { # code (not just comment) follows
  885. @in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'"
  886. $hanging_offset = 0;
  887. } else {
  888. $if_maybe_terminated = 1;
  889. }
  890. } elsif ($tail =~ m/^[\s@]*$/) { # ';' has been trailing, i.e. there is nothing but whitespace and comments
  891. $hanging_offset = 0; # reset in case of terminated assignment ('=') etc.
  892. }
  893. $in_typedecl-- if $in_typedecl != 0 && @nested_in_typedecl == 0; # TODO handle multiple type decls per line
  894. m/(;[^;]*)$/; # match last ';'
  895. $terminator_position = length($_) - length($1) if $1;
  896. # new $terminator_position value may be after the earlier one in case multiple terminators on current line
  897. # TODO check treatment in case of multiple terminators on current line
  898. update_nested_indents($_, $terminator_position + 1);
  899. }
  900. # set hanging expression indent according to nested indents - TODO maybe do better in update_nested_indents()
  901. # also if $in_expr is 0: in statement/type declaration/variable definition/function header
  902. $expr_indent = 0;
  903. for (my $i = -1; $i >= -@nested_symbols; $i--) {
  904. if (@nested_symbols[$i] ne "?") { # conditionals '?' ... ':' are treated specially in check_indent()
  905. $hanging_symbol = @nested_symbols[$i];
  906. $expr_indent = $nested_indents[$i];
  907. # $expr_indent is guaranteed to be != 0 unless @nested_indents contains just outer conditionals
  908. last;
  909. }
  910. }
  911. # remember line number and header containing name of last function defined for reports w.r.t. MAX_BODY_LENGTH
  912. if ($outermost_level && m/(\w+)\s*\(/ && $1 ne "STACK_OF") {
  913. $line_function_start = $line;
  914. $last_function_header = $contents;
  915. }
  916. # special checks for last, typically trailing opening brace '{' in line
  917. if (my ($head, $tail) = m/^(.*)\{(.*)$/) { # match last ... '{'
  918. if ($in_directive == 0 && !$in_expr && $in_typedecl == 0) {
  919. if ($outermost_level) {
  920. if (!$assignment_start && !$bak_in_expr) {
  921. # at end of function definition header (or stmt or var definition)
  922. report("'{' not at beginning") if $head ne "";
  923. $line_body_start = $contents =~ m/LONG BODY/ ? 0 : $line;
  924. }
  925. } else {
  926. $line_opening_brace = $line if $keyword_opening_brace =~ m/do|while|for/;
  927. # using, not assigning, $keyword_opening_brace here because it could be on an earlier line
  928. $line_opening_brace = $line if $keyword_opening_brace =~ m/if|else/ && $extended_1_stmt &&
  929. # TODO prevent false positives for if/else where braces around single-statement branches
  930. # should be avoided but only if all branches have just single statements
  931. # The following helps detecting the exception when handling multiple 'if ... else' branches:
  932. !($keyword_opening_brace eq "else" && $line_opening_brace < $line_before2);
  933. }
  934. report("code after '{'") if $tail=~ m/[^\s\@]/ && # trailing non-whitespace non-comment (non-'\')
  935. !($tail=~ m/\}/); # no '}' after last '{'
  936. }
  937. }
  938. # check for opening brace after if/while/for/switch/do not on same line
  939. # note that "no '{' on same line after '} else'" is handled further below
  940. if (/^[\s@]*{/ && # leading '{'
  941. $line_before > 0 && !($contents_before_ =~ m/^\s*#/) && # not preprocessor directive '#if
  942. (my ($head, $mid, $tail) = ($contents_before_ =~ m/(^|^.*\W)(if|while|for|switch|do)(\W.*$|$)/))) {
  943. my $brace_after = $tail =~ /^[\s@]*{/; # any whitespace or comments then '{'
  944. report("'{' not on same line as preceding '$mid'") if !$brace_after;
  945. }
  946. # check for closing brace on line before 'else' not followed by leading '{'
  947. elsif (my ($head, $tail) = m/(^|^.*\W)else(\W.*$|$)/) {
  948. if (parens_balance($tail) == 0 && # avoid false positive due to unfinished expr on current line
  949. !($tail =~ m/{/) && # after 'else' no '{' on same line
  950. !($head =~ m/}[\s@]*$/) && # not: '}' then any whitespace or comments before 'else'
  951. $line_before > 0 && $contents_before_ =~ /}[\s@]*$/) { # trailing '}' on line before
  952. report("no '{' after '} else'");
  953. }
  954. }
  955. # check for closing brace before 'while' not on same line
  956. if (my ($head, $tail) = m/(^|^.*\W)while(\W.*$|$)/) {
  957. my $brace_before = $head =~ m/}[\s@]*$/; # '}' then any whitespace or comments
  958. # possibly 'if (...)' (with potentially inner '(' and ')') then any whitespace or comments then '{'
  959. if (!$brace_before &&
  960. # does not work here: @in_do_hanging_offsets != 0 && #'while' terminates loop
  961. parens_balance($tail) == 0 && # avoid false positive due to unfinished expr on current line
  962. $tail =~ /;/ && # 'while' terminates loop (by ';')
  963. $line_before > 0 &&
  964. $contents_before_ =~ /}[\s@]*$/) { # on line before: '}' then any whitespace or comments
  965. report("'while' not on same line as preceding '}'");
  966. }
  967. }
  968. # check for missing brace on same line before or after 'else'
  969. if (my ($head, $tail) = m/(^|^.*\W)else(\W.*$|$)/) {
  970. my $brace_before = $head =~ /}[\s@]*$/; # '}' then any whitespace or comments
  971. my $brace_after = $tail =~ /^[\s@]*if[\s@]*\(.*\)[\s@]*{|[\s@]*{/;
  972. # possibly 'if (...)' (with potentially inner '(' and ')') then any whitespace or comments then '{'
  973. if (!$brace_before) {
  974. if ($line_before > 0 && $contents_before_ =~ /}[\s@]*$/) {
  975. report("'else' not on same line as preceding '}'");
  976. } elsif (parens_balance($tail) == 0) { # avoid false positive due to unfinished expr on current line
  977. report("no '}' on same line before 'else ... {'") if $brace_after;
  978. }
  979. } elsif (parens_balance($tail) == 0) { # avoid false positive due to unfinished expr on current line
  980. report("no '{' on same line after '} else'") if $brace_before && !$brace_after;
  981. }
  982. }
  983. POSTPROCESS_DIRECTIVE:
  984. # on begin of multi-line preprocessor directive, adapt indent
  985. # need to use original line contents because trailing '\' may have been stripped above
  986. if ($contents =~ m/^(.*?)[\s@]*\\[\s@]*$/) { # trailing '\' (which is not stripped from $contents),
  987. # typically used in macro definitions (or other preprocessor directives)
  988. if ($in_directive == 0) {
  989. $in_macro_header = m/^\s*#\s*define(\W|$)?(.*)/ ? 1 + parens_balance($2) : 0; # '#define' is beginning
  990. $directive_offset = INDENT_LEVEL;
  991. $block_indent += $directive_offset;
  992. }
  993. $in_directive += 1;
  994. }
  995. # post-processing at end of line @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  996. LINE_FINISHED:
  997. # on end of multi-line preprocessor directive, adapt indent
  998. if ($in_directive > 0 &&
  999. # need to use original line contents because trailing \ may have been stripped
  1000. !($contents =~ m/^(.*?)[\s@]*\\[\s@]*$/)) { # no trailing '\'
  1001. $block_indent -= $directive_offset;
  1002. $in_directive = 0;
  1003. # macro body typically does not include terminating ';'
  1004. $hanging_offset = 0; # compensate for this in case macro ends, e.g., as 'while (0)'
  1005. }
  1006. if (m/^\s*$/) { # at begin of file essentially empty line: just whitespace (and maybe a '\')
  1007. report("leading ".($1 eq "" ? "empty" :"whitespace")." line") if $line == 1 && !$sloppy_SPC;
  1008. } else {
  1009. if ($line_before > 0) {
  1010. my $linediff = $line - $line_before - 1;
  1011. report("$linediff empty lines before") if $linediff > 1 && !$sloppy_SPC;
  1012. }
  1013. $line_before2 = $line_before;
  1014. $contents_before2 = $contents_before;
  1015. $contents_before_2 = $contents_before_;
  1016. $line_before = $line;
  1017. $contents_before = $contents;
  1018. $contents_before_ = $_;
  1019. $count_before = $count;
  1020. }
  1021. if ($self_test) { # debugging
  1022. my $should_report = $contents =~ m/\*@(\d)?/ ? 1 : 0;
  1023. $should_report = +$1 if $should_report != 0 && defined $1;
  1024. print("$ARGV:$line:$num_reports_line reports on:$contents")
  1025. if $num_reports_line != $should_report;
  1026. }
  1027. $num_reports_line = 0;
  1028. # post-processing at end of file @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  1029. if (eof) {
  1030. # check for essentially empty line (which may include a '\') just before EOF
  1031. report(($1 eq "\n" ? "empty line" : $2 ne "" ? "'\\'" : "whitespace")." at EOF")
  1032. if $contents =~ m/^(\s*(\\?)\s*)$/ && !$sloppy_SPC;
  1033. # report unclosed expression-level nesting
  1034. check_nested_nonblock_indents("expr at EOF"); # also adapts @nested_block_indents
  1035. # sanity-check balance of block-level { ... } via final $block_indent at end of file
  1036. report_flexibly($line, +@nested_block_indents." unclosed '{'", "(EOF)\n") if @nested_block_indents != 0;
  1037. # sanity-check balance of #if ... #endif via final preprocessor directive indent at end of file
  1038. report_flexibly($line, "$directive_nesting unclosed '#if'", "(EOF)\n") if $directive_nesting != 0;
  1039. reset_file_state();
  1040. }
  1041. }
  1042. # final summary report @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  1043. my $num_other_reports = $num_reports - $num_indent_reports - $num_nesting_issues
  1044. - $num_syntax_issues - $num_SPC_reports - $num_length_reports;
  1045. print "$num_reports ($num_indent_reports indentation, $num_nesting_issues directive nesting, ".
  1046. "$num_syntax_issues syntax, $num_SPC_reports whitespace, $num_length_reports length, $num_other_reports other)".
  1047. " issues have been found by $0\n" if $num_reports != 0 && !$self_test;