From 34efc9c427372719b175c9efc64a3a48dcdc6b6d Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 9 Feb 2023 17:45:46 +0800 Subject: [PATCH] checker: fix returning if expr with custom error (#17265) --- vlib/v/checker/if.v | 13 +++++++++++++ .../return_if_expr_with_custom_error_test.v | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 vlib/v/tests/return_if_expr_with_custom_error_test.v diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index 76cb37305..abe971947 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -285,6 +285,19 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { if is_noreturn_callexpr(stmt.expr) { continue } + if (node.typ.has_flag(.option) || node.typ.has_flag(.result)) + && c.table.sym(stmt.typ).kind == .struct_ + && c.type_implements(stmt.typ, ast.error_type, node.pos) { + stmt.expr = ast.CastExpr{ + expr: stmt.expr + typname: 'IError' + typ: ast.error_type + expr_type: stmt.typ + pos: node.pos + } + stmt.typ = ast.error_type + continue + } c.error('mismatched types `${c.table.type_to_str(node.typ)}` and `${c.table.type_to_str(stmt.typ)}`', node.pos) } diff --git a/vlib/v/tests/return_if_expr_with_custom_error_test.v b/vlib/v/tests/return_if_expr_with_custom_error_test.v new file mode 100644 index 000000000..bb5292663 --- /dev/null +++ b/vlib/v/tests/return_if_expr_with_custom_error_test.v @@ -0,0 +1,19 @@ +struct CustomError { + Error +} + +fn ret() !string { + return if true { + 'ok' + } else { + CustomError{} + } +} + +fn test_return_if_expr_with_custom_error() { + if r := ret() { + assert r == 'ok' + } else { + assert false + } +} -- 2.39.5