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

cgen: fix return result in or block (#16158)

This commit is contained in:
yuyi 2022-10-23 18:11:11 +08:00 committed by GitHub
parent 33b2b4c6a1
commit 3f035205b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 7 deletions

View File

@ -5477,13 +5477,29 @@ fn (mut g Gen) or_block(var_name string, or_block ast.OrExpr, return_type ast.Ty
if i == stmts.len - 1 {
expr_stmt := stmt as ast.ExprStmt
g.set_current_pos_as_last_stmt_pos()
g.write('*($mr_styp*) ${cvar_name}.data = ')
old_inside_opt_data := g.inside_opt_data
g.inside_opt_data = true
g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_flag(.optional).clear_flag(.result))
g.inside_opt_data = old_inside_opt_data
g.writeln(';')
g.stmt_path_pos.delete_last()
if g.inside_return && (expr_stmt.typ.idx() == ast.error_type_idx
|| expr_stmt.typ in [ast.none_type, ast.error_type]) {
// `return foo() or { error('failed') }`
if g.cur_fn != unsafe { nil } {
if g.cur_fn.return_type.has_flag(.result) {
g.write('return ')
g.gen_result_error(g.cur_fn.return_type, expr_stmt.expr)
g.writeln(';')
} else if g.cur_fn.return_type.has_flag(.optional) {
g.write('return ')
g.gen_optional_error(g.cur_fn.return_type, expr_stmt.expr)
g.writeln(';')
}
}
} else {
g.write('*($mr_styp*) ${cvar_name}.data = ')
old_inside_opt_data := g.inside_opt_data
g.inside_opt_data = true
g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_flag(.optional).clear_flag(.result))
g.inside_opt_data = old_inside_opt_data
g.writeln(';')
g.stmt_path_pos.delete_last()
}
} else {
g.stmt(stmt)
}

View File

@ -0,0 +1,21 @@
fn unwrap_int() ?int {
return 1
}
fn unwrap_function1() !int {
return unwrap_int() or { error('we are issing the return?') }
}
fn unwrap_function2() ?int {
return unwrap_int() or { none }
}
fn test_return_result_in_or_block() {
x1 := unwrap_function1() or { panic(err) }
println(x1)
assert x1 == 1
x2 := unwrap_function2() or { panic(err) }
println(x2)
assert x2 == 1
}