Repository navigation
Expand file tree
/
Copy patheval.go
More file actions
1245 lines (1185 loc) · 40.2 KB
/
Copy patheval.go
File metadata and controls
1245 lines (1185 loc) · 40.2 KB
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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package xpath
import (
"fmt"
"math"
"github.com/knroy/go-xml/v2/xdm"
)
// Eval implements Expr for literals.
func (e *Literal) Eval(*Context) (xdm.Sequence, error) {
if len(e.seq) == 1 && e.seq[0] == xdm.Item(e.Val) {
return e.seq, nil
}
return xdm.One(e.Val), nil
}
// Eval implements Expr for variable references.
func (e *VarRef) Eval(ctx *Context) (xdm.Sequence, error) {
v, ok, err := ctx.lookupVar(e.Name)
if err != nil {
return nil, err
}
if !ok {
if ctx.ev().MissingVar != nil {
if err := ctx.ev().MissingVar(ctx, e.Name); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("XPST0008: undeclared variable $%s", e.Name.Lexical())
}
return v, nil
}
// Eval implements Expr for the context item.
func (e *ContextItem) Eval(ctx *Context) (xdm.Sequence, error) {
if ctx.Item == nil {
return nil, fmt.Errorf("XPDY0002: no context item for '.'")
}
return xdm.One(ctx.Item), nil
}
// Eval implements Expr for a sequence constructor.
func (e *SequenceExpr) Eval(ctx *Context) (xdm.Sequence, error) {
var out xdm.Sequence
widest := 0
for _, it := range e.Items {
v, err := it.Eval(ctx)
if err != nil {
return nil, err
}
widest = max(widest, len(v))
out = append(out, v...)
}
// The widest operand was charged by whatever built it; the rest is
// copies, which ($s, $s) in a loop doubles without any other charge.
if err := ctx.chargeCopies(len(out) - widest); err != nil {
return nil, err
}
return out, nil
}
// chargeCopyFloor is the size below which chargeCopies charges nothing, so
// that ordinary small sequences cost no atomic add.
const chargeCopyFloor = 64
// chargeGrowth charges an accumulation's excess as it grows rather than once
// it is built: *charged is what has been charged so far, and excess the items
// now held beyond those already paid for. Growth is charged in steps of at
// least chargeCopyFloor, so the total charged trails the peak by less than
// that.
func (c *Context) chargeGrowth(charged *int, excess int) error {
if excess-*charged < chargeCopyFloor {
return nil
}
n := excess - *charged
*charged = excess
return c.countItems(n)
}
// chargeCopies charges n items a constructor copied beyond those the
// expressions that built them already charged.
func (c *Context) chargeCopies(n int) error {
if n < chargeCopyFloor {
return nil
}
return c.countItems(n)
}
// Eval implements Expr for a single axis step.
//
// A step is evaluated against the context item alone; iterating a step over
// many context nodes is PathExpr's job. Splitting it this way means the
// predicate's context size is the number of nodes selected by *this* step from
// *this* node, which is what the spec requires and what a combined
// implementation typically gets wrong.
func (e *Step) Eval(ctx *Context) (xdm.Sequence, error) {
node, err := ctx.ContextNode()
if err != nil {
return nil, err
}
return e.evalFrom(ctx, node)
}
// evalFrom is Eval with node as the context node. Of ctx it uses only what
// the predicates inherit, and each predicate replaces the focus with its own,
// so ctx's focus need not be node: evalStepOver calls this with its own
// context rather than copying it once per input node to install a focus that
// nothing would read.
func (e *Step) evalFrom(ctx *Context, node *xdm.Node) (xdm.Sequence, error) {
var err error
selected := e.appendFromN(nil, node, e.firstPosition())
// Predicates apply in axis order, so a reverse axis numbers positions
// from the context node outwards.
for _, pred := range e.Predicates {
selected, err = applyPredicate(ctx, selected, pred)
if err != nil {
return nil, err
}
}
// The result of a step is always in document order with duplicates
// removed, regardless of the axis direction.
return xdm.SortDocumentOrder(selected), nil
}
// appendFrom appends to selected the nodes e's axis and node test select
// from node, in axis order, before any predicate.
func (e *Step) appendFrom(selected xdm.Sequence, node *xdm.Node) xdm.Sequence {
return e.appendFromN(selected, node, 0)
}
// firstPosition is k when e's first predicate is the integer literal k >= 1:
// that predicate keeps only the k-th selected node, so nothing past the k-th
// need be built. Zero means no such bound.
func (e *Step) firstPosition() int {
if len(e.Predicates) == 0 {
return 0
}
l, ok := e.Predicates[0].(*Literal)
if !ok || l.Val == nil || l.Val.Type != xdm.TypeInteger {
return 0
}
if r := l.Val.Rat(); r != nil && r.IsInt() && r.Num().IsInt64() {
if k := r.Num().Int64(); k >= 1 && k <= math.MaxInt32 {
return int(k)
}
}
return 0
}
// appendFromN is appendFrom that stops once limit nodes are selected, where
// limit is positive and selected started empty.
func (e *Step) appendFromN(selected xdm.Sequence, node *xdm.Node, limit int) xdm.Sequence {
principal := e.Axis.PrincipalKind()
if nt, ok := e.Test.(*NameTest); ok && (e.Axis == AxisDescendant || e.Axis == AxisDescendantOrSelf) {
// The direct walk selects what walkAxis would, in the same order.
if e.Axis == AxisDescendantOrSelf && nt.Matches(node, principal) {
selected = append(selected, node)
}
return appendNamedDescendants(selected, node, nt)
}
// Ancestors come in a chain, so a first match usually has more behind it:
// one block of four in place of the 1, 2, 4 growth.
chain := e.Axis == AxisAncestor || e.Axis == AxisAncestorOrSelf
walkAxis(node, e.Axis, func(n *xdm.Node) bool {
if e.Test.Matches(n, principal) {
if chain && selected == nil {
selected = make(xdm.Sequence, 0, 4)
}
selected = append(selected, n)
return limit == 0 || len(selected) < limit
}
return true
})
return selected
}
// Eval implements Expr for a path expression.
func (e *PathExpr) Eval(ctx *Context) (xdm.Sequence, error) {
var cur xdm.Sequence
if e.Root {
node, err := ctx.ContextNode()
if err != nil {
return nil, err
}
root := node.Root()
if root.Kind() != xdm.KindDocument {
// "/" requires the context node to be in a tree whose root is a
// document node; a bare element tree has no document root.
return nil, fmt.Errorf("XPDY0050: root of the context node is not a document node")
}
cur = xdm.One(root)
} else if len(e.Steps) > 0 && !stepNeedsFocus(e.Steps[0]) {
// The first step supplies its own starting sequence — "$v/a" or
// "f()/a" — so the focus is irrelevant and must not be required.
// This is what makes a path rooted at a variable legal inside an
// xsl:function, where there is no context item at all.
v, err := e.Steps[0].Eval(ctx)
if err != nil {
return nil, err
}
cur = v
return evalRemainingSteps(ctx, cur, e.Steps[1:])
} else {
if ctx.Item == nil {
return nil, fmt.Errorf("XPDY0002: no context item for path expression")
}
// A relative path starts from the CONTEXT ITEM, and when that is not
// a node the error is XPTY0020 — "the context item is not a node" —
// not XPTY0019, which is about the value a preceding step produced.
// XPath 2.0 3.2.1 attaches XPTY0020 to the axis step itself, and
// evalStepOver cannot tell the two apart because by then the context
// item is indistinguishable from a step result.
//
// The distinction is observable: analyze-string-085 evaluates
// following-sibling::text inside xsl:matching-substring, where the
// context item is the matched SUBSTRING, and the suite asks for
// XPTY0020 by name.
if _, ok := ctx.Item.(*xdm.Node); !ok && len(e.Steps) > 0 &&
stepIsAxisStep(e.Steps[0]) {
return nil, xdm.Errorf("XPTY0020",
"the context item for an axis step is %s, not a node",
ctx.Item.TypeName())
}
if len(e.Steps) > 0 {
return evalPathFromItem(ctx, ctx.Item, e.Steps)
}
cur = xdm.One(ctx.Item)
}
return evalRemainingSteps(ctx, cur, e.Steps)
}
// evalPathFromItem is evalRemainingSteps starting from the one item it.
// The first step only iterates its input, so it is held in an array on the
// stack rather than boxed into a one-item sequence on the heap, which was an
// allocation for every relative path evaluated.
func evalPathFromItem(ctx *Context, it xdm.Item, steps []Expr) (xdm.Sequence, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
one := [1]xdm.Item{it}
step, rest := steps[0], steps[1:]
if d := fuseDescendant(steps, 0); d != nil {
step, rest = d, steps[2:]
}
next, err := evalStepOver(ctx, one[:], step, len(rest) == 0)
if err != nil {
return nil, err
}
return evalRemainingSteps(ctx, next, rest)
}
// evalStepOver evaluates one step with each item of input as the context item,
// concatenating the results.
//
// The result must be sorted into document order and deduplicated: two distinct
// context nodes can select the same node (as in "a/../b"), and the spec
// requires the path's value to be a node sequence in document order.
//
// The duplicates are removed as the step goes, not only at its end. Over an
// overlapping axis ("//*/following::*") or a rooted inner path ("//*/(//*)")
// each of N context nodes selects up to N nodes, so concatenating them all
// before one final sort held N^2 entries for a result of at most N, and no
// budget saw them. Once out reaches stepDedupMin entries, every node appended
// after is kept only if it is not already there, so out stays the distinct
// nodes plus one context node's selection.
func evalStepOver(ctx *Context, input xdm.Sequence, step Expr, last bool) (xdm.Sequence, error) {
var out xdm.Sequence
size := len(input)
allNodes := true
hasNode := false
charged := 0
var seen map[xdm.IdentityKey]struct{}
// The left operand of "/" must be a sequence of nodes. This is its own
// error — XPTY0019, "the step operand is not a node" — and is distinct
// from XPTY0020, which is about the *context item* being wrong. Letting
// "(10)/child::*" fall through to the focus check reported the latter,
// which points at the wrong thing.
//
// A step that never dereferences the operand — "(10)/f()" — was exempted,
// on the reasoning that nothing goes wrong. But "/" is defined on node
// sequences whatever the step does with them, so "1/3" is XPTY0019 rather
// than 3. The exemption only hid the error.
//
// A static error still comes first, though: "(1 to 10)/count()" calls a
// function that does not exist at that arity, which is XPST0017 and would
// be reported by a processor that resolved functions at compile time —
// this one resolves them at evaluation, so the check is made here before
// the operand is judged.
if call, ok := step.(*FuncCall); ok && ctx.Funcs != nil {
if _, found := lookupFor(ctx, call.Name, len(call.Args)); !found {
return nil, fmt.Errorf(
"XPST0017: unknown function %s with %d argument(s)",
call.Name.Clark(), len(call.Args))
}
}
for _, it := range input {
if _, ok := it.(*xdm.Node); !ok {
return nil, xdm.Errorf("XPTY0019",
"the left operand of a path step is %s, not a node",
it.TypeName())
}
}
for i, it := range input {
if err := ctx.Err(); err != nil {
return nil, err
}
// A plain axis step reads the focus only for its context node, so it
// is handed the node directly; the per-node Context copy WithFocus
// makes was a heap allocation for every node a path visited. The
// loop above has already checked that every item is a node.
var v xdm.Sequence
var err error
st, fresh := step.(*Step)
if fresh && len(st.Predicates) == 0 && !st.Axis.IsReverse() {
// Nothing numbers this node's selection apart from the others,
// so it goes straight onto out; the sort below orders and
// deduplicates the whole, as it would the per-node results.
from := len(out)
out = st.appendFrom(out, it.(*xdm.Node))
out, seen = dedupStep(out, from, seen, allNodes)
continue
}
if fresh {
v, err = st.evalFrom(ctx, it.(*xdm.Node))
} else if da, ok := step.(*descendantAttrs); ok {
v = da.appendFrom(nil, it.(*xdm.Node))
} else {
v, err = step.Eval(ctx.WithFocus(it, i+1, size))
}
if err != nil {
return nil, err
}
for _, r := range v {
if _, ok := r.(*xdm.Node); ok {
hasNode = true
} else {
allNodes = false
}
}
if !allNodes && hasNode {
return nil, mixedStepError(last)
}
// evalFrom's result is a fresh slice no one else holds, so the first
// one becomes out instead of being copied into it: for a single
// input node, the common case, that copy was the accumulation's
// whole cost. Any other step can return a sequence a variable still
// holds, whose spare capacity a later append must not write into.
from := len(out)
if fresh && out == nil {
out = v
} else {
out = append(out, v...)
}
out, seen = dedupStep(out, from, seen, allNodes)
if !allNodes {
// An atomic accumulation has no dedup to bound it, so what it
// holds beyond one item per context node is charged as it grows.
if err := ctx.chargeGrowth(&charged, len(out)-(i+1)); err != nil {
return nil, err
}
}
}
if !allNodes {
// XPath 2.0 section 3.2.1: "If the result of the last step in a path
// expression contains both nodes and atomic values, a type error is
// raised [err:XPTY0018]." A result that is entirely atomic is legal
// and common — "a/string(@b)" is an ordinary path — so only a genuine
// MIX is an error, and only a mix is checked for here.
//
// The distinction matters and an earlier attempt missed it: raising
// the error for the whole !allNodes branch condemns every all-atomic
// path as well, which is most of them, and was measured to cost 149
// tests. Testing per INPUT ITEM instead never fires: "//item/(if
// (position()=3) then @* else string(@val))" yields nodes for one
// item and strings for the others, so each item's own result is
// homogeneous and only the accumulation is mixed. The accumulation is
// exactly what the spec calls "the result of the last step", so that
// is what is examined.
//
// A mixed result is also unsortable, which is why the check precedes
// the sort: document order is not defined over atomic values. It is
// made in the loop above, as soon as the accumulation holds both, so
// a mixed result is never built in full.
return out, nil
}
return xdm.SortDocumentOrder(out), nil
}
// mixedStepError is the error for a step result holding both nodes and
// atomic values.
//
// XPTY0018 is the *last* step's error. A step with another after it has
// produced the left operand of the next "/", and a non-node there is XPTY0019
// -- the same complaint the operand check makes, reached one step earlier.
// Reporting XPTY0018 for both named the wrong fault whenever the mixture
// appeared mid-path, as in "$x/b/(f(position()))/a".
func mixedStepError(last bool) error {
if !last {
return xdm.Errorf("XPTY0019",
"the left operand of a path step contains a non-node")
}
return xdm.Errorf("XPTY0018",
"the result of a path step contains both nodes and atomic values")
}
// stepDedupMin is the size at which evalStepOver starts removing duplicates
// as it accumulates. Below it the accumulation is left to the final sort,
// which costs nothing extra for the common path whose selections never meet.
const stepDedupMin = 4096
// dedupStep drops from out[from:] every node already in out, recording the
// ones it keeps in seen, which it creates (from the whole of out) once out
// reaches stepDedupMin. The tail is filtered in place: out is a slice
// evalStepOver owns. Identity is what Is compares, so no two distinct nodes
// are merged; the final sort still orders the result. An accumulation holding
// an atomic value is left as it is, for the final type check.
func dedupStep(out xdm.Sequence, from int, seen map[xdm.IdentityKey]struct{}, allNodes bool) (xdm.Sequence, map[xdm.IdentityKey]struct{}) {
if !allNodes {
return out, seen
}
if seen == nil {
if len(out) < stepDedupMin {
return out, nil
}
seen = make(map[xdm.IdentityKey]struct{}, len(out))
from = 0
}
kept := out[:from]
for _, it := range out[from:] {
k := it.(*xdm.Node).Identity()
if _, dup := seen[k]; dup {
continue
}
seen[k] = struct{}{}
kept = append(kept, it)
}
return kept, seen
}
// Eval implements Expr for a filtered expression.
func (e *FilterExpr) Eval(ctx *Context) (xdm.Sequence, error) {
base, err := e.Base.Eval(ctx)
if err != nil {
return nil, err
}
for _, pred := range e.Predicates {
base, err = applyPredicate(ctx, base, pred)
if err != nil {
return nil, err
}
}
return base, nil
}
// applyPredicate filters seq by pred.
//
// The numeric-predicate rule is the one piece of real subtlety: if the
// predicate's value is a single number, it selects by position rather than by
// effective boolean value. "[1]" means "the first item", while "[true()]"
// means "every item". The test is on the *value*, not the syntax, so
// "[$n]" behaves either way depending on what $n holds.
func applyPredicate(ctx *Context, seq xdm.Sequence, pred Expr) (xdm.Sequence, error) {
var out xdm.Sequence
size := len(seq)
var h *comparisonHoist
var hoist comparisonHoist // on the stack: one allocation less per predicate
if size > 1 && hoist.init(ctx, pred) {
h = &hoist
}
// One focus context serves every item when the predicate cannot keep
// it: each item's evaluation is over before the next begins, so the
// context is moved on in place instead of copied per item.
var reuse *Context
share := size > 1 && !mayCaptureFocus(pred)
for i, it := range seq {
if err := ctx.Err(); err != nil {
return nil, err
}
pos := i + 1
var sub *Context
switch {
case !share:
sub = ctx.WithFocus(it, pos, size)
case reuse == nil:
reuse = ctx.WithFocus(it, pos, size)
sub = reuse
default:
reuse.Item, reuse.Position = it, int32(pos)
sub = reuse
}
if h != nil {
keep, ok, err := h.holds(sub)
if err != nil {
return nil, err
}
if ok {
if keep {
out = append(out, it)
}
continue
}
h = nil // the hoisted operand failed: evaluate as written from here
}
v, err := pred.Eval(sub)
if err != nil {
return nil, err
}
keep, err := predicateHolds(v, pos)
if err != nil {
return nil, err
}
if keep {
out = append(out, it)
}
}
return out, nil
}
// mayCaptureFocus reports whether evaluating e might keep its context past
// the evaluation, which would see a later item's focus if applyPredicate
// moved that context on. A function item is the way one could: an inline
// function, a named function reference, a partial application or
// fn:function-lookup builds one, and a dynamic call runs one. Anything not
// known to be free of them is assumed to capture.
func mayCaptureFocus(e Expr) bool {
anyOf := func(es []Expr) bool {
for _, x := range es {
if mayCaptureFocus(x) {
return true
}
}
return false
}
bindings := func(bs []Binding) bool {
for _, b := range bs {
if mayCaptureFocus(b.Seq) {
return true
}
}
return false
}
switch v := e.(type) {
case nil, *Literal, *VarRef, *ContextItem, *descendantAttrs:
return false
case *FuncCall:
if v.Name.URI == xdm.NSFN {
switch v.Name.Local {
case "function-lookup", "load-xquery-module":
return true
}
}
return anyOf(v.Args)
case *Step:
return anyOf(v.Predicates)
case *FilterExpr:
return mayCaptureFocus(v.Base) || anyOf(v.Predicates)
case *PathExpr:
return anyOf(v.Steps)
case *BinaryOp:
return mayCaptureFocus(v.Left) || mayCaptureFocus(v.Right)
case *UnaryOp:
return mayCaptureFocus(v.Operand)
case *CastExpr:
return mayCaptureFocus(v.Operand)
case *InstanceOfExpr:
return mayCaptureFocus(v.Operand)
case *TreatExpr:
return mayCaptureFocus(v.Operand)
case *SequenceExpr:
return anyOf(v.Items)
case *IfExpr:
return mayCaptureFocus(v.Cond) || mayCaptureFocus(v.Then) ||
mayCaptureFocus(v.Else)
case *StringConcat:
return mayCaptureFocus(v.Left) || mayCaptureFocus(v.Right)
case *SimpleMap:
return mayCaptureFocus(v.Left) || mayCaptureFocus(v.Right)
case *ForExpr:
return bindings(v.Bindings) || mayCaptureFocus(v.Return)
case *LetExpr:
return bindings(v.Bindings) || mayCaptureFocus(v.Return)
case *QuantifiedExpr:
return bindings(v.Bindings) || mayCaptureFocus(v.Test)
case *LookupExpr:
return mayCaptureFocus(v.Base) || mayCaptureFocus(v.Expr)
case *MapConstructor:
return anyOf(v.Keys) || anyOf(v.Values)
case *ArrayConstructor:
return anyOf(v.Members)
}
return true
}
// comparisonHoist evaluates a predicate "A op B", a general or value
// comparison, whose one operand reads no focus and calls only pure built-ins
// (hoistable and callsBuiltins, as the XQuery join uses them): that operand is
// evaluated and atomized once per application of the predicate rather than
// once per item. A comparison is never numeric, so no positional predicate is
// affected. "$letters/l[. = substring($term, 1, 2)]" is the motivating shape.
type comparisonHoist struct {
cmp *BinaryOp
left bool // the hoisted operand is the left one
value xdm.Sequence // its atomized value, once ready
ready bool
}
// init sets up h for pred and reports true, or reports false when pred is not
// such a comparison, under
// XPath 1.0 compatibility (whose conversions need the raw operands), and for
// "A = (M to N)", which evalGeneralComparison answers from the bounds.
func (h *comparisonHoist) init(ctx *Context, pred Expr) bool {
b, ok := pred.(*BinaryOp)
if !ok {
return false
}
switch b.Op {
case "eq", "ne", "lt", "le", "gt", "ge":
case "=", "!=", "<", "<=", ">", ">=":
if r, isRange := b.Right.(*BinaryOp); ctx.Compat() || (isRange && r.Op == "to") {
return false
}
default:
return false
}
side, left := b.Right, false
if !hoistable(side, false) {
side, left = b.Left, true
if !hoistable(side, false) {
return false
}
}
if !callsBuiltins(side, ctx) {
return false
}
*h = comparisonHoist{cmp: b, left: left}
return true
}
// holds reports whether the predicate selects sub's context item. The hoisted
// operand is evaluated on the first item, so an empty sequence never raises
// its error. ok is false when it raised one: the caller then evaluates the
// predicate as written from this item on, which raises whichever error the
// comparison raises first. Once it has succeeded it cannot fail on a later
// item, so every error left comes from the other operand or the comparison,
// in the order evaluating "A op B" would raise them.
func (h *comparisonHoist) holds(sub *Context) (keep, ok bool, err error) {
b := h.cmp
if keep, ok := nameComparison(sub, b); ok {
return keep, true, nil
}
other := b.Left
if h.left {
other = b.Right
}
if !h.ready {
side := b.Right
if h.left {
side = b.Left
}
v, err := side.Eval(sub)
if err == nil {
v, err = sub.atomizeChecked(v)
}
if err != nil {
return false, false, nil
}
h.value, h.ready = v, true
}
v, err := other.Eval(sub)
if err != nil {
return false, true, err
}
a, err := sub.atomizeChecked(v)
if err != nil {
return false, true, err
}
la, ra := a, h.value
if h.left {
la, ra = h.value, a
}
if generalValueOp(b.Op) != "" {
keep, err = b.comparePairs(sub, la, ra)
return keep, true, err
}
r, err := b.compareSingletons(sub, la, ra)
if err != nil || len(r) == 0 {
return false, true, err
}
return r[0].(*xdm.Atomic).Bool(), true, nil
}
// predicateHolds decides whether a predicate value selects the item at pos.
//
// The focus is not needed here: the predicate expression has already been
// evaluated against it by the caller, and what remains is a decision about
// the resulting value alone.
func predicateHolds(v xdm.Sequence, pos int) (bool, error) {
if len(v) == 1 {
if a, ok := v[0].(*xdm.Atomic); ok && a.Type.IsNumeric() {
// Positional predicate: compare numerically so that 1.0 and 1
// both select position 1, and NaN selects nothing.
if a.IsNaN() {
return false, nil
}
// An integer compares exactly, and without the allocations
// big.Rat's Float64 makes.
if r := a.Rat(); a.Type == xdm.TypeInteger && r != nil && r.IsInt() &&
r.Num().IsInt64() {
return r.Num().Int64() == int64(pos), nil
}
return a.Float64() == float64(pos), nil
}
}
return EffectiveBooleanValue(v)
}
// EffectiveBooleanValue computes fn:boolean over a sequence.
//
// XPath 2.0 restricts this compared with 1.0: a sequence of two or more
// atomic values raises FORG0006 rather than being truthy. That strictness is
// deliberate — it catches "if ($seq)" where the author meant
// "if (exists($seq))" — so it is enforced rather than relaxed.
func EffectiveBooleanValue(seq xdm.Sequence) (bool, error) {
if len(seq) == 0 {
return false, nil
}
if _, isNode := seq[0].(*xdm.Node); isNode {
// A sequence starting with a node is true regardless of length.
return true, nil
}
if len(seq) > 1 {
return false, fmt.Errorf(
"FORG0006: effective boolean value of a sequence of %d atomic values is undefined", len(seq))
}
a, ok := seq[0].(*xdm.Atomic)
if !ok {
return false, fmt.Errorf("FORG0006: cannot compute effective boolean value")
}
switch {
case a.Type == xdm.TypeBoolean:
return a.Bool(), nil
case a.Type == xdm.TypeString || a.Type == xdm.TypeUntypedAtomic || a.Type == xdm.TypeAnyURI:
return a.Str() != "", nil
case a.Type.IsNumeric():
// NaN is false, as is zero of any sign.
return !a.IsNaN() && a.Float64() != 0, nil
}
return false, fmt.Errorf("FORG0006: effective boolean value of %s is undefined", a.TypeName())
}
// Eval implements Expr for conditionals.
func (e *IfExpr) Eval(ctx *Context) (xdm.Sequence, error) {
c, err := e.Cond.Eval(ctx)
if err != nil {
return nil, err
}
b, err := EffectiveBooleanValue(c)
if err != nil {
return nil, err
}
if b {
return e.Then.Eval(ctx)
}
return e.Else.Eval(ctx)
}
// Eval implements Expr for for-expressions.
//
// Multiple bindings iterate as nested loops, left to right, with each binding
// visible to the ones after it.
func (e *ForExpr) Eval(ctx *Context) (xdm.Sequence, error) {
sub, err := ctx.Descend()
if err != nil {
return nil, err
}
return evalFor(sub, e.Bindings, e.Return)
}
// Eval implements Expr.
//
// Each binding is evaluated in the scope of the ones before it and bound
// whole, so the body runs exactly once however many items a binding holds.
// That single evaluation is the difference from ForExpr, not the keyword.
func (e *LetExpr) Eval(ctx *Context) (xdm.Sequence, error) {
sub, err := ctx.Descend()
if err != nil {
return nil, err
}
for _, b := range e.Bindings {
if err := sub.Err(); err != nil {
return nil, err
}
v, err := b.Seq.Eval(sub)
if err != nil {
return nil, err
}
if err := sub.countItems(len(v)); err != nil {
return nil, err
}
sub = sub.WithVar(b.Var, v)
}
return e.Return.Eval(sub)
}
// bindingFrame is one level of a multi-binding for or quantified expression
// while it iterates: the scope its binding's sequence was evaluated in, that
// sequence, and the next item of it to bind.
type bindingFrame struct {
scope *Context
seq xdm.Sequence
next int
}
// evalFor runs the nested loops of a for expression with an explicit stack of
// frames rather than one Go call per binding. The parser puts no bound on the
// number of bindings, and Descend is charged once for the whole expression, so
// recursing over bindings[1:] let a long enough binding list exhaust the
// goroutine stack, which is fatal rather than an error.
func evalFor(ctx *Context, bindings []Binding, body Expr) (xdm.Sequence, error) {
if len(bindings) == 0 {
return body.Eval(ctx)
}
seq, err := bindings[0].Seq.Eval(ctx)
if err != nil {
return nil, err
}
frames := []bindingFrame{{scope: ctx, seq: seq}}
var out xdm.Sequence
for len(frames) > 0 {
k := len(frames) - 1
f := &frames[k]
if f.next == len(f.seq) {
frames = frames[:k]
continue
}
if err := ctx.Err(); err != nil {
return nil, err
}
inner := f.scope.WithVar(bindings[k].Var, xdm.One(f.seq[f.next]))
f.next++
if k+1 < len(bindings) {
seq, err := bindings[k+1].Seq.Eval(inner)
if err != nil {
return nil, err
}
frames = append(frames, bindingFrame{scope: inner, seq: seq})
continue
}
v, err := body.Eval(inner)
if err != nil {
return nil, err
}
// The recursive form charged a body result once at every binding
// level, as each level's concatenation took it in, and the item
// budget's verdicts are pinned to that accounting: XQuery charges a
// FLWOR's tuple stream per clause, and "count(for ...)" -- routed
// here -- must be refused where the bare FLWOR is. So the charge is
// kept, made at once for all the levels, saturating rather than
// wrapping where int is 32 bits.
charge := len(v)
if charge > math.MaxInt/len(bindings) {
charge = math.MaxInt
} else {
charge *= len(bindings)
}
if err := ctx.countItems(charge); err != nil {
return nil, err
}
out = append(out, v...)
}
return out, nil
}
// Eval implements Expr for quantified expressions.
func (e *QuantifiedExpr) Eval(ctx *Context) (xdm.Sequence, error) {
sub, err := ctx.Descend()
if err != nil {
return nil, err
}
res, err := evalQuantified(sub, e.Every, e.Bindings, e.Test)
if err != nil {
return nil, err
}
return xdm.One(boolItem(res)), nil
}
// evalQuantified short-circuits: "some" stops at the first true, "every" at
// the first false. Over a large node-set that is the difference between one
// comparison and a full scan.
//
// The bindings iterate on a stack of frames, as in evalFor and for the same
// reason: a Go call per binding let a long binding list overflow the stack.
func evalQuantified(ctx *Context, every bool, bindings []Binding, test Expr) (bool, error) {
if len(bindings) == 0 {
v, err := test.Eval(ctx)
if err != nil {
return false, err
}
return EffectiveBooleanValue(v)
}
seq, err := bindings[0].Seq.Eval(ctx)
if err != nil {
return false, err
}
frames := []bindingFrame{{scope: ctx, seq: seq}}
for len(frames) > 0 {
k := len(frames) - 1
f := &frames[k]
if f.next == len(f.seq) {
// An exhausted inner binding decided nothing; the one around it
// moves on to its next item.
frames = frames[:k]
continue
}
if err := ctx.Err(); err != nil {
return false, err
}
inner := f.scope.WithVar(bindings[k].Var, xdm.One(f.seq[f.next]))
f.next++
if k+1 < len(bindings) {
seq, err := bindings[k+1].Seq.Eval(inner)
if err != nil {
return false, err
}
frames = append(frames, bindingFrame{scope: inner, seq: seq})
continue
}
v, err := test.Eval(inner)
if err != nil {
return false, err
}
ok, err := EffectiveBooleanValue(v)
if err != nil {
return false, err
}
if ok != every {
return ok, nil
}
}
// An empty sequence makes "every" vacuously true and "some" false.
return every, nil
}
// Eval implements Expr for function calls.
func (e *FuncCall) Eval(ctx *Context) (xdm.Sequence, error) {
if ctx.Funcs == nil {
return nil, fmt.Errorf("XPST0017: no function library available for %s", e.Name.Clark())
}
// A "?" in the argument list makes this a partial application: the result
// is a function item of the remaining arity, not a call.
if hasPlaceholder(e.Args) {
fn, ok := lookupFor(ctx, e.Name, len(e.Args))
if !ok {
return nil, fmt.Errorf("XPST0017: unknown function %s with %d argument(s)",
e.Name.Clark(), len(e.Args))
}
return partialApply(e.Name, fn.Arity, hostBoundCall(ctx, fn), e.Args, ctx)
}
fn, params, hasParams, ok := e.resolve(ctx)
if !ok {
// XSLT 18.1, and B.1 rule 6: under XPath 1.0 compatibility a call to
// an unknown function in a non-null namespace is not the static error
// XPST0017. 1.0 could not resolve extension functions statically at
// all, so the call binds to a fallback that raises the *dynamic*
// XTDE1425 -- and only if it is actually evaluated, which is why a
// stylesheet guarded by function-available() still compiles.
//
// A function in no namespace is excluded: that is a call to a builtin
// this processor does not have, which is a genuine XPST0017 whatever
// mode it is written in.
if ctx.Compat() && e.Name.URI != "" && e.Name.URI != xdm.NSFN {
return nil, xdm.Errorf("XTDE1425",
"no implementation is available for the extension function "+
"%s with %d argument(s)", e.Name.Clark(), len(e.Args))
}
return nil, fmt.Errorf("XPST0017: unknown function %s with %d argument(s)",
e.Name.Clark(), len(e.Args))
}
// An aggregate over a bare integer range is answered from the bounds
// rather than by building the sequence: count is hi-lo+1, sum is the
// arithmetic series, min and max are the bounds themselves. Materialising
// ten million values to then discard all of them peaked at 1.9 GB, for
// answers that are arithmetic. See rangeprops.go for what does and does
// not qualify.
if seq, ok, err := rangeAggregate(ctx, e); err != nil {
return nil, err
} else if ok {
return seq, nil
}