-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluable_expression.go
54 lines (41 loc) · 1.51 KB
/
evaluable_expression.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package valuate
import (
"github.com/antlr4-go/antlr/v4"
"github.com/bruceding/go-antlr-valuate/parser"
)
type EvaluableExpression struct {
//ast *parser.ASTEvaluator
expressionContext parser.IExpressionContext
customFunctions map[string]parser.ExpressionFunction
}
func NewEvaluableExpression(expr string) (*EvaluableExpression, error) {
m := make(map[string]parser.ExpressionFunction)
return NewEvaluableExpressionWithFunctions(expr, m)
}
func NewEvaluableExpressionWithFunctions(expr string, functions map[string]parser.ExpressionFunction) (*EvaluableExpression, error) {
lexer := parser.NewGovaluateLexer(antlr.NewInputStream(expr))
stream := antlr.NewCommonTokenStream(lexer, antlr.LexerDefaultTokenChannel)
p := parser.NewGovaluateParser(stream)
p.RemoveErrorListeners()
errorListener := NewEvaluableStatementErrorListener()
p.AddErrorListener(errorListener)
expressionContext := p.Expression()
//ast := parser.NewASTEvaluator()
customFunctions := make(map[string]parser.ExpressionFunction, len(functions))
for k, v := range functions {
customFunctions[k] = v
}
return &EvaluableExpression{
//ast: ast,
expressionContext: expressionContext,
customFunctions: customFunctions,
}, errorListener.Error()
}
func (e *EvaluableExpression) Evaluate(params map[string]interface{}) (interface{}, error) {
ast := parser.NewASTEvaluatorWithParams(params, e.customFunctions)
result := ast.Visit(e.expressionContext)
if e, ok := result.(error); ok {
return nil, e
}
return result, nil
}