Skip to content

Commit

Permalink
checker: fix match expr with empty array init expression (vlang#22832)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored Nov 11, 2024
1 parent ec1f95a commit 5092626
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
8 changes: 6 additions & 2 deletions vlib/v/checker/containers.v
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,12 @@ fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
// `a = []`
if node.exprs.len == 0 {
// `a := fn_returning_opt_array() or { [] }`
if c.expected_type == ast.void_type && c.expected_or_type != ast.void_type {
c.expected_type = c.expected_or_type
if c.expected_type == ast.void_type {
if c.expected_or_type != ast.void_type {
c.expected_type = c.expected_or_type
} else if c.expected_expr_type != ast.void_type {
c.expected_type = c.expected_expr_type
}
}
mut type_sym := c.table.sym(c.expected_type)
if type_sym.kind != .array || type_sym.array_info().elem_type == ast.void_type {
Expand Down
7 changes: 6 additions & 1 deletion vlib/v/checker/match.v
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
if branch.stmts.len > 0 && node.is_expr {
mut stmt := branch.stmts.last()
if mut stmt is ast.ExprStmt {
c.expected_type = node.expected_type
c.expected_type = if c.expected_expr_type != ast.void_type {
c.expected_expr_type
} else {
node.expected_type
}
expr_type := if stmt.expr is ast.CallExpr {
stmt.typ
} else {
Expand All @@ -92,6 +96,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
}
}
}
c.expected_expr_type = expr_type
}
infer_cast_type = stmt.typ
if mut stmt.expr is ast.CastExpr {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn test_match_expr_with_empty_array_init() {
arr1 := ['Peter', 'Bob']
arr2 := ['Sam', 'Mike']
typ := 1
names := match typ {
1 {
arr1
}
2 {
arr2
}
else {
[]
}
}
println(names)
assert names == ['Peter', 'Bob']
}

0 comments on commit 5092626

Please sign in to comment.