mirror of
https://github.com/hanzoai/expr.git
synced 2026-09-24 16:58:58 +00:00
Fix operator overloading (#554)
This commit is contained in:
+2
-1
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user