-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluable_statement.go
46 lines (35 loc) · 1.44 KB
/
evaluable_statement.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
package valuate
import (
"github.com/antlr4-go/antlr/v4"
"github.com/bruceding/go-antlr-valuate/parser"
)
type EvaluableStatement struct {
variableScanListener *parser.VariableScanListener
progContext parser.IProgContext
customFunctions map[string]parser.ExpressionFunction
}
func NewEvaluableStatement(expr string) (*EvaluableStatement, error) {
m := make(map[string]parser.ExpressionFunction)
return NewEvaluableStatementWithFunctions(expr, m)
}
func NewEvaluableStatementWithFunctions(expr string, functions map[string]parser.ExpressionFunction) (*EvaluableStatement, error) {
lexer := parser.NewGovaluateLexer(antlr.NewInputStream(expr))
stream := antlr.NewCommonTokenStream(lexer, antlr.LexerDefaultTokenChannel)
p := parser.NewGovaluateParser(stream)
p.RemoveErrorListeners()
errorListener := NewEvaluableStatementErrorListener()
p.AddErrorListener(errorListener)
progContext := p.Prog()
scan := parser.NewVariableScanListener()
antlr.ParseTreeWalkerDefault.Walk(scan, progContext)
return &EvaluableStatement{
variableScanListener: scan,
progContext: progContext,
customFunctions: functions,
}, errorListener.Error()
}
func (e *EvaluableStatement) Evaluate(params map[string]interface{}) (map[string]any, []error) {
ast := parser.NewStatementASTEvaluatorWithParams(params, e.customFunctions, e.variableScanListener.GetNode2Variables())
ast.Visit(e.progContext)
return ast.ParamsMap(), ast.Errors()
}