From ee0309c1291ddbc78d69c01a66340517071fa6cc Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Wed, 25 Mar 2026 22:44:51 +0300 Subject: [PATCH] checker: fix arithmetic operator overloading result type (fixes #23194) --- vlib/v/checker/fn.v | 8 ++++++++ ...overloading_primitive_alias_return_type_err.out | 14 ++++++++++++++ ..._overloading_primitive_alias_return_type_err.vv | 10 ++++++++++ 3 files changed, 32 insertions(+) create mode 100644 vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.out create mode 100644 vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.vv diff --git a/vlib/v/checker/fn.v b/vlib/v/checker/fn.v index 3a6fd760e..1b359c3f2 100644 --- a/vlib/v/checker/fn.v +++ b/vlib/v/checker/fn.v @@ -522,6 +522,14 @@ fn (mut c Checker) fn_decl(mut node ast.FnDecl) { } else if node.return_type != ast.bool_type && node.name in ['<', '=='] { c.error('operator comparison methods should return `bool`', node.pos) } else if parent_sym.is_primitive() { + if node.return_type.has_option_or_result() { + c.error('return type cannot be Option or Result', node.return_type_pos) + } else if node.name in ['+', '-', '*', '%', '/'] + && node.return_type != receiver_type { + srtype := c.table.type_to_str(receiver_type) + c.error('operator `${node.name}` methods on primitive aliases should return `${srtype}`', + node.return_type_pos) + } // aliases of primitive types are explicitly allowed } else if receiver_type != param_type { srtype := c.table.type_to_str(receiver_type) diff --git a/vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.out b/vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.out new file mode 100644 index 000000000..ced95529d --- /dev/null +++ b/vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.out @@ -0,0 +1,14 @@ +vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.vv:4:24: error: operator `+` methods on primitive aliases should return `Byte` + 2 | type ByteString = string + 3 | + 4 | fn (a Byte) + (b Byte) ByteString { + | ~~~~~~~~~~ + 5 | return ByteString('x') + 6 | } +vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.vv:8:24: error: operator `-` methods on primitive aliases should return `Byte` + 6 | } + 7 | + 8 | fn (a Byte) - (b Byte) string { + | ~~~~~~ + 9 | return 'y' + 10 | } diff --git a/vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.vv b/vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.vv new file mode 100644 index 000000000..3fc4f18ca --- /dev/null +++ b/vlib/v/checker/tests/operator_overloading_primitive_alias_return_type_err.vv @@ -0,0 +1,10 @@ +type Byte = u8 +type ByteString = string + +fn (a Byte) + (b Byte) ByteString { + return ByteString('x') +} + +fn (a Byte) - (b Byte) string { + return 'y' +} -- 2.39.5