aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/goccy/go-json/internal/decoder/path.go
blob: a15ff69e3cd80f152a4f426a28cf72763cd770f9 (plain) (blame)
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
package decoder

import (
	"fmt"
	"reflect"
	"strconv"

	"github.com/goccy/go-json/internal/errors"
	"github.com/goccy/go-json/internal/runtime"
)

type PathString string

func (s PathString) Build() (*Path, error) {
	builder := new(PathBuilder)
	return builder.Build([]rune(s))
}

type PathBuilder struct {
	root                    PathNode
	node                    PathNode
	singleQuotePathSelector bool
	doubleQuotePathSelector bool
}

func (b *PathBuilder) Build(buf []rune) (*Path, error) {
	node, err := b.build(buf)
	if err != nil {
		return nil, err
	}
	return &Path{
		node:                    node,
		RootSelectorOnly:        node == nil,
		SingleQuotePathSelector: b.singleQuotePathSelector,
		DoubleQuotePathSelector: b.doubleQuotePathSelector,
	}, nil
}

func (b *PathBuilder) build(buf []rune) (PathNode, error) {
	if len(buf) == 0 {
		return nil, errors.ErrEmptyPath()
	}
	if buf[0] != '$' {
		return nil, errors.ErrInvalidPath("JSON Path must start with a $ character")
	}
	if len(buf) == 1 {
		return nil, nil
	}
	buf = buf[1:]
	offset, err := b.buildNext(buf)
	if err != nil {
		return nil, err
	}
	if len(buf) > offset {
		return nil, errors.ErrInvalidPath("remain invalid path %q", buf[offset:])
	}
	return b.root, nil
}

func (b *PathBuilder) buildNextCharIfExists(buf []rune, cursor int) (int, error) {
	if len(buf) > cursor {
		offset, err := b.buildNext(buf[cursor:])
		if err != nil {
			return 0, err
		}
		return cursor + 1 + offset, nil
	}
	return cursor, nil
}

func (b *PathBuilder) buildNext(buf []rune) (int, error) {
	switch buf[0] {
	case '.':
		if len(buf) == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with dot character")
		}
		offset, err := b.buildSelector(buf[1:])
		if err != nil {
			return 0, err
		}
		return offset + 1, nil
	case '[':
		if len(buf) == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with left bracket character")
		}
		offset, err := b.buildIndex(buf[1:])
		if err != nil {
			return 0, err
		}
		return offset + 1, nil
	default:
		return 0, errors.ErrInvalidPath("expect dot or left bracket character. but found %c character", buf[0])
	}
}

func (b *PathBuilder) buildSelector(buf []rune) (int, error) {
	switch buf[0] {
	case '.':
		if len(buf) == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with double dot character")
		}
		offset, err := b.buildPathRecursive(buf[1:])
		if err != nil {
			return 0, err
		}
		return 1 + offset, nil
	case '[', ']', '$', '*':
		return 0, errors.ErrInvalidPath("found invalid path character %c after dot", buf[0])
	}
	for cursor := 0; cursor < len(buf); cursor++ {
		switch buf[cursor] {
		case '$', '*', ']':
			return 0, errors.ErrInvalidPath("found %c character in field selector context", buf[cursor])
		case '.':
			if cursor+1 >= len(buf) {
				return 0, errors.ErrInvalidPath("JSON Path ends with dot character")
			}
			selector := buf[:cursor]
			b.addSelectorNode(string(selector))
			offset, err := b.buildSelector(buf[cursor+1:])
			if err != nil {
				return 0, err
			}
			return cursor + 1 + offset, nil
		case '[':
			if cursor+1 >= len(buf) {
				return 0, errors.ErrInvalidPath("JSON Path ends with left bracket character")
			}
			selector := buf[:cursor]
			b.addSelectorNode(string(selector))
			offset, err := b.buildIndex(buf[cursor+1:])
			if err != nil {
				return 0, err
			}
			return cursor + 1 + offset, nil
		case '"':
			if cursor+1 >= len(buf) {
				return 0, errors.ErrInvalidPath("JSON Path ends with double quote character")
			}
			offset, err := b.buildQuoteSelector(buf[cursor+1:], DoubleQuotePathSelector)
			if err != nil {
				return 0, err
			}
			return cursor + 1 + offset, nil
		}
	}
	b.addSelectorNode(string(buf))
	return len(buf), nil
}

func (b *PathBuilder) buildQuoteSelector(buf []rune, sel QuotePathSelector) (int, error) {
	switch buf[0] {
	case '[', ']', '$', '.', '*', '\'', '"':
		return 0, errors.ErrInvalidPath("found invalid path character %c after quote", buf[0])
	}
	for cursor := 0; cursor < len(buf); cursor++ {
		switch buf[cursor] {
		case '\'':
			if sel != SingleQuotePathSelector {
				return 0, errors.ErrInvalidPath("found double quote character in field selector with single quote context")
			}
			if len(buf) <= cursor+1 {
				return 0, errors.ErrInvalidPath("JSON Path ends with single quote character in field selector context")
			}
			if buf[cursor+1] != ']' {
				return 0, errors.ErrInvalidPath("expect right bracket for field selector with single quote but found %c", buf[cursor+1])
			}
			selector := buf[:cursor]
			b.addSelectorNode(string(selector))
			b.singleQuotePathSelector = true
			return b.buildNextCharIfExists(buf, cursor+2)
		case '"':
			if sel != DoubleQuotePathSelector {
				return 0, errors.ErrInvalidPath("found single quote character in field selector with double quote context")
			}
			selector := buf[:cursor]
			b.addSelectorNode(string(selector))
			b.doubleQuotePathSelector = true
			return b.buildNextCharIfExists(buf, cursor+1)
		}
	}
	return 0, errors.ErrInvalidPath("couldn't find quote character in selector quote path context")
}

func (b *PathBuilder) buildPathRecursive(buf []rune) (int, error) {
	switch buf[0] {
	case '.', '[', ']', '$', '*':
		return 0, errors.ErrInvalidPath("found invalid path character %c after double dot", buf[0])
	}
	for cursor := 0; cursor < len(buf); cursor++ {
		switch buf[cursor] {
		case '$', '*', ']':
			return 0, errors.ErrInvalidPath("found %c character in field selector context", buf[cursor])
		case '.':
			if cursor+1 >= len(buf) {
				return 0, errors.ErrInvalidPath("JSON Path ends with dot character")
			}
			selector := buf[:cursor]
			b.addRecursiveNode(string(selector))
			offset, err := b.buildSelector(buf[cursor+1:])
			if err != nil {
				return 0, err
			}
			return cursor + 1 + offset, nil
		case '[':
			if cursor+1 >= len(buf) {
				return 0, errors.ErrInvalidPath("JSON Path ends with left bracket character")
			}
			selector := buf[:cursor]
			b.addRecursiveNode(string(selector))
			offset, err := b.buildIndex(buf[cursor+1:])
			if err != nil {
				return 0, err
			}
			return cursor + 1 + offset, nil
		}
	}
	b.addRecursiveNode(string(buf))
	return len(buf), nil
}

func (b *PathBuilder) buildIndex(buf []rune) (int, error) {
	switch buf[0] {
	case '.', '[', ']', '$':
		return 0, errors.ErrInvalidPath("found invalid path character %c after left bracket", buf[0])
	case '\'':
		if len(buf) == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with single quote character")
		}
		offset, err := b.buildQuoteSelector(buf[1:], SingleQuotePathSelector)
		if err != nil {
			return 0, err
		}
		return 1 + offset, nil
	case '*':
		if len(buf) == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with star character")
		}
		if buf[1] != ']' {
			return 0, errors.ErrInvalidPath("expect right bracket character for index all path but found %c character", buf[1])
		}
		b.addIndexAllNode()
		offset := len("*]")
		if len(buf) > 2 {
			buildOffset, err := b.buildNext(buf[2:])
			if err != nil {
				return 0, err
			}
			return offset + buildOffset, nil
		}
		return offset, nil
	}

	for cursor := 0; cursor < len(buf); cursor++ {
		switch buf[cursor] {
		case ']':
			index, err := strconv.ParseInt(string(buf[:cursor]), 10, 64)
			if err != nil {
				return 0, errors.ErrInvalidPath("%q is unexpected index path", buf[:cursor])
			}
			b.addIndexNode(int(index))
			return b.buildNextCharIfExists(buf, cursor+1)
		}
	}
	return 0, errors.ErrInvalidPath("couldn't find right bracket character in index path context")
}

func (b *PathBuilder) addIndexAllNode() {
	node := newPathIndexAllNode()
	if b.root == nil {
		b.root = node
		b.node = node
	} else {
		b.node = b.node.chain(node)
	}
}

func (b *PathBuilder) addRecursiveNode(selector string) {
	node := newPathRecursiveNode(selector)
	if b.root == nil {
		b.root = node
		b.node = node
	} else {
		b.node = b.node.chain(node)
	}
}

func (b *PathBuilder) addSelectorNode(name string) {
	node := newPathSelectorNode(name)
	if b.root == nil {
		b.root = node
		b.node = node
	} else {
		b.node = b.node.chain(node)
	}
}

func (b *PathBuilder) addIndexNode(idx int) {
	node := newPathIndexNode(idx)
	if b.root == nil {
		b.root = node
		b.node = node
	} else {
		b.node = b.node.chain(node)
	}
}

type QuotePathSelector int

const (
	SingleQuotePathSelector QuotePathSelector = 1
	DoubleQuotePathSelector QuotePathSelector = 2
)

type Path struct {
	node                    PathNode
	RootSelectorOnly        bool
	SingleQuotePathSelector bool
	DoubleQuotePathSelector bool
}

func (p *Path) Field(sel string) (PathNode, bool, error) {
	if p.node == nil {
		return nil, false, nil
	}
	return p.node.Field(sel)
}

func (p *Path) Get(src, dst reflect.Value) error {
	if p.node == nil {
		return nil
	}
	return p.node.Get(src, dst)
}

func (p *Path) String() string {
	if p.node == nil {
		return "$"
	}
	return p.node.String()
}

type PathNode interface {
	fmt.Stringer
	Index(idx int) (PathNode, bool, error)
	Field(fieldName string) (PathNode, bool, error)
	Get(src, dst reflect.Value) error
	chain(PathNode) PathNode
	target() bool
	single() bool
}

type BasePathNode struct {
	child PathNode
}

func (n *BasePathNode) chain(node PathNode) PathNode {
	n.child = node
	return node
}

func (n *BasePathNode) target() bool {
	return n.child == nil
}

func (n *BasePathNode) single() bool {
	return true
}

type PathSelectorNode struct {
	*BasePathNode
	selector string
}

func newPathSelectorNode(selector string) *PathSelectorNode {
	return &PathSelectorNode{
		BasePathNode: &BasePathNode{},
		selector:     selector,
	}
}

func (n *PathSelectorNode) Index(idx int) (PathNode, bool, error) {
	return nil, false, &errors.PathError{}
}

func (n *PathSelectorNode) Field(fieldName string) (PathNode, bool, error) {
	if n.selector == fieldName {
		return n.child, true, nil
	}
	return nil, false, nil
}

func (n *PathSelectorNode) Get(src, dst reflect.Value) error {
	switch src.Type().Kind() {
	case reflect.Map:
		iter := src.MapRange()
		for iter.Next() {
			key, ok := iter.Key().Interface().(string)
			if !ok {
				return fmt.Errorf("invalid map key type %T", src.Type().Key())
			}
			child, found, err := n.Field(key)
			if err != nil {
				return err
			}
			if found {
				if child != nil {
					return child.Get(iter.Value(), dst)
				}
				return AssignValue(iter.Value(), dst)
			}
		}
	case reflect.Struct:
		typ := src.Type()
		for i := 0; i < typ.Len(); i++ {
			tag := runtime.StructTagFromField(typ.Field(i))
			child, found, err := n.Field(tag.Key)
			if err != nil {
				return err
			}
			if found {
				if child != nil {
					return child.Get(src.Field(i), dst)
				}
				return AssignValue(src.Field(i), dst)
			}
		}
	case reflect.Ptr:
		return n.Get(src.Elem(), dst)
	case reflect.Interface:
		return n.Get(reflect.ValueOf(src.Interface()), dst)
	case reflect.Float64, reflect.String, reflect.Bool:
		return AssignValue(src, dst)
	}
	return fmt.Errorf("failed to get %s value from %s", n.selector, src.Type())
}

func (n *PathSelectorNode) String() string {
	s := fmt.Sprintf(".%s", n.selector)
	if n.child != nil {
		s += n.child.String()
	}
	return s
}

type PathIndexNode struct {
	*BasePathNode
	selector int
}

func newPathIndexNode(selector int) *PathIndexNode {
	return &PathIndexNode{
		BasePathNode: &BasePathNode{},
		selector:     selector,
	}
}

func (n *PathIndexNode) Index(idx int) (PathNode, bool, error) {
	if n.selector == idx {
		return n.child, true, nil
	}
	return nil, false, nil
}

func (n *PathIndexNode) Field(fieldName string) (PathNode, bool, error) {
	return nil, false, &errors.PathError{}
}

func (n *PathIndexNode) Get(src, dst reflect.Value) error {
	switch src.Type().Kind() {
	case reflect.Array, reflect.Slice:
		if src.Len() > n.selector {
			if n.child != nil {
				return n.child.Get(src.Index(n.selector), dst)
			}
			return AssignValue(src.Index(n.selector), dst)
		}
	case reflect.Ptr:
		return n.Get(src.Elem(), dst)
	case reflect.Interface:
		return n.Get(reflect.ValueOf(src.Interface()), dst)
	}
	return fmt.Errorf("failed to get [%d] value from %s", n.selector, src.Type())
}

func (n *PathIndexNode) String() string {
	s := fmt.Sprintf("[%d]", n.selector)
	if n.child != nil {
		s += n.child.String()
	}
	return s
}

type PathIndexAllNode struct {
	*BasePathNode
}

func newPathIndexAllNode() *PathIndexAllNode {
	return &PathIndexAllNode{
		BasePathNode: &BasePathNode{},
	}
}

func (n *PathIndexAllNode) Index(idx int) (PathNode, bool, error) {
	return n.child, true, nil
}

func (n *PathIndexAllNode) Field(fieldName string) (PathNode, bool, error) {
	return nil, false, &errors.PathError{}
}

func (n *PathIndexAllNode) Get(src, dst reflect.Value) error {
	switch src.Type().Kind() {
	case reflect.Array, reflect.Slice:
		var arr []interface{}
		for i := 0; i < src.Len(); i++ {
			var v interface{}
			rv := reflect.ValueOf(&v)
			if n.child != nil {
				if err := n.child.Get(src.Index(i), rv); err != nil {
					return err
				}
			} else {
				if err := AssignValue(src.Index(i), rv); err != nil {
					return err
				}
			}
			arr = append(arr, v)
		}
		if err := AssignValue(reflect.ValueOf(arr), dst); err != nil {
			return err
		}
		return nil
	case reflect.Ptr:
		return n.Get(src.Elem(), dst)
	case reflect.Interface:
		return n.Get(reflect.ValueOf(src.Interface()), dst)
	}
	return fmt.Errorf("failed to get all value from %s", src.Type())
}

func (n *PathIndexAllNode) String() string {
	s := "[*]"
	if n.child != nil {
		s += n.child.String()
	}
	return s
}

type PathRecursiveNode struct {
	*BasePathNode
	selector string
}

func newPathRecursiveNode(selector string) *PathRecursiveNode {
	node := newPathSelectorNode(selector)
	return &PathRecursiveNode{
		BasePathNode: &BasePathNode{
			child: node,
		},
		selector: selector,
	}
}

func (n *PathRecursiveNode) Field(fieldName string) (PathNode, bool, error) {
	if n.selector == fieldName {
		return n.child, true, nil
	}
	return nil, false, nil
}

func (n *PathRecursiveNode) Index(_ int) (PathNode, bool, error) {
	return n, true, nil
}

func valueToSliceValue(v interface{}) []interface{} {
	rv := reflect.ValueOf(v)
	ret := []interface{}{}
	if rv.Type().Kind() == reflect.Slice || rv.Type().Kind() == reflect.Array {
		for i := 0; i < rv.Len(); i++ {
			ret = append(ret, rv.Index(i).Interface())
		}
		return ret
	}
	return []interface{}{v}
}

func (n *PathRecursiveNode) Get(src, dst reflect.Value) error {
	if n.child == nil {
		return fmt.Errorf("failed to get by recursive path ..%s", n.selector)
	}
	var arr []interface{}
	switch src.Type().Kind() {
	case reflect.Map:
		iter := src.MapRange()
		for iter.Next() {
			key, ok := iter.Key().Interface().(string)
			if !ok {
				return fmt.Errorf("invalid map key type %T", src.Type().Key())
			}
			child, found, err := n.Field(key)
			if err != nil {
				return err
			}
			if found {
				var v interface{}
				rv := reflect.ValueOf(&v)
				_ = child.Get(iter.Value(), rv)
				arr = append(arr, valueToSliceValue(v)...)
			} else {
				var v interface{}
				rv := reflect.ValueOf(&v)
				_ = n.Get(iter.Value(), rv)
				if v != nil {
					arr = append(arr, valueToSliceValue(v)...)
				}
			}
		}
		_ = AssignValue(reflect.ValueOf(arr), dst)
		return nil
	case reflect.Struct:
		typ := src.Type()
		for i := 0; i < typ.Len(); i++ {
			tag := runtime.StructTagFromField(typ.Field(i))
			child, found, err := n.Field(tag.Key)
			if err != nil {
				return err
			}
			if found {
				var v interface{}
				rv := reflect.ValueOf(&v)
				_ = child.Get(src.Field(i), rv)
				arr = append(arr, valueToSliceValue(v)...)
			} else {
				var v interface{}
				rv := reflect.ValueOf(&v)
				_ = n.Get(src.Field(i), rv)
				if v != nil {
					arr = append(arr, valueToSliceValue(v)...)
				}
			}
		}
		_ = AssignValue(reflect.ValueOf(arr), dst)
		return nil
	case reflect.Array, reflect.Slice:
		for i := 0; i < src.Len(); i++ {
			var v interface{}
			rv := reflect.ValueOf(&v)
			_ = n.Get(src.Index(i), rv)
			if v != nil {
				arr = append(arr, valueToSliceValue(v)...)
			}
		}
		_ = AssignValue(reflect.ValueOf(arr), dst)
		return nil
	case reflect.Ptr:
		return n.Get(src.Elem(), dst)
	case reflect.Interface:
		return n.Get(reflect.ValueOf(src.Interface()), dst)
	}
	return fmt.Errorf("failed to get %s value from %s", n.selector, src.Type())
}

func (n *PathRecursiveNode) String() string {
	s := fmt.Sprintf("..%s", n.selector)
	if n.child != nil {
		s += n.child.String()
	}
	return s
}