checker: disallow option or result return type, for infix operator overloading (#20494)

This commit is contained in:
Swastik Baranwal 2024-01-12 00:01:44 +05:30 committed by GitHub
parent 69b0d1cfe9
commit 554f21a29c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 0 deletions

View File

@ -346,6 +346,8 @@ fn (mut c Checker) fn_decl(mut node ast.FnDecl) {
sptype := c.table.type_to_str(param_type)
c.error('the receiver type `${srtype}` should be the same type as the operand `${sptype}`',
node.pos)
} else if node.return_type.has_option_or_result() {
c.error('return type cannot be Option or Result', node.return_type_pos)
}
}
}

View File

@ -0,0 +1,14 @@
vlib/v/checker/tests/operator_overloading_return_type_option_or_result.vv:3:22: error: return type cannot be Option or Result
1 | type Vec = []int
2 |
3 | fn (v Vec) + (u Vec) !Vec {
| ~~~~
4 | if v.len != u.len {
5 | return error("Operations require dim(v) == dim(u)")
vlib/v/checker/tests/operator_overloading_return_type_option_or_result.vv:10:22: error: return type cannot be Option or Result
8 | }
9 |
10 | fn (v Vec) - (u Vec) ?Vec {
| ~~~~
11 | if v.len != u.len {
12 | return none

View File

@ -0,0 +1,22 @@
type Vec = []int
fn (v Vec) + (u Vec) !Vec {
if v.len != u.len {
return error("Operations require dim(v) == dim(u)")
}
return Vec([v[0] + u[0], v[1] + u[1], v[2] + u[2]])
}
fn (v Vec) - (u Vec) ?Vec {
if v.len != u.len {
return none
}
return Vec([v[0] + u[0], v[1] + u[1], v[2] + u[2]])
}
fn main() {
vec := Vec([1, 2, 3])
dump(vec + vec)
}