-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexpr_evaluator.go
More file actions
79 lines (67 loc) · 2.04 KB
/
Copy pathexpr_evaluator.go
File metadata and controls
79 lines (67 loc) · 2.04 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package vuego
import (
"fmt"
"strings"
"sync"
"github.com/expr-lang/expr"
"github.com/expr-lang/expr/vm"
)
// ExprEvaluator wraps expr for evaluating boolean and interpolated expressions.
// It caches compiled programs to avoid recompilation.
type ExprEvaluator struct {
mu sync.RWMutex
programs map[string]*vm.Program
}
// NewExprEvaluator creates a new ExprEvaluator with an empty cache.
func NewExprEvaluator() *ExprEvaluator {
return &ExprEvaluator{
programs: make(map[string]*vm.Program),
}
}
// Eval evaluates an expression against the given environment (stack).
// It returns the result value and any error.
// The expression can contain:
// - Variable references: item, item.title, items[0]
// - Comparison: ==, !=, <, >, <=, >=, === (same as ==, for convenience)
// - Boolean operations: &&, ||, !
// - Function calls: len(items), isActive(v)
// - Literals: 42, "text", true, false.
func (e *ExprEvaluator) Eval(expression string, env map[string]any) (any, error) {
expression = strings.ReplaceAll(expression, "===", "==")
// Get or compile the program
prog, err := e.getProgram(expression)
if err != nil {
return nil, err
}
// Run the compiled program
result, err := expr.Run(prog, env)
if err != nil {
return nil, fmt.Errorf("eval error: %w", err)
}
return result, nil
}
// getProgram returns a cached compiled program or compiles a new one.
func (e *ExprEvaluator) getProgram(expression string) (*vm.Program, error) {
e.mu.RLock()
if prog, ok := e.programs[expression]; ok {
e.mu.RUnlock()
return prog, nil
}
e.mu.RUnlock()
// Compile the expression
prog, err := expr.Compile(expression, expr.AllowUndefinedVariables(), expr.DisableBuiltin("count"))
if err != nil {
return nil, fmt.Errorf("compile error: %w", err)
}
// Cache it
e.mu.Lock()
e.programs[expression] = prog
e.mu.Unlock()
return prog, nil
}
// ClearCache clears the program cache (useful for testing or memory management).
func (e *ExprEvaluator) ClearCache() {
e.mu.Lock()
defer e.mu.Unlock()
e.programs = make(map[string]*vm.Program)
}