diff --git a/vlib/v/fmt/tests/if_cond_with_inline_comments_expected.vv b/vlib/v/fmt/tests/if_cond_with_inline_comments_expected.vv new file mode 100644 index 0000000000..3ae8cc09d3 --- /dev/null +++ b/vlib/v/fmt/tests/if_cond_with_inline_comments_expected.vv @@ -0,0 +1,13 @@ +fn main() { + a, b := true, true + + // a + if a || b { + println('hi') + } + + // a + if a || b { + println('hi') + } +} diff --git a/vlib/v/fmt/tests/if_cond_with_inline_comments_input.vv b/vlib/v/fmt/tests/if_cond_with_inline_comments_input.vv new file mode 100644 index 0000000000..77bb9fc87d --- /dev/null +++ b/vlib/v/fmt/tests/if_cond_with_inline_comments_input.vv @@ -0,0 +1,10 @@ +fn main() { + a, b := true, true + + if a || // a + b { + println('hi') + } + + if a /* a */ || b {println('hi')} +} diff --git a/vlib/v/parser/expr.v b/vlib/v/parser/expr.v index c22d311746..c123ccf73a 100644 --- a/vlib/v/parser/expr.v +++ b/vlib/v/parser/expr.v @@ -21,6 +21,9 @@ pub fn (mut p Parser) check_expr(precedence int) ?ast.Expr { if !p.pref.is_fmt { p.eat_comments() } + if p.inside_if_cond { + p.if_cond_comments << p.eat_comments() + } inside_array_lit := p.inside_array_lit p.inside_array_lit = false defer { @@ -350,6 +353,9 @@ pub fn (mut p Parser) check_expr(precedence int) ?ast.Expr { return node } } + if p.inside_if_cond { + p.if_cond_comments << p.eat_comments() + } return p.expr_with_left(node, precedence, is_stmt_ident) } @@ -481,6 +487,9 @@ fn (mut p Parser) infix_expr(left ast.Expr) ast.Expr { precedence := p.tok.precedence() mut pos := p.tok.pos() p.next() + if p.inside_if_cond { + p.if_cond_comments << p.eat_comments() + } mut right := ast.empty_expr() prev_expecting_type := p.expecting_type if op in [.key_is, .not_is] { diff --git a/vlib/v/parser/if_match.v b/vlib/v/parser/if_match.v index 0a993d033f..77944b0bca 100644 --- a/vlib/v/parser/if_match.v +++ b/vlib/v/parser/if_match.v @@ -128,7 +128,13 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr { } else { prev_guard = false p.comptime_if_cond = true + p.inside_if_cond = true cond = p.expr(0) + p.inside_if_cond = false + if p.if_cond_comments.len > 0 { + comments << p.if_cond_comments + p.if_cond_comments = [] + } p.comptime_if_cond = false } comments << p.eat_comments() diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index b300e19cfd..964411f487 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -36,6 +36,7 @@ mut: inside_test_file bool // when inside _test.v or _test.vv file inside_if bool inside_if_expr bool + inside_if_cond bool inside_ct_if_expr bool inside_or_expr bool inside_for bool @@ -90,6 +91,7 @@ mut: should_abort bool // when too many errors/warnings/notices are accumulated, should_abort becomes true, and the parser should stop codegen_text string struct_init_generic_types []ast.Type + if_cond_comments []ast.Comment } __global codegen_files = []&ast.File{}