2
0

check-format.pl 60 KB

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