check-format.pl 60 KB

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