checker, cgen: fix optional with if expr (#10242)

pull/10245/head
yuyi 2021-05-29 15:00:12 +08:00 committed by GitHub
parent 465860e418
commit 8785599094
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 1 deletions

View File

@ -5816,6 +5816,17 @@ pub fn (mut c Checker) unsafe_expr(mut node ast.UnsafeExpr) ast.Type {
pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
if_kind := if node.is_comptime { '\$if' } else { 'if' }
mut node_is_expr := false
if node.branches.len > 0 && node.has_else {
stmts := node.branches[0].stmts
if stmts.len > 0 && stmts[stmts.len - 1] is ast.ExprStmt
&& (stmts[stmts.len - 1] as ast.ExprStmt).typ != ast.void_type {
node_is_expr = true
}
}
if c.expected_type == ast.void_type && node_is_expr {
c.expected_type = c.expected_or_type
}
expr_required := c.expected_type != ast.void_type
former_expected_type := c.expected_type
node.typ = ast.void_type

View File

@ -5877,7 +5877,7 @@ fn (mut g Gen) or_block(var_name string, or_block ast.OrExpr, return_type ast.Ty
g.inside_opt_data = true
g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_flag(.optional))
g.inside_opt_data = old_inside_opt_data
if g.inside_ternary == 0 && !(expr_stmt.expr is ast.IfExpr) {
if g.inside_ternary == 0 {
g.writeln(';')
}
g.stmt_path_pos.delete_last()

View File

@ -0,0 +1,16 @@
fn f() ?int {
return none
}
fn test_option_if_expr() {
i := f() or {
if err is none {
int(0)
} else {
eprintln(err)
int(-1)
}
}
println(i)
assert i == 0
}