mirror of
https://github.com/hanzoai/expr.git
synced 2026-09-24 16:58:58 +00:00
Refactor operator patcher
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package conf
|
||||
|
||||
import "reflect"
|
||||
import (
|
||||
"github.com/antonmedv/expr/ast"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// OperatorsTable maps binary operators to corresponding list of functions.
|
||||
// Functions should be provided in the environment to allow operator overloading.
|
||||
@@ -24,3 +27,33 @@ func FindSuitableOperatorOverload(fns []string, types TypesTable, l, r reflect.T
|
||||
}
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
type OperatorPatcher struct {
|
||||
Operators OperatorsTable
|
||||
Types TypesTable
|
||||
}
|
||||
|
||||
func (p *OperatorPatcher) Enter(_ *ast.Node) {}
|
||||
func (p *OperatorPatcher) Exit(node *ast.Node) {
|
||||
binaryNode, ok := (*node).(*ast.BinaryNode)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
fns, ok := p.Operators[binaryNode.Operator]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
leftType := binaryNode.Left.Type()
|
||||
rightType := binaryNode.Right.Type()
|
||||
|
||||
_, 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},
|
||||
}
|
||||
ast.Patch(node, newNode)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user