-
Notifications
You must be signed in to change notification settings - Fork 3
/
interpreter.go
475 lines (458 loc) · 11.9 KB
/
interpreter.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package mexpr
import (
"math"
"strings"
)
// InterpreterOption passes configuration settings when creating a new
// interpreter instance.
type InterpreterOption int
const (
// StrictMode does extra checks like making sure identifiers exist.
StrictMode InterpreterOption = iota
// UnqoutedStrings enables the use of unquoted string values rather than
// returning nil or a missing identifier error. Identifiers get priority
// over unquoted strings.
UnquotedStrings
)
// mapValues returns the values of the map m.
// The values will be in an indeterminate order.
func mapValues[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
// checkBounds returns an error if the index is out of bounds.
func checkBounds(ast *Node, input any, idx int) Error {
if v, ok := input.([]any); ok {
if idx < 0 || idx >= len(v) {
return NewError(ast.Offset, ast.Length, "invalid index %d for slice of length %d", int(idx), len(v))
}
}
if v, ok := input.(string); ok {
if idx < 0 || idx >= len(v) {
return NewError(ast.Offset, ast.Length, "invalid index %d for string of length %d", int(idx), len(v))
}
}
return nil
}
// Interpreter executes expression AST programs.
type Interpreter interface {
Run(value any) (any, Error)
}
// NewInterpreter returns an interpreter for the given AST.
func NewInterpreter(ast *Node, options ...InterpreterOption) Interpreter {
strict := false
unquoted := false
for _, opt := range options {
switch opt {
case StrictMode:
strict = true
case UnquotedStrings:
unquoted = true
}
}
return &interpreter{
ast: ast,
strict: strict,
unquoted: unquoted,
}
}
type interpreter struct {
ast *Node
prevFieldSelect bool
strict bool
unquoted bool
}
func (i *interpreter) Run(value any) (any, Error) {
return i.run(i.ast, value)
}
func (i *interpreter) run(ast *Node, value any) (any, Error) {
if ast == nil {
return nil, nil
}
fromSelect := i.prevFieldSelect
i.prevFieldSelect = false
switch ast.Type {
case NodeIdentifier:
switch ast.Value.(string) {
case "@":
return value, nil
case "length":
// Special pseudo-property to get the value's length.
if s, ok := value.(string); ok {
return len(s), nil
}
if a, ok := value.([]any); ok {
return len(a), nil
}
case "lower":
if s, ok := value.(string); ok {
return strings.ToLower(s), nil
}
case "upper":
if s, ok := value.(string); ok {
return strings.ToUpper(s), nil
}
}
if m, ok := value.(map[string]any); ok {
if v, ok := m[ast.Value.(string)]; ok {
return v, nil
}
}
if m, ok := value.(map[any]any); ok {
if v, ok := m[ast.Value]; ok {
return v, nil
}
}
if i.unquoted && !fromSelect {
// Identifiers not found in the map are treated as strings, but only if
// the previous item was not a `.` like `obj.field`.
return ast.Value.(string), nil
}
if !i.strict {
return nil, nil
}
return nil, NewError(ast.Offset, ast.Length, "cannot get %v from %v", ast.Value, value)
case NodeFieldSelect:
i.prevFieldSelect = true
leftValue, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
i.prevFieldSelect = true
return i.run(ast.Right, leftValue)
case NodeArrayIndex:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
if !isSlice(resultLeft) && !isString(resultLeft) {
return nil, NewError(ast.Offset, ast.Length, "can only index strings or arrays but got %v", resultLeft)
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
if isSlice(resultRight) && len(resultRight.([]any)) == 2 {
start, err := toNumber(ast, resultRight.([]any)[0])
if err != nil {
return nil, err
}
end, err := toNumber(ast, resultRight.([]any)[1])
if err != nil {
return nil, err
}
if left, ok := resultLeft.([]any); ok {
if start < 0 {
start += float64(len(left))
}
if end < 0 {
end += float64(len(left))
}
if err := checkBounds(ast, left, int(start)); err != nil {
return nil, err
}
if err := checkBounds(ast, left, int(end)); err != nil {
return nil, err
}
if int(start) > int(end) {
return nil, NewError(ast.Offset, ast.Length, "slice start cannot be greater than end")
}
return left[int(start) : int(end)+1], nil
}
left := toString(resultLeft)
if start < 0 {
start += float64(len(left))
}
if end < 0 {
end += float64(len(left))
}
if err := checkBounds(ast, left, int(start)); err != nil {
return nil, err
}
if int(start) > int(end) {
return nil, NewError(ast.Offset, ast.Length, "string slice start cannot be greater than end")
}
if err := checkBounds(ast, left, int(end)); err != nil {
return nil, err
}
return left[int(start) : int(end)+1], nil
}
if isNumber(resultRight) {
idx, err := toNumber(ast, resultRight)
if err != nil {
return nil, err
}
if left, ok := resultLeft.([]any); ok {
if idx < 0 {
idx += float64(len(left))
}
if err := checkBounds(ast, left, int(idx)); err != nil {
return nil, err
}
return left[int(idx)], nil
}
left := toString(resultLeft)
if idx < 0 {
idx += float64(len(left))
}
if err := checkBounds(ast, left, int(idx)); err != nil {
return nil, err
}
return string(left[int(idx)]), nil
}
return nil, NewError(ast.Offset, ast.Length, "array index must be number or slice %v", resultRight)
case NodeSlice:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
ast.Value.([]any)[0] = resultLeft
ast.Value.([]any)[1] = resultRight
return ast.Value, nil
case NodeLiteral:
return ast.Value, nil
case NodeSign:
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
right, err := toNumber(ast, resultRight)
if err != nil {
return nil, err
}
if ast.Value.(string) == "-" {
right = -right
}
return right, nil
case NodeAdd, NodeSubtract, NodeMultiply, NodeDivide, NodeModulus, NodePower:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
if ast.Type == NodeAdd {
if isString(resultLeft) || isString(resultRight) {
return toString(resultLeft) + toString(resultRight), nil
}
if isSlice(resultLeft) && isSlice(resultRight) {
tmp := append([]any{}, resultLeft.([]any)...)
return append(tmp, resultRight.([]any)...), nil
}
}
if isNumber(resultLeft) && isNumber(resultRight) {
left, err := toNumber(ast.Left, resultLeft)
if err != nil {
return nil, err
}
right, err := toNumber(ast.Right, resultRight)
if err != nil {
return nil, err
}
switch ast.Type {
case NodeAdd:
return left + right, nil
case NodeSubtract:
return left - right, nil
case NodeMultiply:
return left * right, nil
case NodeDivide:
if right == 0.0 {
return nil, NewError(ast.Offset, ast.Length, "cannot divide by zero")
}
return left / right, nil
case NodeModulus:
if int(right) == 0 {
return nil, NewError(ast.Offset, ast.Length, "cannot divide by zero")
}
return int(left) % int(right), nil
case NodePower:
return math.Pow(left, right), nil
}
}
return nil, NewError(ast.Offset, ast.Length, "cannot add incompatible types %v and %v", resultLeft, resultRight)
case NodeEqual, NodeNotEqual, NodeLessThan, NodeLessThanEqual, NodeGreaterThan, NodeGreaterThanEqual:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
if ast.Type == NodeEqual {
return deepEqual(resultLeft, resultRight), nil
}
if ast.Type == NodeNotEqual {
return !deepEqual(resultLeft, resultRight), nil
}
left, err := toNumber(ast.Left, resultLeft)
if err != nil {
return nil, err
}
right, err := toNumber(ast.Right, resultRight)
if err != nil {
return nil, err
}
switch ast.Type {
case NodeGreaterThan:
return left > right, nil
case NodeGreaterThanEqual:
return left >= right, nil
case NodeLessThan:
return left < right, nil
case NodeLessThanEqual:
return left <= right, nil
}
case NodeAnd, NodeOr:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
left := toBool(resultLeft)
right := toBool(resultRight)
switch ast.Type {
case NodeAnd:
return left && right, nil
case NodeOr:
return left || right, nil
}
case NodeBefore, NodeAfter:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
leftTime := toTime(resultLeft)
if leftTime.IsZero() {
return nil, NewError(ast.Offset, ast.Length, "unable to convert %v to date or time", resultLeft)
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
rightTime := toTime(resultRight)
if rightTime.IsZero() {
return nil, NewError(ast.Offset, ast.Length, "unable to convert %v to date or time", resultRight)
}
if ast.Type == NodeBefore {
return leftTime.Before(rightTime), nil
} else {
return leftTime.After(rightTime), nil
}
case NodeIn, NodeContains, NodeStartsWith, NodeEndsWith:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
switch ast.Type {
case NodeIn:
if a, ok := resultRight.([]any); ok {
for _, item := range a {
if deepEqual(item, resultLeft) {
return true, nil
}
}
return false, nil
}
if m, ok := resultRight.(map[string]any); ok {
if m[toString(resultLeft)] != nil {
return true, nil
}
return false, nil
}
if m, ok := resultRight.(map[any]any); ok {
if m[resultLeft] != nil {
return true, nil
}
return false, nil
}
return strings.Contains(toString(resultRight), toString(resultLeft)), nil
case NodeContains:
if a, ok := resultLeft.([]any); ok {
for _, item := range a {
if deepEqual(item, resultRight) {
return true, nil
}
}
return false, nil
}
if m, ok := resultLeft.(map[string]any); ok {
if m[toString(resultRight)] != nil {
return true, nil
}
return false, nil
}
if m, ok := resultLeft.(map[any]any); ok {
if m[resultRight] != nil {
return true, nil
}
return false, nil
}
return strings.Contains(toString(resultLeft), toString(resultRight)), nil
case NodeStartsWith:
return strings.HasPrefix(toString(resultLeft), toString(resultRight)), nil
case NodeEndsWith:
return strings.HasSuffix(toString(resultLeft), toString(resultRight)), nil
}
case NodeNot:
resultRight, err := i.run(ast.Right, value)
if err != nil {
return nil, err
}
right := toBool(resultRight)
return !right, nil
case NodeWhere:
resultLeft, err := i.run(ast.Left, value)
if err != nil {
return nil, err
}
results := []any{}
if resultLeft == nil {
return nil, nil
}
if m, ok := resultLeft.(map[string]any); ok {
resultLeft = mapValues(m)
}
if m, ok := resultLeft.(map[any]any); ok {
values := make([]any, 0, len(m))
for _, v := range m {
values = append(values, v)
}
resultLeft = values
}
if leftSlice, ok := resultLeft.([]any); ok {
for _, item := range leftSlice {
// In an unquoted string scenario it makes no sense for the first/only
// token after a `where` clause to be treated as a string. Instead we
// treat a `where` the same as a field select `.` in this scenario.
i.prevFieldSelect = true
resultRight, err := i.run(ast.Right, item)
if i.strict && err != nil {
return nil, err
}
if toBool(resultRight) {
results = append(results, item)
}
}
}
return results, nil
}
return nil, nil
}