1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker, cgen: fix if expr with result (#15709)

This commit is contained in:
yuyi 2022-09-09 16:29:21 +08:00 committed by GitHub
parent 71f5f7f3a7
commit 0f3a395ca2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 2 deletions

View File

@ -188,7 +188,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
}
}
c.expected_type = former_expected_type
if c.expected_type.has_flag(.optional) {
if c.expected_type.has_flag(.optional) || c.expected_type.has_flag(.result) {
if node.typ == ast.void_type {
node.is_expr = true
node.typ = c.expected_type

View File

@ -7,7 +7,7 @@ import v.ast
fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool {
if node.is_expr && g.inside_ternary == 0 {
if g.is_autofree || node.typ.has_flag(.optional) {
if g.is_autofree || node.typ.has_flag(.optional) || node.typ.has_flag(.result) {
return true
}
for branch in node.branches {
@ -142,6 +142,8 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
if needs_tmp_var {
if node.typ.has_flag(.optional) {
g.inside_if_optional = true
} else if node.typ.has_flag(.result) {
g.inside_if_result = true
}
styp := g.typ(node.typ)
cur_line = g.go_before_stmt(0)
@ -325,5 +327,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
}
if node.typ.has_flag(.optional) {
g.inside_if_optional = false
} else if node.typ.has_flag(.result) {
g.inside_if_result = false
}
}

View File

@ -0,0 +1,17 @@
fn foo(i int) ?bool {
return if i == 0 { true } else { none }
}
fn bar(i int) !bool {
return if i == 0 { true } else { error('') }
}
fn test_if_expr_with_result() {
r1 := foo(0) or { false }
println(r1)
assert r1
r2 := bar(0) or { false }
println(r2)
assert r2
}