Skip to content

Commit

Permalink
checker, cgen: allow op overload for type with generic parent (#21262)
Browse files Browse the repository at this point in the history
  • Loading branch information
Delta456 authored Apr 12, 2024
1 parent a222d7b commit 433f914
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
4 changes: 2 additions & 2 deletions vlib/v/checker/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,8 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
} else {
return_type = left_type
}
} else if left_final_sym.has_method(node.op.str()) {
if method := left_final_sym.find_method(node.op.str()) {
} else if left_final_sym.has_method_with_generic_parent(node.op.str()) {
if method := left_final_sym.find_method_with_generic_parent(node.op.str()) {
return_type = method.return_type
} else {
return_type = left_type
Expand Down
11 changes: 9 additions & 2 deletions vlib/v/gen/c/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -784,9 +784,16 @@ fn (mut g Gen) infix_expr_arithmetic_op(node ast.InfixExpr) {
if left.sym.has_method(node.op.str()) {
method = left.sym.find_method(node.op.str()) or { ast.Fn{} }
method_name = left.sym.cname + '_' + util.replace_op(node.op.str())
} else if left.unaliased_sym.has_method(node.op.str()) {
method = left.unaliased_sym.find_method(node.op.str()) or { ast.Fn{} }
} else if left.unaliased_sym.has_method_with_generic_parent(node.op.str()) {
method = left.unaliased_sym.find_method_with_generic_parent(node.op.str()) or {
ast.Fn{}
}
method_name = left.unaliased_sym.cname + '_' + util.replace_op(node.op.str())
if left.unaliased_sym.info is ast.Struct
&& left.unaliased_sym.info.generic_types.len > 0 {
method_name = g.generic_fn_name(left.unaliased_sym.info.concrete_types,
method_name)
}
} else {
g.gen_plain_infix_expr(node)
return
Expand Down
13 changes: 13 additions & 0 deletions vlib/v/tests/operator_overloading_type_alias_generic_parent_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import math.vec

type Vec3 = vec.Vec3[f64]

fn test_operator_overloading_type_alias_generic_parent() {
a := Vec3{1.0, 2.0, 3.0}
b := Vec3{0.5, 1.5, 2.5}

assert a + b == Vec3{1.5, 3.5, 5.5}
assert a - b == Vec3{0.5, 0.5, 0.5}
assert a * b == Vec3{0.5, 3.0, 7.5}
assert a / b == Vec3{2.0, 1.3333333333333333, 1.2}
}

0 comments on commit 433f914

Please sign in to comment.