From 55d69203f8c4672884ad138cc3dab88fa7a57381 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 12 Nov 2024 19:06:26 +0800 Subject: [PATCH] checker: fix if expr with empty array init expression (related #22832) (#22841) --- vlib/v/checker/if.v | 4 ++++ .../ifs/if_expr_with_empty_array_init_test.v | 14 ++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 vlib/v/tests/conditions/ifs/if_expr_with_empty_array_init_test.v diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index 20e91c853..602ce9dbb 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -422,6 +422,9 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { } continue } + if c.expected_expr_type != ast.void_type { + c.expected_type = c.expected_expr_type + } stmt.typ = c.expr(mut stmt.expr) if c.table.type_kind(c.expected_type) == .multi_return && c.table.type_kind(stmt.typ) == .multi_return { @@ -447,6 +450,7 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { } else { node.typ = stmt.typ } + c.expected_expr_type = node.typ continue } else if node.typ in [ast.float_literal_type, ast.int_literal_type] { if node.typ == ast.int_literal_type { diff --git a/vlib/v/tests/conditions/ifs/if_expr_with_empty_array_init_test.v b/vlib/v/tests/conditions/ifs/if_expr_with_empty_array_init_test.v new file mode 100644 index 000000000..f4077638f --- /dev/null +++ b/vlib/v/tests/conditions/ifs/if_expr_with_empty_array_init_test.v @@ -0,0 +1,14 @@ +fn test_if_expr_with_empty_array_init() { + arr1 := ['Peter', 'Bob'] + arr2 := ['Sam', 'Mike'] + typ := 1 + names := if typ == 1 { + arr1 + } else if typ == 2 { + arr2 + } else { + [] + } + println(names) + assert names == ['Peter', 'Bob'] +} -- 2.39.5