-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathxpath.js
2281 lines (2250 loc) · 70.9 KB
/
xpath.js
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
// NOTE: This code was taken from jsdom, and slightly modified to install a
// global XPathEvaluator in global scope.
//
// This is a temporary solution where xpath is polyfilled in JS rather than
// implemented directly in Go code.
//
// JSDOM Source: https://github.com/jsdom/jsdom
/** Here is yet another implementation of XPath 1.0 in Javascript.
*
* My goal was to make it relatively compact, but as I fixed all the axis bugs
* the axes became more and more complicated. :-(.
*
* I have not implemented namespaces or case-sensitive axes for XML yet.
*
* How to test it in Chrome: You can make a Chrome extension that replaces
* the WebKit XPath parser with this one. But it takes a bit of effort to
* get around isolated world and same-origin restrictions:
* manifest.json:
{
"name": "XPathTest",
"version": "0.1",
"content_scripts": [{
"matches": ["http://localhost/*"], // or wildcard host
"js": ["xpath.js", "injection.js"],
"all_frames": true, "run_at": "document_start"
}]
}
* injection.js:
// goal: give my xpath object to the website's JS context.
var script = document.createElement('script');
script.textContent =
"document.addEventListener('xpathextend', function(e) {\n" +
" console.log('extending document with xpath...');\n" +
" e.detail(window);" +
"});";
document.documentElement.appendChild(script);
document.documentElement.removeChild(script);
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('xpathextend', true, true, this.xpath.extend);
document.dispatchEvent(evt);
*/
function initXPath(core) {
var xpath = {};
// Helper function to deal with the migration of Attr to no longer have a nodeName property despite this codebase
// assuming it does.
function getNodeName(nodeOrAttr) {
return nodeOrAttr.constructor.name === "Attr"
? nodeOrAttr.name
: nodeOrAttr.nodeName;
}
/***************************************************************************
* Tokenization *
***************************************************************************/
/**
* The XPath lexer is basically a single regular expression, along with
* some helper functions to pop different types.
*/
var Stream = (xpath.Stream = function Stream(str) {
this.original = this.str = str;
this.peeked = null;
// TODO: not really needed, but supposedly tokenizer also disambiguates
// a * b vs. node test *
this.prev = null; // for debugging
this.prevprev = null;
});
Stream.prototype = {
peek: function () {
if (this.peeked) return this.peeked;
var m = this.re.exec(this.str);
if (!m) return null;
this.str = this.str.substr(m[0].length);
return (this.peeked = m[1]);
},
/** Peek 2 tokens ahead. */
peek2: function () {
this.peek(); // make sure this.peeked is set
var m = this.re.exec(this.str);
if (!m) return null;
return m[1];
},
pop: function () {
var r = this.peek();
this.peeked = null;
this.prevprev = this.prev;
this.prev = r;
return r;
},
trypop: function (tokens) {
var tok = this.peek();
if (tok === tokens) return this.pop();
if (Array.isArray(tokens)) {
for (var i = 0; i < tokens.length; ++i) {
var t = tokens[i];
if (t == tok) return this.pop();
}
}
},
trypopfuncname: function () {
var tok = this.peek();
if (!this.isQnameRe.test(tok)) return null;
switch (tok) {
case "comment":
case "text":
case "processing-instruction":
case "node":
return null;
}
if ("(" != this.peek2()) return null;
return this.pop();
},
trypopaxisname: function () {
var tok = this.peek();
switch (tok) {
case "ancestor":
case "ancestor-or-self":
case "attribute":
case "child":
case "descendant":
case "descendant-or-self":
case "following":
case "following-sibling":
case "namespace":
case "parent":
case "preceding":
case "preceding-sibling":
case "self":
if ("::" == this.peek2()) return this.pop();
}
return null;
},
trypopnametest: function () {
var tok = this.peek();
if ("*" === tok || this.startsWithNcNameRe.test(tok)) return this.pop();
return null;
},
trypopliteral: function () {
var tok = this.peek();
if (null == tok) return null;
var first = tok.charAt(0);
var last = tok.charAt(tok.length - 1);
if (('"' === first && '"' === last) || ("'" === first && "'" === last)) {
this.pop();
return tok.substr(1, tok.length - 2) ?? null;
}
return null;
},
trypopnumber: function () {
var tok = this.peek();
if (this.isNumberRe.test(tok)) return parseFloat(this.pop()) ?? null;
else return null;
},
trypopvarref: function () {
var tok = this.peek();
if (null == tok) return null;
if ("$" === tok.charAt(0)) return this.pop().substr(1) ?? null;
else return null;
},
position: function () {
return this.original.length - this.str.length;
},
};
(function () {
// http://www.w3.org/TR/REC-xml-names/#NT-NCName
var nameStartCharsExceptColon =
"A-Z_a-z\xc0-\xd6\xd8-\xf6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF" +
"\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF" +
"\uFDF0-\uFFFD"; // JS doesn't support [#x10000-#xEFFFF]
var nameCharExceptColon =
nameStartCharsExceptColon + "\\-\\.0-9\xb7\u0300-\u036F\u203F-\u2040";
var ncNameChars =
"[" + nameStartCharsExceptColon + "][" + nameCharExceptColon + "]*";
// http://www.w3.org/TR/REC-xml-names/#NT-QName
var qNameChars = ncNameChars + "(?::" + ncNameChars + ")?";
var otherChars = "\\.\\.|[\\(\\)\\[\\].@,]|::"; // .. must come before [.]
var operatorChars = "and|or|mod|div|" + "//|!=|<=|>=|[*/|+\\-=<>]"; // //, !=, <=, >= before individual ones.
var literal = '"[^"]*"|' + "'[^']*'";
var numberChars = "[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+";
var variableReference = "\\$" + qNameChars;
var nameTestChars = "\\*|" + ncNameChars + ":\\*|" + qNameChars;
var optionalSpace = "[ \t\r\n]*"; // stricter than regexp \s.
var nodeType = "comment|text|processing-instruction|node";
var re = new RegExp(
// numberChars before otherChars so that leading-decimal doesn't become .
"^" +
optionalSpace +
"(" +
numberChars +
"|" +
otherChars +
"|" +
nameTestChars +
"|" +
operatorChars +
"|" +
literal +
"|" +
variableReference +
")",
// operatorName | nodeType | functionName | axisName are lumped into
// qName for now; we'll check them on pop.
);
Stream.prototype.re = re;
Stream.prototype.startsWithNcNameRe = new RegExp("^" + ncNameChars);
Stream.prototype.isQnameRe = new RegExp("^" + qNameChars + "$");
Stream.prototype.isNumberRe = new RegExp("^" + numberChars + "$");
})();
/***************************************************************************
* Parsing *
***************************************************************************/
var parse = (xpath.parse = function parse(stream, a) {
var r = orExpr(stream, a);
var x,
unparsed = [];
while ((x = stream.pop())) {
unparsed.push(x);
}
if (unparsed.length)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": Unparsed tokens: " +
unparsed.join(" "),
);
return r;
});
/**
* binaryL ::= subExpr
* | binaryL op subExpr
* so a op b op c becomes ((a op b) op c)
*/
function binaryL(subExpr, stream, a, ops) {
var lhs = subExpr(stream, a);
if (lhs == null) return null;
var op;
while ((op = stream.trypop(ops))) {
var rhs = subExpr(stream, a);
if (rhs == null)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected something after " + op,
);
lhs = a.node(op, lhs, rhs);
}
return lhs;
}
/**
* Too bad this is never used. If they made a ** operator (raise to power),
( we would use it.
* binaryR ::= subExpr
* | subExpr op binaryR
* so a op b op c becomes (a op (b op c))
*/
function binaryR(subExpr, stream, a, ops) {
var lhs = subExpr(stream, a);
if (lhs == null) return null;
var op = stream.trypop(ops);
if (op) {
var rhs = binaryR(stream, a);
if (rhs == null)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected something after " + op,
);
return a.node(op, lhs, rhs);
} else {
return lhs; // TODO
}
}
/** [1] LocationPath::= RelativeLocationPath | AbsoluteLocationPath
* e.g. a, a/b, //a/b
*/
function locationPath(stream, a) {
return (
absoluteLocationPath(stream, a) || relativeLocationPath(null, stream, a)
);
}
/** [2] AbsoluteLocationPath::= '/' RelativeLocationPath? | AbbreviatedAbsoluteLocationPath
* [10] AbbreviatedAbsoluteLocationPath::= '//' RelativeLocationPath
*/
function absoluteLocationPath(stream, a) {
var op = stream.peek();
if ("/" === op || "//" === op) {
var lhs = a.node("Root");
return relativeLocationPath(lhs, stream, a, true);
} else {
return null;
}
}
/** [3] RelativeLocationPath::= Step | RelativeLocationPath '/' Step |
* | AbbreviatedRelativeLocationPath
* [11] AbbreviatedRelativeLocationPath::= RelativeLocationPath '//' Step
* e.g. p/a, etc.
*/
function relativeLocationPath(lhs, stream, a, isOnlyRootOk) {
if (null == lhs) {
lhs = step(stream, a);
if (null == lhs) return lhs;
}
var op;
while ((op = stream.trypop(["/", "//"]))) {
if ("//" === op) {
lhs = a.node(
"/",
lhs,
a.node("Axis", "descendant-or-self", "node", undefined),
);
}
var rhs = step(stream, a);
if (null == rhs && "/" === op && isOnlyRootOk) return lhs;
else isOnlyRootOk = false;
if (null == rhs)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected step after " + op,
);
lhs = a.node("/", lhs, rhs);
}
return lhs;
}
/** [4] Step::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
* [12] AbbreviatedStep::= '.' | '..'
* e.g. @href, self::p, p, a[@href], ., ..
*/
function step(stream, a) {
var abbrStep = stream.trypop([".", ".."]);
if ("." === abbrStep)
// A location step of . is short for self::node().
return a.node("Axis", "self", "node");
if (".." === abbrStep)
// A location step of .. is short for parent::node()
return a.node("Axis", "parent", "node");
var axis = axisSpecifier(stream, a);
var nodeType = nodeTypeTest(stream, a);
var nodeName;
if (null == nodeType) nodeName = nodeNameTest(stream, a);
if (null == axis && null == nodeType && null == nodeName) return null;
if (null == nodeType && null == nodeName)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": Expected nodeTest after axisSpecifier " +
axis,
);
if (null == axis) axis = "child";
if (null == nodeType) {
// When there's only a node name, then the node type is forced to be the
// principal node type of the axis.
// see http://www.w3.org/TR/xpath/#dt-principal-node-type
if ("attribute" === axis) nodeType = "attribute";
else if ("namespace" === axis) nodeType = "namespace";
else nodeType = "element";
}
var lhs = a.node("Axis", axis, nodeType, nodeName);
var pred;
while (null != (pred = predicate(lhs, stream, a))) {
lhs = pred;
}
return lhs;
}
/** [5] AxisSpecifier::= AxisName '::' | AbbreviatedAxisSpecifier
* [6] AxisName::= 'ancestor' | 'ancestor-or-self' | 'attribute' | 'child'
* | 'descendant' | 'descendant-or-self' | 'following'
* | 'following-sibling' | 'namespace' | 'parent' |
* | 'preceding' | 'preceding-sibling' | 'self'
* [13] AbbreviatedAxisSpecifier::= '@'?
*/
function axisSpecifier(stream, a) {
var attr = stream.trypop("@");
if (null != attr) return "attribute";
var axisName = stream.trypopaxisname();
if (null != axisName) {
var coloncolon = stream.trypop("::");
if (null == coloncolon)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": Should not happen. Should be ::.",
);
return axisName;
}
}
/** [7] NodeTest::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'
* [38] NodeType::= 'comment' | 'text' | 'processing-instruction' | 'node'
* I've split nodeTypeTest from nodeNameTest for convenience.
*/
function nodeTypeTest(stream, a) {
if ("(" !== stream.peek2()) {
return null;
}
var type = stream.trypop([
"comment",
"text",
"processing-instruction",
"node",
]);
if (null != type) {
if (null == stream.trypop("("))
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Should not happen.",
);
var param = undefined;
if (type == "processing-instruction") {
param = stream.trypopliteral();
}
if (null == stream.trypop(")"))
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected close parens.",
);
return type;
}
}
function nodeNameTest(stream, a) {
var name = stream.trypopnametest();
if (name != null) return name;
else return null;
}
/** [8] Predicate::= '[' PredicateExpr ']'
* [9] PredicateExpr::= Expr
*/
function predicate(lhs, stream, a) {
if (null == stream.trypop("[")) return null;
var expr = orExpr(stream, a);
if (null == expr)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected expression after [",
);
if (null == stream.trypop("]"))
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected ] after expression.",
);
return a.node("Predicate", lhs, expr);
}
/** [14] Expr::= OrExpr
*/
/** [15] PrimaryExpr::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
* e.g. $x, (3+4), "hi", 32, f(x)
*/
function primaryExpr(stream, a) {
var x = stream.trypopliteral();
if (null == x) x = stream.trypopnumber();
if (null != x) {
return x;
}
var varRef = stream.trypopvarref();
if (null != varRef) return a.node("VariableReference", varRef);
var funCall = functionCall(stream, a);
if (null != funCall) {
return funCall;
}
if (stream.trypop("(")) {
var e = orExpr(stream, a);
if (null == e)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected expression after (.",
);
if (null == stream.trypop(")"))
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected ) after expression.",
);
return e;
}
return null;
}
/** [16] FunctionCall::= FunctionName '(' ( Argument ( ',' Argument )* )? ')'
* [17] Argument::= Expr
*/
function functionCall(stream, a) {
var name = stream.trypopfuncname(stream, a);
if (null == name) return null;
if (null == stream.trypop("("))
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " + stream.position() + ": Expected ( ) after function name.",
);
var params = [];
var first = true;
while (null == stream.trypop(")")) {
if (!first && null == stream.trypop(","))
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": Expected , between arguments of the function.",
);
first = false;
var param = orExpr(stream, a);
if (param == null)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": Expected expression as argument of function.",
);
params.push(param);
}
return a.node("FunctionCall", name, params);
}
/** [18] UnionExpr::= PathExpr | UnionExpr '|' PathExpr
*/
function unionExpr(stream, a) {
return binaryL(pathExpr, stream, a, "|");
}
/** [19] PathExpr ::= LocationPath
* | FilterExpr
* | FilterExpr '/' RelativeLocationPath
* | FilterExpr '//' RelativeLocationPath
* Unlike most other nodes, this one always generates a node because
* at this point all reverse nodesets must turn into a forward nodeset
*/
function pathExpr(stream, a) {
// We have to do FilterExpr before LocationPath because otherwise
// LocationPath will eat up the name from a function call.
var filter = filterExpr(stream, a);
if (null == filter) {
var loc = locationPath(stream, a);
if (null == loc) {
throw new Error();
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": The expression shouldn't be empty...",
);
}
return a.node("PathExpr", loc);
}
var rel = relativeLocationPath(filter, stream, a, false);
if (filter === rel) return rel;
else return a.node("PathExpr", rel);
}
/** [20] FilterExpr::= PrimaryExpr | FilterExpr Predicate
* aka. FilterExpr ::= PrimaryExpr Predicate*
*/
function filterExpr(stream, a) {
var primary = primaryExpr(stream, a);
if (primary == null) return null;
var pred,
lhs = primary;
while (null != (pred = predicate(lhs, stream, a))) {
lhs = pred;
}
return lhs;
}
/** [21] OrExpr::= AndExpr | OrExpr 'or' AndExpr
*/
function orExpr(stream, a) {
var orig = (stream.peeked || "") + stream.str;
var r = binaryL(andExpr, stream, a, "or");
var now = (stream.peeked || "") + stream.str;
return r;
}
/** [22] AndExpr::= EqualityExpr | AndExpr 'and' EqualityExpr
*/
function andExpr(stream, a) {
return binaryL(equalityExpr, stream, a, "and");
}
/** [23] EqualityExpr::= RelationalExpr | EqualityExpr '=' RelationalExpr
* | EqualityExpr '!=' RelationalExpr
*/
function equalityExpr(stream, a) {
return binaryL(relationalExpr, stream, a, ["=", "!="]);
}
/** [24] RelationalExpr::= AdditiveExpr | RelationalExpr '<' AdditiveExpr
* | RelationalExpr '>' AdditiveExpr
* | RelationalExpr '<=' AdditiveExpr
* | RelationalExpr '>=' AdditiveExpr
*/
function relationalExpr(stream, a) {
return binaryL(additiveExpr, stream, a, ["<", ">", "<=", ">="]);
}
/** [25] AdditiveExpr::= MultiplicativeExpr
* | AdditiveExpr '+' MultiplicativeExpr
* | AdditiveExpr '-' MultiplicativeExpr
*/
function additiveExpr(stream, a) {
return binaryL(multiplicativeExpr, stream, a, ["+", "-"]);
}
/** [26] MultiplicativeExpr::= UnaryExpr
* | MultiplicativeExpr MultiplyOperator UnaryExpr
* | MultiplicativeExpr 'div' UnaryExpr
* | MultiplicativeExpr 'mod' UnaryExpr
*/
function multiplicativeExpr(stream, a) {
return binaryL(unaryExpr, stream, a, ["*", "div", "mod"]);
}
/** [27] UnaryExpr::= UnionExpr | '-' UnaryExpr
*/
function unaryExpr(stream, a) {
if (stream.trypop("-")) {
var e = unaryExpr(stream, a);
if (null == e)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
"Position " +
stream.position() +
": Expected unary expression after -",
);
return a.node("UnaryMinus", e);
} else return unionExpr(stream, a);
}
var astFactory = {
node: function () {
return Array.prototype.slice.call(arguments);
},
};
/***************************************************************************
* Optimizations (TODO) *
***************************************************************************/
/**
* Some things I've been considering:
* 1) a//b becomes a/descendant::b if there's no predicate that uses
* position() or last()
* 2) axis[pred]: when pred doesn't use position, evaluate it just once per
* node in the node-set rather than once per (node, position, last).
* For more optimizations, look up Gecko's optimizer:
* http://mxr.mozilla.org/mozilla-central/source/content/xslt/src/xpath/txXPathOptimizer.cpp
*/
// TODO
function optimize(ast) {}
/***************************************************************************
* Evaluation: axes *
***************************************************************************/
/**
* Data types: For string, number, boolean, we just use Javascript types.
* Node-sets have the form
* {nodes: [node, ...]}
* or {nodes: [node, ...], pos: [[1], [2], ...], lasts: [[1], [2], ...]}
*
* Most of the time, only the node is used and the position information is
* discarded. But if you use a predicate, we need to try every value of
* position and last in case the predicate calls position() or last().
*/
/**
* The NodeMultiSet is a helper class to help generate
* {nodes:[], pos:[], lasts:[]} structures. It is useful for the
* descendant, descendant-or-self, following-sibling, and
* preceding-sibling axes for which we can use a stack to organize things.
*/
function NodeMultiSet(isReverseAxis) {
this.nodes = [];
this.pos = [];
this.lasts = [];
this.nextPos = [];
this.seriesIndexes = []; // index within nodes that each series begins.
this.isReverseAxis = isReverseAxis;
this._pushToNodes = isReverseAxis
? Array.prototype.unshift
: Array.prototype.push;
}
NodeMultiSet.prototype = {
pushSeries: function pushSeries() {
this.nextPos.push(1);
this.seriesIndexes.push(this.nodes.length);
},
popSeries: function popSeries() {
console.assert(0 < this.nextPos.length, this.nextPos);
var last = this.nextPos.pop() - 1,
indexInPos = this.nextPos.length,
seriesBeginIndex = this.seriesIndexes.pop(),
seriesEndIndex = this.nodes.length;
for (var i = seriesBeginIndex; i < seriesEndIndex; ++i) {
console.assert(indexInPos < this.lasts[i].length);
console.assert(undefined === this.lasts[i][indexInPos]);
this.lasts[i][indexInPos] = last;
}
},
finalize: function () {
if (null == this.nextPos) return this;
console.assert(0 === this.nextPos.length);
var lastsJSON = JSON.stringify(this.lasts);
for (var i = 0; i < this.lasts.length; ++i) {
for (var j = 0; j < this.lasts[i].length; ++j) {
console.assert(
null != this.lasts[i][j],
i + "," + j + ":" + lastsJSON,
);
}
}
this.pushSeries =
this.popSeries =
this.addNode =
function () {
throw new Error("Already finalized.");
};
return this;
},
addNode: function addNode(node) {
console.assert(node);
this._pushToNodes.call(this.nodes, node);
this._pushToNodes.call(this.pos, this.nextPos.slice());
this._pushToNodes.call(this.lasts, new Array(this.nextPos.length));
for (var i = 0; i < this.nextPos.length; ++i) this.nextPos[i]++;
},
simplify: function () {
this.finalize();
return { nodes: this.nodes, pos: this.pos, lasts: this.lasts };
},
};
function eachContext(nodeMultiSet) {
var r = [];
for (var i = 0; i < nodeMultiSet.nodes.length; i++) {
var node = nodeMultiSet.nodes[i];
if (!nodeMultiSet.pos) {
r.push({
nodes: [node],
pos: [[i + 1]],
lasts: [[nodeMultiSet.nodes.length]],
});
} else {
for (var j = 0; j < nodeMultiSet.pos[i].length; ++j) {
r.push({
nodes: [node],
pos: [[nodeMultiSet.pos[i][j]]],
lasts: [[nodeMultiSet.lasts[i][j]]],
});
}
}
}
return r;
}
/** Matcher used in the axes.
*/
function NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase) {
this.nodeTypeNum = nodeTypeNum;
this.nodeName = nodeName;
this.shouldLowerCase = shouldLowerCase;
this.nodeNameTest =
null == nodeName
? this._alwaysTrue
: shouldLowerCase
? this._nodeNameLowerCaseEquals
: this._nodeNameEquals;
}
NodeMatcher.prototype = {
matches: function matches(node) {
if (0 === this.nodeTypeNum || this._nodeTypeMatches(node)) {
return this.nodeNameTest(getNodeName(node));
}
return false;
},
_nodeTypeMatches(nodeOrAttr) {
if (nodeOrAttr.constructor.name === "Attr" && this.nodeTypeNum === 2) {
return true;
}
return nodeOrAttr.nodeType === this.nodeTypeNum;
},
_alwaysTrue: function (name) {
return true;
},
_nodeNameEquals: function _nodeNameEquals(name) {
return this.nodeName === name;
},
_nodeNameLowerCaseEquals: function _nodeNameLowerCaseEquals(name) {
return this.nodeName === name.toLowerCase();
},
};
function followingSiblingHelper(
nodeList /*destructive!*/,
nodeTypeNum,
nodeName,
shouldLowerCase,
shift,
peek,
followingNode,
andSelf,
isReverseAxis,
) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(isReverseAxis);
while (0 < nodeList.length) {
// can be if for following, preceding
var node = shift.call(nodeList);
console.assert(node != null);
node = followingNode(node);
nodeMultiSet.pushSeries();
var numPushed = 1;
while (null != node) {
if (!andSelf && matcher.matches(node)) nodeMultiSet.addNode(node);
if (node === peek.call(nodeList)) {
shift.call(nodeList);
nodeMultiSet.pushSeries();
numPushed++;
}
if (andSelf && matcher.matches(node)) nodeMultiSet.addNode(node);
node = followingNode(node);
}
while (0 < numPushed--) nodeMultiSet.popSeries();
}
return nodeMultiSet;
}
/** Returns the next non-descendant node in document order.
* This is the first node in following::node(), if node is the context.
*/
function followingNonDescendantNode(node) {
if (node.ownerElement) {
if (node.ownerElement.firstChild) return node.ownerElement.firstChild;
node = node.ownerElement;
}
do {
if (node.nextSibling) return node.nextSibling;
} while ((node = node.parentNode));
return null;
}
/** Returns the next node in a document-order depth-first search.
* See the definition of document order[1]:
* 1) element
* 2) namespace nodes
* 3) attributes
* 4) children
* [1]: http://www.w3.org/TR/xpath/#dt-document-order
*/
function followingNode(node) {
if (node.ownerElement)
// attributes: following node of element.
node = node.ownerElement;
if (null != node.firstChild) return node.firstChild;
do {
if (null != node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
} while (node);
return null;
}
/** Returns the previous node in document order (excluding attributes
* and namespace nodes).
*/
function precedingNode(node) {
if (node.ownerElement) return node.ownerElement;
if (null != node.previousSibling) {
node = node.previousSibling;
while (null != node.lastChild) {
node = node.lastChild;
}
return node;
}
if (null != node.parentNode) {
return node.parentNode;
}
return null;
}
/** This axis is inefficient if there are many nodes in the nodeList.
* But I think it's a pretty useless axis so it's ok. */
function followingHelper(
nodeList /*destructive!*/,
nodeTypeNum,
nodeName,
shouldLowerCase,
) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(false);
var cursor = nodeList[0];
var unorderedFollowingStarts = [];
for (var i = 0; i < nodeList.length; i++) {
var node = nodeList[i];
var start = followingNonDescendantNode(node);
if (start) unorderedFollowingStarts.push(start);
}
if (0 === unorderedFollowingStarts.length) return { nodes: [] };
var pos = [],
nextPos = [];
var started = 0;
while ((cursor = followingNode(cursor))) {
for (var i = unorderedFollowingStarts.length - 1; i >= 0; i--) {
if (cursor === unorderedFollowingStarts[i]) {
nodeMultiSet.pushSeries();
unorderedFollowingStarts.splice(i, i + 1);
started++;
}
}
if (started && matcher.matches(cursor)) {
nodeMultiSet.addNode(cursor);
}
}
console.assert(0 === unorderedFollowingStarts.length);
for (var i = 0; i < started; i++) nodeMultiSet.popSeries();
return nodeMultiSet.finalize();
}
function precedingHelper(
nodeList /*destructive!*/,
nodeTypeNum,
nodeName,
shouldLowerCase,
) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var cursor = nodeList.pop();
if (null == cursor) return { nodes: {} };
var r = { nodes: [], pos: [], lasts: [] };
var nextParents = [cursor.parentNode || cursor.ownerElement],
nextPos = [1];
while ((cursor = precedingNode(cursor))) {
if (cursor === nodeList[nodeList.length - 1]) {
nextParents.push(nodeList.pop());
nextPos.push(1);
}
var matches = matcher.matches(cursor);
var pos,
someoneUsed = false;
if (matches) pos = nextPos.slice();
for (var i = 0; i < nextParents.length; ++i) {
if (cursor === nextParents[i]) {
nextParents[i] = cursor.parentNode || cursor.ownerElement;
if (matches) {
pos[i] = null;
}
} else {
if (matches) {
pos[i] = nextPos[i]++;
someoneUsed = true;
}
}
}
if (someoneUsed) {
r.nodes.unshift(cursor);
r.pos.unshift(pos);
}
}
for (var i = 0; i < r.pos.length; ++i) {
var lasts = [];
r.lasts.push(lasts);
for (var j = r.pos[i].length - 1; j >= 0; j--) {
if (null == r.pos[i][j]) {
r.pos[i].splice(j, j + 1);
} else {
lasts.unshift(nextPos[j] - 1);
}
}
}
return r;
}
/** node-set, axis -> node-set */
function descendantDfs(
nodeMultiSet,
node,
remaining,
matcher,
andSelf,
attrIndices,
attrNodes,
) {
while (0 < remaining.length && null != remaining[0].ownerElement) {
var attr = remaining.shift();
if (andSelf && matcher.matches(attr)) {
attrNodes.push(attr);
attrIndices.push(nodeMultiSet.nodes.length);
}
}
if (null != node && !andSelf) {
if (matcher.matches(node)) nodeMultiSet.addNode(node);
}
var pushed = false;
if (null == node) {
if (0 === remaining.length) return;
node = remaining.shift();
nodeMultiSet.pushSeries();
pushed = true;
} else if (0 < remaining.length && node === remaining[0]) {
nodeMultiSet.pushSeries();
pushed = true;
remaining.shift();
}
if (andSelf) {
if (matcher.matches(node)) nodeMultiSet.addNode(node);
}
// TODO: use optimization. Also try element.getElementsByTagName
// var nodeList = 1 === nodeTypeNum && null != node.children ? node.children : node.childNodes;
var nodeList = node.childNodes;
for (var j = 0; j < nodeList.length; ++j) {
var child = nodeList[j];
descendantDfs(
nodeMultiSet,
child,
remaining,