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