Refactor operator patcher

This commit is contained in:
Anton Medvedev
2022-10-22 13:30:57 +02:00
parent f94fe06d80
commit c19d6d15fc
4 changed files with 51 additions and 58 deletions
+34 -1
View File
@@ -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)
}
}