From 6df25afe0615c430e0e1ffc99fe11c8a27252d57 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 7 Dec 2024 23:03:38 -0300 Subject: [PATCH] cgen: fix option codegen for accept IError value (fix #23076) (#23085) --- vlib/v/checker/check_types.v | 2 ++ vlib/v/gen/c/cgen.v | 2 ++ vlib/v/tests/options/option_with_error_test.v | 17 +++++++++++++++++ 3 files changed, 21 insertions(+) create mode 100644 vlib/v/tests/options/option_with_error_test.v diff --git a/vlib/v/checker/check_types.v b/vlib/v/checker/check_types.v index f0f827ab2..c5523d501 100644 --- a/vlib/v/checker/check_types.v +++ b/vlib/v/checker/check_types.v @@ -162,6 +162,8 @@ fn (mut c Checker) check_types(got ast.Type, expected ast.Type) bool { } if expected.has_option_or_result() { sym := c.table.sym(got) + // Allow error() for Option and Result types + // `none` for Option only if ((sym.idx == ast.error_type_idx || got in [ast.none_type, ast.error_type]) && expected.has_flag(.option)) || ((sym.idx == ast.error_type_idx || got == ast.error_type) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 1aabb8b0c..fc3d9485f 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2079,6 +2079,8 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T g.write('${g.styp(ret_typ)} ${tmp_var} = ') g.gen_option_error(ret_typ, expr) g.writeln(';') + } else if expr is ast.Ident && expr_typ == ast.error_type { + g.writeln('${g.styp(ret_typ)} ${tmp_var} = {.state=2, .err = ${expr.name}};') } else { mut simple_assign := false if ret_typ.has_flag(.generic) { diff --git a/vlib/v/tests/options/option_with_error_test.v b/vlib/v/tests/options/option_with_error_test.v new file mode 100644 index 000000000..c8d216b8f --- /dev/null +++ b/vlib/v/tests/options/option_with_error_test.v @@ -0,0 +1,17 @@ +struct Struct { + error ?string +} + +fn result_function() !Struct { + return error('This is an error') +} + +fn test_main() { + some_struct := result_function() or { + Struct{ + error: err + } + } + // some_struct.error? + assert some_struct.error or { '${err}' } == 'This is an error' +} -- 2.39.5