From 554f21a29c236a1c863f846f8f120122ec352d2d Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Fri, 12 Jan 2024 00:01:44 +0530 Subject: [PATCH] checker: disallow `option` or `result` return type, for infix operator overloading (#20494) --- vlib/v/checker/fn.v | 2 ++ ...erloading_return_type_option_or_result.out | 14 ++++++++++++ ...verloading_return_type_option_or_result.vv | 22 +++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 vlib/v/checker/tests/operator_overloading_return_type_option_or_result.out create mode 100644 vlib/v/checker/tests/operator_overloading_return_type_option_or_result.vv diff --git a/vlib/v/checker/fn.v b/vlib/v/checker/fn.v index d58adb7931d4d7..1bbcd5c94072d9 100644 --- a/vlib/v/checker/fn.v +++ b/vlib/v/checker/fn.v @@ -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) } } } diff --git a/vlib/v/checker/tests/operator_overloading_return_type_option_or_result.out b/vlib/v/checker/tests/operator_overloading_return_type_option_or_result.out new file mode 100644 index 00000000000000..4034dde74f9811 --- /dev/null +++ b/vlib/v/checker/tests/operator_overloading_return_type_option_or_result.out @@ -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 diff --git a/vlib/v/checker/tests/operator_overloading_return_type_option_or_result.vv b/vlib/v/checker/tests/operator_overloading_return_type_option_or_result.vv new file mode 100644 index 00000000000000..06db596e35d1c5 --- /dev/null +++ b/vlib/v/checker/tests/operator_overloading_return_type_option_or_result.vv @@ -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) +}