Skip to content

Commit 45d4849

Browse files
authored
checker: fix returning match expr with custom error (#17413)
1 parent 00aecf9 commit 45d4849

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

vlib/v/checker/match.v

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,21 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
6969
ret_type = expr_type
7070
}
7171
} else if node.is_expr && ret_type.idx() != expr_type.idx() {
72-
c.check_match_branch_last_stmt(stmt, ret_type, expr_type)
72+
if (node.expected_type.has_flag(.option)
73+
|| node.expected_type.has_flag(.result))
74+
&& c.table.sym(stmt.typ).kind == .struct_
75+
&& c.type_implements(stmt.typ, ast.error_type, node.pos) {
76+
stmt.expr = ast.CastExpr{
77+
expr: stmt.expr
78+
typname: 'IError'
79+
typ: ast.error_type
80+
expr_type: stmt.typ
81+
pos: node.pos
82+
}
83+
stmt.typ = ast.error_type
84+
} else {
85+
c.check_match_branch_last_stmt(stmt, ret_type, expr_type)
86+
}
7387
}
7488
} else if stmt !is ast.Return {
7589
if node.is_expr && ret_type != ast.void_type {
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
struct CustomError {
2+
Error
3+
}
4+
5+
fn ret() !string {
6+
return match true {
7+
true { 'ok' }
8+
else { CustomError{} }
9+
}
10+
}
11+
12+
fn test_return_match_expr_with_custom_error() {
13+
if r := ret() {
14+
assert r == 'ok'
15+
} else {
16+
assert false
17+
}
18+
}

0 commit comments

Comments
 (0)