Skip to content

Commit

Permalink
checker: don't cast match branch structs to IError, when the return t…
Browse files Browse the repository at this point in the history
…ype of a function is !SumType (#22444)
  • Loading branch information
edam authored Oct 8, 2024
1 parent eb57746 commit 9d164d0
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
2 changes: 2 additions & 0 deletions vlib/v/checker/match.v
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
if ret_type.idx() != expr_type.idx() {
if node.expected_type.has_option_or_result()
&& c.table.sym(stmt.typ).kind == .struct_
&& (c.table.sym(ret_type).kind != .sum_type
|| !c.check_types(expr_type, ret_type))
&& c.type_implements(stmt.typ, ast.error_type, node.pos) {
stmt.expr = ast.CastExpr{
expr: stmt.expr
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
type Foo = int | string | Bar

struct Bar {}

fn foo_result_struct_second() !Foo {
return match true {
true { 1 }
else { Bar{} }
}
}

fn foo_option_struct_second() ?Foo {
return match true {
true { 1 }
else { Bar{} }
}
}

fn foo_result_string_second() !Foo {
return match true {
true { 1 }
else { '' }
}
}

fn foo_option_string_second() ?Foo {
return match true {
true { 1 }
else { '' }
}
}

fn foo_result_struct_first() !Foo {
return match true {
true { Bar{} }
else { 7 }
}
}

fn foo_option_struct_first() ?Foo {
return match true {
true { Bar{} }
else { 7 }
}
}

fn test_return_match_expr_of_sumtype_opt_res() {
mut ret := Foo{}

ret = foo_result_struct_second() or { return }
println(ret)
assert '${ret}' == 'Foo(1)'

ret = foo_option_struct_second() or { return }
println(ret)
assert '${ret}' == 'Foo(1)'

ret = foo_result_string_second() or { return }
println(ret)
assert '${ret}' == 'Foo(1)'

ret = foo_option_string_second() or { return }
println(ret)
assert '${ret}' == 'Foo(1)'

ret = foo_result_struct_first() or { return }
println(ret)
assert '${ret}' == 'Foo(Bar{})'

ret = foo_option_struct_first() or { return }
println(ret)
assert '${ret}' == 'Foo(Bar{})'
}

0 comments on commit 9d164d0

Please sign in to comment.