Fix operator overloading (#554)

This commit is contained in:
Vladimir Fetisov
2024-02-08 21:07:58 +01:00
committed by GitHub
parent 8d2e6b133c
commit c7c060ff44
2 changed files with 43 additions and 1 deletions
+2 -1
View File
@@ -48,12 +48,13 @@ func (p *OperatorPatcher) Visit(node *ast.Node) {
leftType := binaryNode.Left.Type()
rightType := binaryNode.Right.Type()
_, fn, ok := FindSuitableOperatorOverload(fns, p.Types, leftType, rightType)
ret, fn, ok := FindSuitableOperatorOverload(fns, p.Types, leftType, rightType)
if ok {
newNode := &ast.CallNode{
Callee: &ast.IdentifierNode{Value: fn},
Arguments: []ast.Node{binaryNode.Left, binaryNode.Right},
}
newNode.SetType(ret)
ast.Patch(node, newNode)
}
}
+41
View File
@@ -311,6 +311,47 @@ func ExampleOperator() {
// Output: true
}
func ExampleOperator_Decimal() {
type Decimal struct{ N float64 }
code := `A + B - C`
type Env struct {
A, B, C Decimal
Sub func(a, b Decimal) Decimal
Add func(a, b Decimal) Decimal
}
options := []expr.Option{
expr.Env(Env{}),
expr.Operator("+", "Add"),
expr.Operator("-", "Sub"),
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("Compile error: %v", err)
return
}
env := Env{
A: Decimal{3},
B: Decimal{2},
C: Decimal{1},
Sub: func(a, b Decimal) Decimal { return Decimal{a.N - b.N} },
Add: func(a, b Decimal) Decimal { return Decimal{a.N + b.N} },
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
// Output: {4}
}
func fib(n int) int {
if n <= 1 {
return n