From 03bef2445608865ae30c5db7c07d1c49189869fe Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 25 Oct 2022 23:17:48 +0800 Subject: [PATCH] checker: fix returning embedded error result (#16208) --- vlib/v/checker/checker.v | 6 +++--- vlib/v/checker/return.v | 11 ++++++++++ .../embed_error_in_returning_result_test.v | 21 +++++++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/embed_error_in_returning_result_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 4747a63f62..e10b3667d7 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -858,9 +858,9 @@ fn (mut c Checker) type_implements(typ ast.Type, interface_type ast.Type, pos to // TODO: remove once deprecation period for `IError` methods has ended if inter_sym.idx == ast.error_type_idx && (imethod.name == 'msg' || imethod.name == 'code') { - c.note("`$styp` doesn't implement method `$imethod.name` of interface `$inter_sym.name`. The usage of fields is being deprecated in favor of methods.", - pos) - continue + // c.note("`$styp` doesn't implement method `$imethod.name` of interface `$inter_sym.name`. The usage of fields is being deprecated in favor of methods.", + // pos) + return false } // << diff --git a/vlib/v/checker/return.v b/vlib/v/checker/return.v index 114c010f6a..11c0f807eb 100644 --- a/vlib/v/checker/return.v +++ b/vlib/v/checker/return.v @@ -138,6 +138,17 @@ pub fn (mut c Checker) return_stmt(mut node ast.Return) { } continue } + if got_typ_sym.kind == .struct_ + && c.type_implements(got_typ, ast.error_type, node.pos) { + node.exprs[expr_idxs[i]] = ast.CastExpr{ + expr: node.exprs[expr_idxs[i]] + typname: 'IError' + typ: ast.error_type + expr_type: got_typ + } + node.types[expr_idxs[i]] = ast.error_type + continue + } got_typ_name := if got_typ_sym.kind == .function { '${c.table.type_to_str(got_typ)}' } else { diff --git a/vlib/v/tests/embed_error_in_returning_result_test.v b/vlib/v/tests/embed_error_in_returning_result_test.v new file mode 100644 index 0000000000..89a80281b1 --- /dev/null +++ b/vlib/v/tests/embed_error_in_returning_result_test.v @@ -0,0 +1,21 @@ +struct NotFoundErr { + Error + id string +} + +struct User {} + +fn find_by_id(id string) !User { + return NotFoundErr{ + id: id + } +} + +fn test_embed_error_in_returning_result() { + find_by_id('id123') or { + println(err) + assert true + return + } + assert false +}