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

cgen: fix returning an option tuple - fn f() ?(int,int) { return g() } (#18851)

This commit is contained in:
yuyi 2023-07-13 17:02:26 +08:00 committed by GitHub
parent 413ffbfc3b
commit aef4367a27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View File

@ -4785,6 +4785,19 @@ fn (mut g Gen) return_stmt(node ast.Return) {
} else if sym.kind == .alias && fn_return_is_fixed_array {
ret_typ = '_v_' + g.typ((sym.info as ast.Alias).parent_type)
}
if node.exprs.len == 1 {
// `return fn_call_opt()`
if (fn_return_is_option || fn_return_is_result) && node.exprs[0] is ast.CallExpr
&& node.exprs[0].return_type == g.fn_decl.return_type
&& node.exprs[0].or_block.kind == .absent {
g.write('${ret_typ} ${tmpvar} = ')
g.expr(node.exprs[0])
g.writeln(';')
g.write_defer_stmts_when_needed()
g.writeln('return ${tmpvar};')
return
}
}
mut use_tmp_var := g.defer_stmts.len > 0 || g.defer_profile_code.len > 0
|| g.cur_lock.lockeds.len > 0
|| (fn_return_is_multi && node.exprs.len >= 1 && fn_return_is_option)

View File

@ -0,0 +1,17 @@
fn issue(data string) ?(int, string) {
if data.len == 0 {
return none
}
return data.len, data
}
fn wrapper(data string) ?(int, string) {
return issue(data)
}
fn test_return_option_call() {
dump(wrapper('issue'))
dump(wrapper('foobar'))
dump(wrapper(''))
assert true
}