-
Notifications
You must be signed in to change notification settings - Fork 1
/
ast.go
107 lines (83 loc) · 1.78 KB
/
ast.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package expr
import "regexp"
// Expr expr
type Expr interface {
Exec(interface{}) (interface{}, error)
}
// VarExprFactory factory method
type VarExprFactory func([]byte, VarType) (Expr, error)
type stack struct {
nodes []*node
}
func (s *stack) push(v *node) {
s.nodes = append(s.nodes, v)
}
func (s *stack) append(v *node) {
s.current().add(v)
s.push(v)
}
func (s *stack) appendWithOP(fn CalcFunc, v *node) {
s.current().appendWithOP(fn, v)
s.push(v)
}
func (s *stack) current() *node {
return s.nodes[len(s.nodes)-1]
}
func (s *stack) pop() Expr {
n := len(s.nodes) - 1
v := s.nodes[n]
s.nodes[n] = nil
s.nodes = s.nodes[:n]
return v
}
type node struct {
exprs []Expr
fns []CalcFunc
}
func (n *node) add(expr Expr) {
n.exprs = append(n.exprs, expr)
}
func (n *node) append(expr Expr) {
n.exprs = append(n.exprs, expr)
}
func (n *node) appendWithOP(fn CalcFunc, expr Expr) {
n.exprs = append(n.exprs, expr)
n.fns = append(n.fns, fn)
}
func (n *node) Exec(ctx interface{}) (interface{}, error) {
left, err := n.exprs[0].Exec(ctx)
if err != nil {
return nil, err
}
for idx, right := range n.exprs[1:] {
left, err = n.fns[idx](left, right, ctx)
if err != nil {
return nil, err
}
}
return left, nil
}
type constString struct {
value string
}
func (expr *constString) Exec(ctx interface{}) (interface{}, error) {
return expr.value, nil
}
type constInt64 struct {
value int64
}
func (expr *constInt64) Exec(ctx interface{}) (interface{}, error) {
return expr.value, nil
}
type constRegexp struct {
value *regexp.Regexp
}
func (expr *constRegexp) Exec(ctx interface{}) (interface{}, error) {
return expr.value, nil
}
type constArray struct {
values []string
}
func (expr *constArray) Exec(ctx interface{}) (interface{}, error) {
return expr.values, nil
}