forked from jmespath/go-jmespath
-
Notifications
You must be signed in to change notification settings - Fork 10
/
interpreter.go
493 lines (478 loc) · 12.4 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package jmespath
import (
"errors"
"fmt"
"reflect"
"unicode"
"unicode/utf8"
)
// NotFoundError is returned when it is impossible to resolve the AstField
type NotFoundError struct {
key string
}
func (n NotFoundError) Error() string {
return fmt.Sprintf("Unknown key \"%s\" in path", n.key)
}
var DefaultFunctionCaller *FunctionCaller = NewFunctionCaller()
type Interpreter interface {
// Interpret the node and return results
Execute(node ASTNode, value interface{}, opts ...InterpreterOption) (interface{}, error)
}
/*
* This is a tree based interpreter. It walks the AST and directly
* interprets the AST to search through a JSON document.
*/
type treeInterpreter struct{}
func NewInterpreter() *treeInterpreter {
interpreter := treeInterpreter{}
return &interpreter
}
type expRef struct {
ref ASTNode
}
// Execute takes an ASTNode and input data and interprets the AST directly.
// It will produce the result of applying the JMESPath expression associated
// with the ASTNode to the input data "value".
func (intr *treeInterpreter) Execute(node ASTNode, value interface{}, opts ...InterpreterOption) (interface{}, error) {
var o interpreterOptions
for _, opt := range opts {
if opt != nil {
o = opt(o)
}
}
functionCaller := o.functionCaller
if functionCaller == nil {
functionCaller = DefaultFunctionCaller
}
return intr.execute(node, value, functionCaller)
}
func (intr *treeInterpreter) execute(node ASTNode, value interface{}, fCall *FunctionCaller) (interface{}, error) {
switch node.NodeType {
case ASTComparator:
left, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
right, err := intr.execute(node.Children[1], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
switch node.Value {
case tEQ:
return objsEqual(left, right), nil
case tNE:
return !objsEqual(left, right), nil
}
leftNum, ok := left.(float64)
if !ok {
return nil, nil
}
rightNum, ok := right.(float64)
if !ok {
return nil, nil
}
switch node.Value {
case tGT:
return leftNum > rightNum, nil
case tGTE:
return leftNum >= rightNum, nil
case tLT:
return leftNum < rightNum, nil
case tLTE:
return leftNum <= rightNum, nil
}
case ASTExpRef:
return expRef{ref: node.Children[0]}, nil
case ASTFunctionExpression:
if _, ok := node.Value.(string); !ok {
return nil, errors.New("invalid node value type")
}
resolvedArgs := []interface{}{}
for _, arg := range node.Children {
current, err := intr.execute(arg, value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
resolvedArgs = append(resolvedArgs, current)
}
return fCall.CallFunction(node.Value.(string), resolvedArgs, intr)
case ASTField:
if m, ok := value.(map[string]interface{}); ok {
key := node.Value.(string)
if val, ok := m[key]; ok {
return val, nil
} else {
return nil, NotFoundError{key}
}
}
return intr.fieldFromStruct(node.Value.(string), value)
case ASTFilterProjection:
left, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
return nil, nil
}
sliceType, ok := left.([]interface{})
if !ok {
if isSliceType(left) {
return intr.filterProjectionWithReflection(node, left, fCall)
}
return nil, nil
}
compareNode := node.Children[2]
collected := []interface{}{}
for _, element := range sliceType {
result, err := intr.execute(compareNode, element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if !isFalse(result) {
current, err := intr.execute(node.Children[1], element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if current != nil {
collected = append(collected, current)
}
}
}
return collected, nil
case ASTFlatten:
left, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
return nil, nil
}
sliceType, ok := left.([]interface{})
if !ok {
// If we can't type convert to []interface{}, there's
// a chance this could still work via reflection if we're
// dealing with user provided types.
if isSliceType(left) {
return intr.flattenWithReflection(left)
}
return nil, nil
}
flattened := []interface{}{}
for _, element := range sliceType {
if elementSlice, ok := element.([]interface{}); ok {
flattened = append(flattened, elementSlice...)
} else if isSliceType(element) {
reflectFlat := []interface{}{}
v := reflect.ValueOf(element)
for i := 0; i < v.Len(); i++ {
reflectFlat = append(reflectFlat, v.Index(i).Interface())
}
flattened = append(flattened, reflectFlat...)
} else {
flattened = append(flattened, element)
}
}
return flattened, nil
case ASTIdentity, ASTCurrentNode:
return value, nil
case ASTIndex:
if sliceType, ok := value.([]interface{}); ok {
index := node.Value.(int)
if index < 0 {
index += len(sliceType)
}
if index < len(sliceType) && index >= 0 {
return sliceType[index], nil
}
return nil, nil
}
// Otherwise try via reflection.
rv := reflect.ValueOf(value)
if rv.Kind() == reflect.Slice {
index := node.Value.(int)
if index < 0 {
index += rv.Len()
}
if index < rv.Len() && index >= 0 {
v := rv.Index(index)
return v.Interface(), nil
}
}
return nil, nil
case ASTKeyValPair:
return intr.execute(node.Children[0], value, fCall)
case ASTLiteral:
return node.Value, nil
case ASTMultiSelectHash:
if value == nil {
return nil, nil
}
collected := make(map[string]interface{})
for _, child := range node.Children {
current, err := intr.execute(child, value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
key := child.Value.(string)
collected[key] = current
}
return collected, nil
case ASTMultiSelectList:
if value == nil {
return nil, nil
}
collected := []interface{}{}
for _, child := range node.Children {
current, err := intr.execute(child, value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
collected = append(collected, current)
}
return collected, nil
case ASTOrExpression:
matched, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); ok {
matched = nil
} else {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
}
if isFalse(matched) {
matched, err = intr.execute(node.Children[1], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
}
return matched, nil
case ASTAndExpression:
matched, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if isFalse(matched) {
return matched, nil
}
return intr.execute(node.Children[1], value, fCall)
case ASTNotExpression:
matched, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if isFalse(matched) {
return true, nil
}
return false, nil
case ASTPipe:
result := value
var err error
for _, child := range node.Children {
result, err = intr.execute(child, result, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
}
return result, nil
case ASTProjection:
left, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
sliceType, ok := left.([]interface{})
if !ok {
if isSliceType(left) {
return intr.projectWithReflection(node, left, fCall)
}
return nil, nil
}
collected := []interface{}{}
var current interface{}
for _, element := range sliceType {
current, err = intr.execute(node.Children[1], element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if current != nil {
collected = append(collected, current)
}
}
return collected, nil
case ASTSubexpression, ASTIndexExpression:
left, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
return nil, err
}
return intr.execute(node.Children[1], left, fCall)
case ASTSlice:
sliceType, ok := value.([]interface{})
if !ok {
if isSliceType(value) {
return intr.sliceWithReflection(node, value)
}
return nil, nil
}
parts := node.Value.([]*int)
sliceParams := make([]sliceParam, 3)
for i, part := range parts {
if part != nil {
sliceParams[i].Specified = true
sliceParams[i].N = *part
}
}
return slice(sliceType, sliceParams)
case ASTValueProjection:
left, err := intr.execute(node.Children[0], value, fCall)
if err != nil {
return nil, nil
}
mapType, ok := left.(map[string]interface{})
if !ok {
return nil, nil
}
values := make([]interface{}, len(mapType))
for _, value := range mapType {
values = append(values, value)
}
collected := []interface{}{}
for _, element := range values {
current, err := intr.execute(node.Children[1], element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if current != nil {
collected = append(collected, current)
}
}
return collected, nil
}
return nil, errors.New("Unknown AST node: " + node.NodeType.String())
}
func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) {
rv := reflect.ValueOf(value)
first, n := utf8.DecodeRuneInString(key)
fieldName := string(unicode.ToUpper(first)) + key[n:]
if rv.Kind() == reflect.Struct {
v := rv.FieldByName(fieldName)
if !v.IsValid() {
return nil, nil
}
return v.Interface(), nil
} else if rv.Kind() == reflect.Ptr {
// Handle multiple levels of indirection?
if rv.IsNil() {
return nil, nil
}
rv = rv.Elem()
v := rv.FieldByName(fieldName)
if !v.IsValid() {
return nil, nil
}
return v.Interface(), nil
}
return nil, nil
}
func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) {
v := reflect.ValueOf(value)
flattened := []interface{}{}
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
if reflect.TypeOf(element).Kind() == reflect.Slice {
// Then insert the contents of the element
// slice into the flattened slice,
// i.e flattened = append(flattened, mySlice...)
elementV := reflect.ValueOf(element)
for j := 0; j < elementV.Len(); j++ {
flattened = append(
flattened, elementV.Index(j).Interface())
}
} else {
flattened = append(flattened, element)
}
}
return flattened, nil
}
func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) {
v := reflect.ValueOf(value)
parts := node.Value.([]*int)
sliceParams := make([]sliceParam, 3)
for i, part := range parts {
if part != nil {
sliceParams[i].Specified = true
sliceParams[i].N = *part
}
}
final := []interface{}{}
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
final = append(final, element)
}
return slice(final, sliceParams)
}
func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}, fCall *FunctionCaller) (interface{}, error) {
compareNode := node.Children[2]
collected := []interface{}{}
v := reflect.ValueOf(value)
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
result, err := intr.execute(compareNode, element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if !isFalse(result) {
current, err := intr.execute(node.Children[1], element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if current != nil {
collected = append(collected, current)
}
}
}
return collected, nil
}
func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}, fCall *FunctionCaller) (interface{}, error) {
collected := []interface{}{}
v := reflect.ValueOf(value)
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
result, err := intr.execute(node.Children[1], element, fCall)
if err != nil {
if _, ok := err.(NotFoundError); !ok {
return nil, err
}
}
if result != nil {
collected = append(collected, result)
}
}
return collected, nil
}