1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: fix returning if expr with custom error (#17265)

This commit is contained in:
yuyi 2023-02-09 17:45:46 +08:00 committed by GitHub
parent 47e8d967e6
commit 34efc9c427
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 0 deletions

View File

@ -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)
}

View File

@ -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
}
}