Skip to content

Commit

Permalink
checker, cgen: fix if expr with result (#15709)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Sep 9, 2022
1 parent 71f5f7f commit 0f3a395
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion vlib/v/checker/if.v
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion vlib/v/gen/c/if.v
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
}
17 changes: 17 additions & 0 deletions vlib/v/tests/if_expr_with_result_test.v
@@ -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
}

0 comments on commit 0f3a395

Please sign in to comment.