forked from expr-lang/expr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr.go
269 lines (235 loc) · 6.18 KB
/
expr.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package expr
import (
"errors"
"fmt"
"reflect"
"github.com/expr-lang/expr/ast"
"github.com/expr-lang/expr/builtin"
"github.com/expr-lang/expr/checker"
"github.com/expr-lang/expr/compiler"
"github.com/expr-lang/expr/conf"
"github.com/expr-lang/expr/file"
"github.com/expr-lang/expr/optimizer"
"github.com/expr-lang/expr/parser"
"github.com/expr-lang/expr/patcher"
"github.com/expr-lang/expr/vm"
)
// Option for configuring config.
type Option func(c *conf.Config)
// Env specifies expected input of env for type checks.
// If struct is passed, all fields will be treated as variables,
// as well as all fields of embedded structs and struct itself.
// If map is passed, all items will be treated as variables.
// Methods defined on this type will be available as functions.
func Env(env any) Option {
return func(c *conf.Config) {
c.WithEnv(env)
}
}
// AllowUndefinedVariables allows to use undefined variables inside expressions.
// This can be used with expr.Env option to partially define a few variables.
func AllowUndefinedVariables() Option {
return func(c *conf.Config) {
c.Strict = false
}
}
// Operator allows to replace a binary operator with a function.
func Operator(operator string, fn ...string) Option {
return func(c *conf.Config) {
p := &patcher.OperatorOverloading{
Operator: operator,
Overloads: fn,
Types: c.Types,
Functions: c.Functions,
}
c.Visitors = append(c.Visitors, p)
}
}
// ConstExpr defines func expression as constant. If all argument to this function is constants,
// then it can be replaced by result of this func call on compile step.
func ConstExpr(fn string) Option {
return func(c *conf.Config) {
c.ConstExpr(fn)
}
}
// AsAny tells the compiler to expect any result.
func AsAny() Option {
return func(c *conf.Config) {
c.ExpectAny = true
}
}
// AsKind tells the compiler to expect kind of the result.
func AsKind(kind reflect.Kind) Option {
return func(c *conf.Config) {
c.Expect = kind
c.ExpectAny = true
}
}
// AsBool tells the compiler to expect a boolean result.
func AsBool() Option {
return func(c *conf.Config) {
c.Expect = reflect.Bool
c.ExpectAny = true
}
}
// AsInt tells the compiler to expect an int result.
func AsInt() Option {
return func(c *conf.Config) {
c.Expect = reflect.Int
c.ExpectAny = true
}
}
// AsInt64 tells the compiler to expect an int64 result.
func AsInt64() Option {
return func(c *conf.Config) {
c.Expect = reflect.Int64
c.ExpectAny = true
}
}
// AsFloat64 tells the compiler to expect a float64 result.
func AsFloat64() Option {
return func(c *conf.Config) {
c.Expect = reflect.Float64
c.ExpectAny = true
}
}
// WarnOnAny tells the compiler to warn if expression return any type.
func WarnOnAny() Option {
return func(c *conf.Config) {
if c.Expect == reflect.Invalid {
panic("WarnOnAny() works only with combination with AsInt(), AsBool(), etc. options")
}
c.ExpectAny = false
}
}
// Optimize turns optimizations on or off.
func Optimize(b bool) Option {
return func(c *conf.Config) {
c.Optimize = b
}
}
// Patch adds visitor to list of visitors what will be applied before compiling AST to bytecode.
func Patch(visitor ast.Visitor) Option {
return func(c *conf.Config) {
c.Visitors = append(c.Visitors, visitor)
}
}
// Function adds function to list of functions what will be available in expressions.
func Function(name string, fn func(params ...any) (any, error), types ...any) Option {
return func(c *conf.Config) {
ts := make([]reflect.Type, len(types))
for i, t := range types {
t := reflect.TypeOf(t)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Func {
panic(fmt.Sprintf("expr: type of %s is not a function", name))
}
ts[i] = t
}
c.Functions[name] = &builtin.Function{
Name: name,
Func: fn,
Types: ts,
}
}
}
// DisableAllBuiltins disables all builtins.
func DisableAllBuiltins() Option {
return func(c *conf.Config) {
for name := range c.Builtins {
c.Disabled[name] = true
}
}
}
// DisableBuiltin disables builtin function.
func DisableBuiltin(name string) Option {
return func(c *conf.Config) {
c.Disabled[name] = true
}
}
// EnableBuiltin enables builtin function.
func EnableBuiltin(name string) Option {
return func(c *conf.Config) {
delete(c.Disabled, name)
}
}
// WithContext passes context to all functions calls with a context.Context argument.
func WithContext(name string) Option {
return Patch(patcher.WithContext{
Name: name,
})
}
// Compile parses and compiles given input expression to bytecode program.
func Compile(input string, ops ...Option) (*vm.Program, error) {
config := conf.CreateNew()
for _, op := range ops {
op(config)
}
for name := range config.Disabled {
delete(config.Builtins, name)
}
config.Check()
tree, err := parser.ParseWithConfig(input, config)
if err != nil {
return nil, err
}
if len(config.Visitors) > 0 {
for i := 0; i < 1000; i++ {
more := false
for _, v := range config.Visitors {
// We need to perform types check, because some visitors may rely on
// types information available in the tree.
_, _ = checker.Check(tree, config)
ast.Walk(&tree.Node, v)
if v, ok := v.(interface {
ShouldRepeat() bool
}); ok {
more = more || v.ShouldRepeat()
}
}
if !more {
break
}
}
}
_, err = checker.Check(tree, config)
if err != nil {
return nil, err
}
if config.Optimize {
err = optimizer.Optimize(&tree.Node, config)
if err != nil {
var fileError *file.Error
if errors.As(err, &fileError) {
return nil, fileError.Bind(tree.Source)
}
return nil, err
}
}
program, err := compiler.Compile(tree, config)
if err != nil {
return nil, err
}
return program, nil
}
// Run evaluates given bytecode program.
func Run(program *vm.Program, env any) (any, error) {
return vm.Run(program, env)
}
// Eval parses, compiles and runs given input.
func Eval(input string, env any) (any, error) {
if _, ok := env.(Option); ok {
return nil, fmt.Errorf("misused expr.Eval: second argument (env) should be passed without expr.Env")
}
program, err := Compile(input)
if err != nil {
return nil, err
}
output, err := Run(program, env)
if err != nil {
return nil, err
}
return output, nil
}