forked from go-xmlpath/xmlpath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.go
900 lines (838 loc) · 18.5 KB
/
path.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
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
package xmlpath
import (
"fmt"
"strconv"
"unicode/utf8"
)
// Path is a compiled path that can be applied to a context
// node to obtain a matching node set.
// A single Path can be applied concurrently to any number
// of context nodes.
type Path struct {
path string
steps []pathStep
}
// Iter returns an iterator that goes over the list of nodes
// that p matches on the given context.
func (p *Path) Iter(context *Node) *Iter {
iter := Iter{
make([]pathStepState, len(p.steps)),
make([]bool, len(context.nodes)),
}
for i := range p.steps {
iter.state[i].step = &p.steps[i]
}
iter.state[0].init(context)
return &iter
}
// Exists returns whether any nodes match p on the given context.
func (p *Path) Exists(context *Node) bool {
return p.Iter(context).Next()
}
// String returns the string value of the first node matched
// by p on the given context.
//
// See the documentation of Node.String.
func (p *Path) String(context *Node) (s string, ok bool) {
iter := p.Iter(context)
if iter.Next() {
return iter.Node().String(), true
}
return "", false
}
// Bytes returns as a byte slice the string value of the first
// node matched by p on the given context.
//
// See the documentation of Node.String.
func (p *Path) Bytes(node *Node) (b []byte, ok bool) {
iter := p.Iter(node)
if iter.Next() {
return iter.Node().Bytes(), true
}
return nil, false
}
// Iter iterates over node sets.
type Iter struct {
state []pathStepState
seen []bool
}
// Node returns the current node.
// Must only be called after Iter.Next returns true.
func (iter *Iter) Node() *Node {
state := iter.state[len(iter.state)-1]
if state.pos == 0 {
panic("Iter.Node called before Iter.Next")
}
if state.node == nil {
panic("Iter.Node called after Iter.Next false")
}
return state.node
}
// Next iterates to the next node in the set, if any, and
// returns whether there is a node available.
func (iter *Iter) Next() bool {
tip := len(iter.state) - 1
outer:
for {
for !iter.state[tip].next() {
tip--
if tip == -1 {
return false
}
}
for tip < len(iter.state)-1 {
tip++
iter.state[tip].init(iter.state[tip-1].node)
if !iter.state[tip].next() {
tip--
continue outer
}
}
if iter.seen[iter.state[tip].node.pos] {
continue
}
iter.seen[iter.state[tip].node.pos] = true
return true
}
panic("unreachable")
}
type pathStepState struct {
step *pathStep
node *Node
pos int
idx int
aux int
}
func (s *pathStepState) init(node *Node) {
s.node = node
s.pos = 0
s.idx = 0
s.aux = 0
}
func (s *pathStepState) next() bool {
for s._next() {
s.pos++
if s.step.pred == nil || s.test(s.step.pred) {
return true
}
}
return false
}
func (s *pathStepState) test(pred predicate) bool {
switch pred := pred.(type) {
case positionPredicate:
if pred.operator(pred.pos, s.pos) {
return true
}
case existsPredicate:
if pred.path.Exists(s.node) {
return true
}
case equalsPredicate:
iter := pred.path.Iter(s.node)
for iter.Next() {
if iter.Node().equals(pred.value) {
return true
}
}
case notequalsPredicate:
iter := pred.path.Iter(s.node)
for iter.Next() {
if !iter.Node().equals(pred.value) {
return true
}
}
case containsPredicate:
iter := pred.path.Iter(s.node)
for iter.Next() {
if iter.Node().contains(pred.value) {
return true
}
}
case startsWithPredicate:
iter := pred.path.Iter(s.node)
for iter.Next() {
if iter.Node().startsWith(pred.value) {
return true
}
}
case notPredicate:
return !s.test(pred.uniSub)
case andPredicate:
for _, sub := range pred.sub {
if !s.test(sub) {
return false
}
}
return true
case orPredicate:
for _, sub := range pred.sub {
if s.test(sub) {
return true
}
}
default:
panic(fmt.Sprintf("internal error: unknown predicate type: %#v", s.step.pred))
}
return false
}
func (s *pathStepState) _next() bool {
if s.node == nil {
return false
}
if s.step.root && s.idx == 0 {
for s.node.up != nil {
s.node = s.node.up
}
}
switch s.step.axis {
case "self":
if s.idx == 0 && s.step.match(s.node) {
s.idx++
return true
}
case "parent":
if s.idx == 0 && s.node.up != nil && s.step.match(s.node.up) {
s.idx++
s.node = s.node.up
return true
}
case "ancestor", "ancestor-or-self":
if s.idx == 0 && s.step.axis == "ancestor-or-self" {
s.idx++
if s.step.match(s.node) {
return true
}
}
for s.node.up != nil {
s.node = s.node.up
s.idx++
if s.step.match(s.node) {
return true
}
}
case "child":
var down []*Node
if s.idx == 0 {
down = s.node.down
} else {
down = s.node.up.down
}
for s.idx < len(down) {
node := down[s.idx]
s.idx++
if s.step.match(node) {
s.node = node
return true
}
}
case "descendant", "descendant-or-self":
if s.idx == 0 {
s.idx = s.node.pos
s.aux = s.node.end
if s.step.axis == "descendant" {
s.idx++
}
}
for s.idx < s.aux {
node := &s.node.nodes[s.idx]
s.idx++
if node.kind == AttrNode {
continue
}
if s.step.match(node) {
s.node = node
return true
}
}
case "following":
if s.idx == 0 {
s.idx = s.node.end
}
for s.idx < len(s.node.nodes) {
node := &s.node.nodes[s.idx]
s.idx++
if node.kind == AttrNode {
continue
}
if s.step.match(node) {
s.node = node
return true
}
}
case "following-sibling":
var down []*Node
if s.node.up != nil {
down = s.node.up.down
if s.idx == 0 {
for s.idx < len(down) {
node := down[s.idx]
s.idx++
if node == s.node {
break
}
}
}
}
for s.idx < len(down) {
node := down[s.idx]
s.idx++
if s.step.match(node) {
s.node = node
return true
}
}
case "preceding":
if s.idx == 0 {
s.aux = s.node.pos // Detect ancestors.
s.idx = s.node.pos - 1
}
for s.idx >= 0 {
node := &s.node.nodes[s.idx]
s.idx--
if node.kind == AttrNode {
continue
}
if node == s.node.nodes[s.aux].up {
s.aux = s.node.nodes[s.aux].up.pos
continue
}
if s.step.match(node) {
s.node = node
return true
}
}
case "preceding-sibling":
var down []*Node
if s.node.up != nil {
down = s.node.up.down
if s.aux == 0 {
s.aux = 1
for s.idx < len(down) {
node := down[s.idx]
s.idx++
if node == s.node {
s.idx--
break
}
}
}
}
for s.idx >= 0 {
node := down[s.idx]
s.idx--
if s.step.match(node) {
s.node = node
return true
}
}
case "attribute":
if s.idx == 0 {
s.idx = s.node.pos + 1
s.aux = s.node.end
}
for s.idx < s.aux {
node := &s.node.nodes[s.idx]
s.idx++
if node.kind != AttrNode {
break
}
if s.step.match(node) {
s.node = node
return true
}
}
}
s.node = nil
return false
}
type positionPredicate struct {
pos int
operator positionFunc
}
type existsPredicate struct {
path *Path
}
type equalsPredicate struct {
path *Path
value string
}
type notequalsPredicate struct {
path *Path
value string
}
type containsPredicate struct {
path *Path
value string
}
type startsWithPredicate struct {
path *Path
value string
}
type notPredicate struct {
uniSub predicate
}
type andPredicate struct {
sub []predicate
}
type orPredicate struct {
sub []predicate
}
// predicate is a marker interface for predicate types.
type predicate interface {
predicate()
}
func (positionPredicate) predicate() {}
func (existsPredicate) predicate() {}
func (equalsPredicate) predicate() {}
func (notequalsPredicate) predicate() {}
func (containsPredicate) predicate() {}
func (startsWithPredicate) predicate() {}
func (notPredicate) predicate() {}
func (andPredicate) predicate() {}
func (orPredicate) predicate() {}
// positionFunc is a type interface for all position comparison operators
type positionFunc func(wanted, current int) bool
func equalPosition(wanted, current int) bool { return wanted == current }
func notequalPosition(wanted, current int) bool { return wanted != current }
func largerPosition(wanted, current int) bool { return current > wanted }
func smallerPosition(wanted, current int) bool { return current < wanted }
func largerequalPosition(wanted, current int) bool { return current >= wanted }
func smallerequalPosition(wanted, current int) bool { return current <= wanted }
type pathStep struct {
root bool
axis string
name string
kind NodeKind
pred predicate
}
func (step *pathStep) match(node *Node) bool {
return node.kind != EndNode &&
(step.kind == AnyNode || step.kind == node.kind) &&
(step.name == "*" || node.name.Local == step.name)
}
// MustCompile returns the compiled path, and panics if
// there are any errors.
func MustCompile(path string) *Path {
e, err := Compile(path)
if err != nil {
panic(err)
}
return e
}
// Compile returns the compiled path.
func Compile(path string) (*Path, error) {
c := pathCompiler{path, 0}
if path == "" {
return nil, c.errorf("empty path")
}
p, err := c.parsePath()
if err != nil {
return nil, err
}
return p, nil
}
type pathCompiler struct {
path string
i int
}
func (c *pathCompiler) errorf(format string, args ...interface{}) error {
return fmt.Errorf("compiling xml path %q:%d: %s", c.path, c.i, fmt.Sprintf(format, args...))
}
func (c *pathCompiler) parsePath() (path *Path, err error) {
var steps []pathStep
var start = c.i
for {
step := pathStep{axis: "child"}
c.skipSpaces()
if c.i == 0 && c.skipByte('/') {
c.skipSpaces()
step.root = true
if len(c.path) == 1 {
step.name = "*"
}
}
if c.peekByte('/') {
step.axis = "descendant-or-self"
step.name = "*"
} else if c.skipByte('@') {
mark := c.i
if !c.skipName() {
return nil, c.errorf("missing name after @")
}
step.axis = "attribute"
step.name = c.path[mark:c.i]
step.kind = AttrNode
} else {
mark := c.i
if c.skipName() {
step.name = c.path[mark:c.i]
c.skipSpaces()
}
if step.name == "" {
return nil, c.errorf("missing name")
} else if step.name == "*" {
step.kind = StartNode
} else if step.name == "." {
step.axis = "self"
step.name = "*"
} else if step.name == ".." {
step.axis = "parent"
step.name = "*"
} else {
if c.skipByte(':') {
if !c.skipByte(':') {
return nil, c.errorf("missing ':'")
}
c.skipSpaces()
switch step.name {
case "attribute":
step.kind = AttrNode
case "self", "child", "parent":
case "descendant", "descendant-or-self":
case "ancestor", "ancestor-or-self":
case "following", "following-sibling":
case "preceding", "preceding-sibling":
default:
return nil, c.errorf("unsupported axis: %q", step.name)
}
step.axis = step.name
mark = c.i
if !c.skipName() {
return nil, c.errorf("missing name")
}
step.name = c.path[mark:c.i]
c.skipSpaces()
}
if c.skipByte('(') {
c.skipSpaces()
conflict := step.kind != AnyNode
switch step.name {
case "node":
// must be anyNode
case "text":
step.kind = TextNode
case "comment":
step.kind = CommentNode
case "processing-instruction":
step.kind = ProcInstNode
default:
return nil, c.errorf("unsupported expression: %s()", step.name)
}
if conflict {
return nil, c.errorf("%s() cannot succeed on axis %q", step.name, step.axis)
}
name := step.name
literal, err := c.parseLiteral()
if err == errNoLiteral {
step.name = "*"
} else if err != nil {
return nil, c.errorf("%v", err)
} else if step.kind == ProcInstNode {
c.skipSpaces()
step.name = literal
} else {
return nil, c.errorf("%s() has no arguments", name)
}
if !c.skipByte(')') {
return nil, c.errorf("%s() missing ')'", name)
}
c.skipSpaces()
} else if step.name == "*" && step.kind == AnyNode {
step.kind = StartNode
}
}
}
if c.skipByte('[') {
c.skipSpaces()
type state struct {
sub []predicate
and bool
not bool
}
var stack []state
var sub []predicate
var and bool
NextPred:
if c.skipByte('(') {
stack = append(stack, state{sub: sub, and: and})
sub = nil
and = false
}
var next predicate
if pos, ok := c.parseInt(); ok {
if pos == 0 {
return nil, c.errorf("positions start at 1")
}
next = positionPredicate{pos: pos, operator: equalPosition}
} else if c.skipString("position()") {
c.skipSpaces()
if operator, ok := c.parseOperator(); !ok {
return nil, c.errorf("position() not followed by operator")
} else {
var operatorFunc positionFunc
switch operator {
case "=":
operatorFunc = equalPosition
case "!=":
operatorFunc = notequalPosition
case "<=":
operatorFunc = smallerequalPosition
case ">=":
operatorFunc = largerequalPosition
case "<":
operatorFunc = smallerPosition
case ">":
operatorFunc = largerPosition
}
c.skipSpaces()
if pos, ok := c.parseInt(); !ok {
return nil, c.errorf("position() not followed by number")
} else {
if pos == 0 {
return nil, c.errorf("positions start at 1")
}
next = positionPredicate{pos: pos, operator: operatorFunc}
}
}
} else if c.skipString("contains(") {
path, err := c.parsePath()
if err != nil {
return nil, err
}
c.skipSpaces()
if !c.skipByte(',') {
return nil, c.errorf("contains() expected ',' followed by a literal string")
}
c.skipSpaces()
value, err := c.parseLiteral()
if err != nil {
return nil, err
}
c.skipSpaces()
if !c.skipByte(')') {
return nil, c.errorf("contains() missing ')'")
}
next = containsPredicate{path, value}
} else if c.skipString("starts-with(") {
path, err := c.parsePath()
if err != nil {
return nil, err
}
c.skipSpaces()
if !c.skipByte(',') {
return nil, c.errorf("starts-with() expected ',' followed by a literal string")
}
c.skipSpaces()
value, err := c.parseLiteral()
if err != nil {
return nil, err
}
c.skipSpaces()
if !c.skipByte(')') {
return nil, c.errorf("starts-with() missing ')'")
}
next = startsWithPredicate{path, value}
} else if c.skipString("not(") {
stack = append(stack, state{sub: sub, and: and, not: true})
sub = nil
and = false
goto NextPred
} else {
path, err := c.parsePath()
if err != nil {
return nil, err
}
if path.path[0] == '-' {
if _, err = strconv.Atoi(path.path); err == nil {
return nil, c.errorf("positions must be positive")
}
}
c.skipSpaces()
if c.skipByte('=') {
c.skipSpaces()
value, err := c.parseLiteral()
if err != nil {
return nil, c.errorf("%v", err)
}
next = equalsPredicate{path, value}
} else if c.skipString("!=") {
c.skipSpaces()
value, err := c.parseLiteral()
if err != nil {
return nil, c.errorf("%v", err)
}
next = notequalsPredicate{path, value}
} else {
next = existsPredicate{path}
}
}
HandleNext:
if and {
p := sub[len(sub)-1].(andPredicate)
p.sub = append(p.sub, next)
sub[len(sub)-1] = p
} else {
sub = append(sub, next)
}
if c.skipSpaces() {
mark := c.i
if c.skipString("and") && c.skipSpaces() {
if !and {
and = true
sub[len(sub)-1] = andPredicate{[]predicate{sub[len(sub)-1]}}
}
goto NextPred
} else if c.skipString("or") && c.skipSpaces() {
and = false
goto NextPred
} else {
c.i = mark
}
}
if c.skipByte(')') {
if len(stack) == 0 {
return nil, c.errorf("unexpected ')'")
}
if len(sub) == 1 {
next = sub[0]
} else {
next = orPredicate{sub}
}
s := stack[len(stack)-1]
stack = stack[:len(stack)-1]
sub = s.sub
and = s.and
if s.not {
next = notPredicate{next}
}
goto HandleNext
}
if len(stack) > 0 {
return nil, c.errorf("expected ')'")
}
if len(sub) == 1 {
step.pred = sub[0]
} else {
step.pred = orPredicate{sub}
}
if !c.skipByte(']') {
return nil, c.errorf("expected ']'")
}
c.skipSpaces()
}
steps = append(steps, step)
//fmt.Printf("step: %#v\n", step)
if !c.skipByte('/') {
if (start == 0 || start == c.i) && c.i < len(c.path) {
return nil, c.errorf("unexpected %q", c.path[c.i])
}
return &Path{steps: steps, path: c.path[start:c.i]}, nil
}
}
panic("unreachable")
}
var errNoLiteral = fmt.Errorf("expected a literal string")
func (c *pathCompiler) parseLiteral() (string, error) {
if c.skipByte('"') {
mark := c.i
if !c.skipByteFind('"') {
return "", fmt.Errorf(`missing '"'`)
}
return c.path[mark : c.i-1], nil
}
if c.skipByte('\'') {
mark := c.i
if !c.skipByteFind('\'') {
return "", fmt.Errorf(`missing "'"`)
}
return c.path[mark : c.i-1], nil
}
return "", errNoLiteral
}
func (c *pathCompiler) parseInt() (v int, ok bool) {
mark := c.i
for c.i < len(c.path) && c.path[c.i] >= '0' && c.path[c.i] <= '9' {
v *= 10
v += int(c.path[c.i]) - '0'
c.i++
}
if c.i == mark {
return 0, false
}
return v, true
}
func (c *pathCompiler) parseOperator() (v string, ok bool) {
if c.skipString("=") {
return "=", true
}
if c.skipString("!=") {
return "!=", true
}
if c.skipString(">=") {
return ">=", true
}
if c.skipString(">") {
return ">", true
}
if c.skipString("<=") {
return "<=", true
}
if c.skipString("<") {
return "<", true
}
return "", false
}
func (c *pathCompiler) skipByte(b byte) bool {
if c.i < len(c.path) && c.path[c.i] == b {
c.i++
return true
}
return false
}
func (c *pathCompiler) skipByteFind(b byte) bool {
for i := c.i; i < len(c.path); i++ {
if c.path[i] == b {
c.i = i + 1
return true
}
}
return false
}
func (c *pathCompiler) peekByte(b byte) bool {
return c.i < len(c.path) && c.path[c.i] == b
}
func (c *pathCompiler) skipSpaces() bool {
mark := c.i
for c.i < len(c.path) {
if c.path[c.i] != ' ' {
break
}
c.i++
}
return c.i != mark
}
func (c *pathCompiler) skipString(s string) bool {
if c.i+len(s) <= len(c.path) && c.path[c.i:c.i+len(s)] == s {
c.i += len(s)
return true
}
return false
}
func (c *pathCompiler) skipName() bool {
if c.i >= len(c.path) {
return false
}
if c.path[c.i] == '*' {
c.i++
return true
}
start := c.i
for c.i < len(c.path) && (c.path[c.i] >= utf8.RuneSelf || isNameByte(c.path[c.i])) {
c.i++
}
return c.i > start
}
func isNameByte(c byte) bool {
return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c == '.' || c == '-'
}