From 7c7c4aac4835b795c0357fb3cf52464899ef41dd Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Mon, 10 Jun 2024 04:44:59 -0300 Subject: [PATCH] cgen: fix or expr with non option fn call return (fix #21660) (#21661) --- vlib/v/gen/c/cgen.v | 2 +- .../tests/option_or_expr_with_non_opt_test.v | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/option_or_expr_with_non_opt_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 1790a7ff510440..246d3a1e866571 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -6997,7 +6997,7 @@ fn (mut g Gen) gen_or_block_stmts(cvar_name string, cast_typ string, stmts []ast && g.table.final_sym(return_type).kind == .array_fixed if !is_array_fixed { if g.inside_return && !g.inside_struct_init - && expr_stmt.expr is ast.CallExpr + && expr_stmt.expr is ast.CallExpr&& (expr_stmt.expr as ast.CallExpr).return_type.has_option_or_result() && g.cur_fn.return_type.has_option_or_result() && return_type.has_option_or_result() && expr_stmt.expr.or_block.kind == .absent { diff --git a/vlib/v/tests/option_or_expr_with_non_opt_test.v b/vlib/v/tests/option_or_expr_with_non_opt_test.v new file mode 100644 index 00000000000000..05fd3ebedd428e --- /dev/null +++ b/vlib/v/tests/option_or_expr_with_non_opt_test.v @@ -0,0 +1,40 @@ +pub struct Foo { + a int + b int +} + +pub fn (f Foo) hello() ! { + println('Hello') +} + +fn default_foo() IFoo { + return Foo{} +} + +fn default_bar() IFoo { + return Foo{} +} + +pub struct Bar { + foo ?IFoo + bar ?IFoo +} + +pub interface IFoo { + hello() ! +} + +pub fn (b Bar) get_foo(baz string) !IFoo { + if baz == 'foo' { + return b.foo or { default_foo() } + } else if baz == 'bar' { + return b.bar or { default_bar() } + } + return error('unknown baz ${baz}') +} + +fn test_main() { + a := Bar{}.get_foo('foo')! + a.hello()! + assert a is IFoo +}