cgen: fix error for if expr returning sumtype (#13752)

pull/13754/head
yuyi 2022-03-16 21:43:17 +08:00 committed by GitHub
parent 315e07abf6
commit 7f62346213
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 0 deletions

View File

@ -200,7 +200,11 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
}
}
if needs_tmp_var {
if node.is_expr && g.table.sym(node.typ).kind == .sum_type {
g.expected_cast_type = node.typ
}
g.stmts_with_tmp_var(branch.stmts, tmp)
g.expected_cast_type = 0
} else {
// restore if_expr stmt header pos
stmt_pos := g.nth_stmt_pos(0)

View File

@ -0,0 +1,23 @@
struct A_str {}
struct B_str {}
type Token = A_str | B_str
fn next(mut v []Token) Token {
return if v.len > 0 { v.pop() } else { A_str{} }
}
fn test_if_expr_with_sumtype() {
mut arr := []Token{}
ret1 := next(mut arr)
println(ret1)
assert '$ret1' == 'Token(A_str{})'
arr << A_str{}
arr << B_str{}
ret2 := next(mut arr)
println(ret2)
assert '$ret2' == 'Token(B_str{})'
}