checker: fix match expr returning optional (#10281)

pull/10285/head
yuyi 2021-05-31 17:34:55 +08:00 committed by GitHub
parent 5b9256ba0b
commit 5aa4f622b6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 1 deletions

View File

@ -5364,7 +5364,7 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
}
expr_type := c.expr(stmt.expr)
if ret_type == ast.void_type {
if node.is_expr
if node.is_expr && !node.expected_type.has_flag(.optional)
&& c.table.get_type_symbol(node.expected_type).kind == .sum_type {
ret_type = node.expected_type
} else {

View File

@ -0,0 +1,36 @@
type Any = int | string
fn ok(s string) Any {
return match s {
'foo' {
Any(1)
}
else {
Any('asdf')
}
}
}
fn fails(s string) ?Any {
return match s {
'foo' {
Any(1)
}
else {
Any('asdf')
}
}
}
fn test_match_expr_returning_optional() {
ret1 := ok('foo')
println(ret1)
assert ret1 == Any(1)
ret2 := fails('foo') or {
assert false
return
}
println(ret2)
assert ret2 == Any(1)
}