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