forked from SeleniumHQ/selenium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxpath.js
2481 lines (2120 loc) · 69.3 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
// Copyright 2005 Google Inc.
// All Rights Reserved
//
// An XPath parser and evaluator written in JavaScript. The
// implementation is complete except for functions handling
// namespaces.
//
// Reference: [XPATH] XPath Specification
// <http://www.w3.org/TR/1999/REC-xpath-19991116>.
//
//
// The API of the parser has several parts:
//
// 1. The parser function xpathParse() that takes a string and returns
// an expession object.
//
// 2. The expression object that has an evaluate() method to evaluate the
// XPath expression it represents. (It is actually a hierarchy of
// objects that resembles the parse tree, but an application will call
// evaluate() only on the top node of this hierarchy.)
//
// 3. The context object that is passed as an argument to the evaluate()
// method, which represents the DOM context in which the expression is
// evaluated.
//
// 4. The value object that is returned from evaluate() and represents
// values of the different types that are defined by XPath (number,
// string, boolean, and node-set), and allows to convert between them.
//
// These parts are near the top of the file, the functions and data
// that are used internally follow after them.
//
//
// Author: Steffen Meschkat <[email protected]>
// The entry point for the parser.
//
// @param expr a string that contains an XPath expression.
// @return an expression object that can be evaluated with an
// expression context.
function xpathParse(expr) {
xpathLog('parse ' + expr);
xpathParseInit();
var cached = xpathCacheLookup(expr);
if (cached) {
xpathLog(' ... cached');
return cached;
}
// Optimize for a few common cases: simple attribute node tests
// (@id), simple element node tests (page), variable references
// ($address), numbers (4), multi-step path expressions where each
// step is a plain element node test
// (page/overlay/locations/location).
if (expr.match(/^(\$|@)?\w+$/i)) {
var ret = makeSimpleExpr(expr);
xpathParseCache[expr] = ret;
xpathLog(' ... simple');
return ret;
}
if (expr.match(/^\w+(\/\w+)*$/i)) {
var ret = makeSimpleExpr2(expr);
xpathParseCache[expr] = ret;
xpathLog(' ... simple 2');
return ret;
}
var cachekey = expr; // expr is modified during parse
var stack = [];
var ahead = null;
var previous = null;
var done = false;
var parse_count = 0;
var lexer_count = 0;
var reduce_count = 0;
while (!done) {
parse_count++;
expr = expr.replace(/^\s*/, '');
previous = ahead;
ahead = null;
var rule = null;
var match = '';
for (var i = 0; i < xpathTokenRules.length; ++i) {
var result = xpathTokenRules[i].re.exec(expr);
lexer_count++;
if (result && result.length > 0 && result[0].length > match.length) {
rule = xpathTokenRules[i];
match = result[0];
break;
}
}
// Special case: allow operator keywords to be element and
// variable names.
// NOTE(mesch): The parser resolves conflicts by looking ahead,
// and this is the only case where we look back to
// disambiguate. So this is indeed something different, and
// looking back is usually done in the lexer (via states in the
// general case, called "start conditions" in flex(1)). Also,the
// conflict resolution in the parser is not as robust as it could
// be, so I'd like to keep as much off the parser as possible (all
// these precedence values should be computed from the grammar
// rules and possibly associativity declarations, as in bison(1),
// and not explicitly set.
if (rule &&
(rule == TOK_DIV ||
rule == TOK_MOD ||
rule == TOK_AND ||
rule == TOK_OR) &&
(!previous ||
previous.tag == TOK_AT ||
previous.tag == TOK_DSLASH ||
previous.tag == TOK_SLASH ||
previous.tag == TOK_AXIS ||
previous.tag == TOK_DOLLAR)) {
rule = TOK_QNAME;
}
if (rule) {
expr = expr.substr(match.length);
xpathLog('token: ' + match + ' -- ' + rule.label);
ahead = {
tag: rule,
match: match,
prec: rule.prec ? rule.prec : 0, // || 0 is removed by the compiler
expr: makeTokenExpr(match)
};
} else {
xpathLog('DONE');
done = true;
}
while (xpathReduce(stack, ahead)) {
reduce_count++;
xpathLog('stack: ' + stackToString(stack));
}
}
xpathLog('stack: ' + stackToString(stack));
// DGF any valid XPath should "reduce" to a single Expr token
if (stack.length != 1) {
throw 'XPath parse error ' + cachekey + ':\n' + stackToString(stack);
}
var result = stack[0].expr;
xpathParseCache[cachekey] = result;
xpathLog('XPath parse: ' + parse_count + ' / ' +
lexer_count + ' / ' + reduce_count);
return result;
}
var xpathParseCache = {};
function xpathCacheLookup(expr) {
return xpathParseCache[expr];
}
/*DGF xpathReduce is where the magic happens in this parser.
Skim down to the bottom of this file to find the table of
grammatical rules and precedence numbers, "The productions of the grammar".
The idea here
is that we want to take a stack of tokens and apply
grammatical rules to them, "reducing" them to higher-level
tokens. Ultimately, any valid XPath should reduce to exactly one
"Expr" token.
Reduce too early or too late and you'll have two tokens that can't reduce
to single Expr. For example, you may hastily reduce a qname that
should name a function, incorrectly treating it as a tag name.
Or you may reduce too late, accidentally reducing the last part of the
XPath into a top-level "Expr" that won't reduce with earlier parts of
the XPath.
A "cand" is a grammatical rule candidate, with a given precedence
number. "ahead" is the upcoming token, which also has a precedence
number. If the token has a higher precedence number than
the rule candidate, we'll "shift" the token onto the token stack,
instead of immediately applying the rule candidate.
Some tokens have left associativity, in which case we shift when they
have LOWER precedence than the candidate.
*/
function xpathReduce(stack, ahead) {
var cand = null;
if (stack.length > 0) {
var top = stack[stack.length-1];
var ruleset = xpathRules[top.tag.key];
if (ruleset) {
for (var i = 0; i < ruleset.length; ++i) {
var rule = ruleset[i];
var match = xpathMatchStack(stack, rule[1]);
if (match.length) {
cand = {
tag: rule[0],
rule: rule,
match: match
};
cand.prec = xpathGrammarPrecedence(cand);
break;
}
}
}
}
var ret;
if (cand && (!ahead || cand.prec > ahead.prec ||
(ahead.tag.left && cand.prec >= ahead.prec))) {
for (var i = 0; i < cand.match.matchlength; ++i) {
stack.pop();
}
xpathLog('reduce ' + cand.tag.label + ' ' + cand.prec +
' ahead ' + (ahead ? ahead.tag.label + ' ' + ahead.prec +
(ahead.tag.left ? ' left' : '')
: ' none '));
var matchexpr = mapExpr(cand.match, function(m) { return m.expr; });
xpathLog('going to apply ' + cand.rule[3].toString());
cand.expr = cand.rule[3].apply(null, matchexpr);
stack.push(cand);
ret = true;
} else {
if (ahead) {
xpathLog('shift ' + ahead.tag.label + ' ' + ahead.prec +
(ahead.tag.left ? ' left' : '') +
' over ' + (cand ? cand.tag.label + ' ' +
cand.prec : ' none'));
stack.push(ahead);
}
ret = false;
}
return ret;
}
function xpathMatchStack(stack, pattern) {
// NOTE(mesch): The stack matches for variable cardinality are
// greedy but don't do backtracking. This would be an issue only
// with rules of the form A* A, i.e. with an element with variable
// cardinality followed by the same element. Since that doesn't
// occur in the grammar at hand, all matches on the stack are
// unambiguous.
var S = stack.length;
var P = pattern.length;
var p, s;
var match = [];
match.matchlength = 0;
var ds = 0;
for (p = P - 1, s = S - 1; p >= 0 && s >= 0; --p, s -= ds) {
ds = 0;
var qmatch = [];
if (pattern[p] == Q_MM) {
p -= 1;
match.push(qmatch);
while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) {
qmatch.push(stack[s - ds]);
ds += 1;
match.matchlength += 1;
}
} else if (pattern[p] == Q_01) {
p -= 1;
match.push(qmatch);
while (s - ds >= 0 && ds < 2 && stack[s - ds].tag == pattern[p]) {
qmatch.push(stack[s - ds]);
ds += 1;
match.matchlength += 1;
}
} else if (pattern[p] == Q_1M) {
p -= 1;
match.push(qmatch);
if (stack[s].tag == pattern[p]) {
while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) {
qmatch.push(stack[s - ds]);
ds += 1;
match.matchlength += 1;
}
} else {
return [];
}
} else if (stack[s].tag == pattern[p]) {
match.push(stack[s]);
ds += 1;
match.matchlength += 1;
} else {
return [];
}
reverseInplace(qmatch);
qmatch.expr = mapExpr(qmatch, function(m) { return m.expr; });
}
reverseInplace(match);
if (p == -1) {
return match;
} else {
return [];
}
}
function xpathTokenPrecedence(tag) {
return tag.prec || 2;
}
function xpathGrammarPrecedence(frame) {
var ret = 0;
if (frame.rule) { /* normal reduce */
if (frame.rule.length >= 3 && frame.rule[2] >= 0) {
ret = frame.rule[2];
} else {
for (var i = 0; i < frame.rule[1].length; ++i) {
var p = xpathTokenPrecedence(frame.rule[1][i]);
ret = Math.max(ret, p);
}
}
} else if (frame.tag) { /* TOKEN match */
ret = xpathTokenPrecedence(frame.tag);
} else if (frame.length) { /* Q_ match */
for (var j = 0; j < frame.length; ++j) {
var p = xpathGrammarPrecedence(frame[j]);
ret = Math.max(ret, p);
}
}
return ret;
}
function stackToString(stack) {
var ret = '';
for (var i = 0; i < stack.length; ++i) {
if (ret) {
ret += '\n';
}
ret += stack[i].tag.label;
}
return ret;
}
// XPath expression evaluation context. An XPath context consists of a
// DOM node, a list of DOM nodes that contains this node, a number
// that represents the position of the single node in the list, and a
// current set of variable bindings. (See XPath spec.)
//
// The interface of the expression context:
//
// Constructor -- gets the node, its position, the node set it
// belongs to, and a parent context as arguments. The parent context
// is used to implement scoping rules for variables: if a variable
// is not found in the current context, it is looked for in the
// parent context, recursively. Except for node, all arguments have
// default values: default position is 0, default node set is the
// set that contains only the node, and the default parent is null.
//
// Notice that position starts at 0 at the outside interface;
// inside XPath expressions this shows up as position()=1.
//
// clone() -- creates a new context with the current context as
// parent. If passed as argument to clone(), the new context has a
// different node, position, or node set. What is not passed is
// inherited from the cloned context.
//
// setVariable(name, expr) -- binds given XPath expression to the
// name.
//
// getVariable(name) -- what the name says.
//
// setNode(position) -- sets the context to the node at the given
// position. Needed to implement scoping rules for variables in
// XPath. (A variable is visible to all subsequent siblings, not
// only to its children.)
//
// set/isCaseInsensitive -- specifies whether node name tests should
// be case sensitive. If you're executing xpaths against a regular
// HTML DOM, you probably don't want case-sensitivity, because
// browsers tend to disagree about whether elements & attributes
// should be upper/lower case. If you're running xpaths in an
// XSLT instance, you probably DO want case sensitivity, as per the
// XSL spec.
//
// set/isReturnOnFirstMatch -- whether XPath evaluation should quit as soon
// as a result is found. This is an optimization that might make sense if you
// only care about the first result.
//
// set/isIgnoreNonElementNodesForNTA -- whether to ignore non-element nodes
// when evaluating the "node()" any node test. While technically this is
// contrary to the XPath spec, practically it can enhance performance
// significantly, and makes sense if you a) use "node()" when you mean "*",
// and b) use "//" when you mean "/descendant::*/".
function ExprContext(node, opt_position, opt_nodelist, opt_parent,
opt_caseInsensitive, opt_ignoreAttributesWithoutValue,
opt_returnOnFirstMatch, opt_ignoreNonElementNodesForNTA)
{
this.node = node;
this.position = opt_position || 0;
this.nodelist = opt_nodelist || [ node ];
this.variables = {};
this.parent = opt_parent || null;
this.caseInsensitive = opt_caseInsensitive || false;
this.ignoreAttributesWithoutValue = opt_ignoreAttributesWithoutValue || false;
this.returnOnFirstMatch = opt_returnOnFirstMatch || false;
this.ignoreNonElementNodesForNTA = opt_ignoreNonElementNodesForNTA || false;
if (opt_parent) {
this.root = opt_parent.root;
} else if (this.node.nodeType == DOM_DOCUMENT_NODE) {
// NOTE(mesch): DOM Spec stipulates that the ownerDocument of a
// document is null. Our root, however is the document that we are
// processing, so the initial context is created from its document
// node, which case we must handle here explcitly.
this.root = node;
} else {
this.root = node.ownerDocument;
}
}
ExprContext.prototype.clone = function(opt_node, opt_position, opt_nodelist) {
return new ExprContext(
opt_node || this.node,
typeof opt_position != 'undefined' ? opt_position : this.position,
opt_nodelist || this.nodelist, this, this.caseInsensitive,
this.ignoreAttributesWithoutValue, this.returnOnFirstMatch,
this.ignoreNonElementNodesForNTA);
};
ExprContext.prototype.setVariable = function(name, value) {
if (value instanceof StringValue || value instanceof BooleanValue ||
value instanceof NumberValue || value instanceof NodeSetValue) {
this.variables[name] = value;
return;
}
if ('true' === value) {
this.variables[name] = new BooleanValue(true);
} else if ('false' === value) {
this.variables[name] = new BooleanValue(false);
} else if (TOK_NUMBER.re.test(value)) {
this.variables[name] = new NumberValue(value);
} else {
// DGF What if it's null?
this.variables[name] = new StringValue(value);
}
};
ExprContext.prototype.getVariable = function(name) {
if (typeof this.variables[name] != 'undefined') {
return this.variables[name];
} else if (this.parent) {
return this.parent.getVariable(name);
} else {
return null;
}
};
ExprContext.prototype.setNode = function(position) {
this.node = this.nodelist[position];
this.position = position;
};
ExprContext.prototype.contextSize = function() {
return this.nodelist.length;
};
ExprContext.prototype.isCaseInsensitive = function() {
return this.caseInsensitive;
};
ExprContext.prototype.setCaseInsensitive = function(caseInsensitive) {
return this.caseInsensitive = caseInsensitive;
};
ExprContext.prototype.isIgnoreAttributesWithoutValue = function() {
return this.ignoreAttributesWithoutValue;
};
ExprContext.prototype.setIgnoreAttributesWithoutValue = function(ignore) {
return this.ignoreAttributesWithoutValue = ignore;
};
ExprContext.prototype.isReturnOnFirstMatch = function() {
return this.returnOnFirstMatch;
};
ExprContext.prototype.setReturnOnFirstMatch = function(returnOnFirstMatch) {
return this.returnOnFirstMatch = returnOnFirstMatch;
};
ExprContext.prototype.isIgnoreNonElementNodesForNTA = function() {
return this.ignoreNonElementNodesForNTA;
};
ExprContext.prototype.setIgnoreNonElementNodesForNTA = function(ignoreNonElementNodesForNTA) {
return this.ignoreNonElementNodesForNTA = ignoreNonElementNodesForNTA;
};
// XPath expression values. They are what XPath expressions evaluate
// to. Strangely, the different value types are not specified in the
// XPath syntax, but only in the semantics, so they don't show up as
// nonterminals in the grammar. Yet, some expressions are required to
// evaluate to particular types, and not every type can be coerced
// into every other type. Although the types of XPath values are
// similar to the types present in JavaScript, the type coercion rules
// are a bit peculiar, so we explicitly model XPath types instead of
// mapping them onto JavaScript types. (See XPath spec.)
//
// The four types are:
//
// StringValue
//
// NumberValue
//
// BooleanValue
//
// NodeSetValue
//
// The common interface of the value classes consists of methods that
// implement the XPath type coercion rules:
//
// stringValue() -- returns the value as a JavaScript String,
//
// numberValue() -- returns the value as a JavaScript Number,
//
// booleanValue() -- returns the value as a JavaScript Boolean,
//
// nodeSetValue() -- returns the value as a JavaScript Array of DOM
// Node objects.
//
function StringValue(value) {
this.value = value;
this.type = 'string';
}
StringValue.prototype.stringValue = function() {
return this.value;
}
StringValue.prototype.booleanValue = function() {
return this.value.length > 0;
}
StringValue.prototype.numberValue = function() {
return this.value - 0;
}
StringValue.prototype.nodeSetValue = function() {
throw this;
}
function BooleanValue(value) {
this.value = value;
this.type = 'boolean';
}
BooleanValue.prototype.stringValue = function() {
return '' + this.value;
}
BooleanValue.prototype.booleanValue = function() {
return this.value;
}
BooleanValue.prototype.numberValue = function() {
return this.value ? 1 : 0;
}
BooleanValue.prototype.nodeSetValue = function() {
throw this;
}
function NumberValue(value) {
this.value = value;
this.type = 'number';
}
NumberValue.prototype.stringValue = function() {
return '' + this.value;
}
NumberValue.prototype.booleanValue = function() {
return !!this.value;
}
NumberValue.prototype.numberValue = function() {
return this.value - 0;
}
NumberValue.prototype.nodeSetValue = function() {
throw this;
}
function NodeSetValue(value) {
this.value = value;
this.type = 'node-set';
}
NodeSetValue.prototype.stringValue = function() {
if (this.value.length == 0) {
return '';
} else {
return xmlValue(this.value[0]);
}
}
NodeSetValue.prototype.booleanValue = function() {
return this.value.length > 0;
}
NodeSetValue.prototype.numberValue = function() {
return this.stringValue() - 0;
}
NodeSetValue.prototype.nodeSetValue = function() {
return this.value;
};
// XPath expressions. They are used as nodes in the parse tree and
// possess an evaluate() method to compute an XPath value given an XPath
// context. Expressions are returned from the parser. Teh set of
// expression classes closely mirrors the set of non terminal symbols
// in the grammar. Every non trivial nonterminal symbol has a
// corresponding expression class.
//
// The common expression interface consists of the following methods:
//
// evaluate(context) -- evaluates the expression, returns a value.
//
// toString() -- returns the XPath text representation of the
// expression (defined in xsltdebug.js).
//
// parseTree(indent) -- returns a parse tree representation of the
// expression (defined in xsltdebug.js).
function TokenExpr(m) {
this.value = m;
}
TokenExpr.prototype.evaluate = function() {
return new StringValue(this.value);
};
function LocationExpr() {
this.absolute = false;
this.steps = [];
}
LocationExpr.prototype.appendStep = function(s) {
var combinedStep = this._combineSteps(this.steps[this.steps.length-1], s);
if (combinedStep) {
this.steps[this.steps.length-1] = combinedStep;
} else {
this.steps.push(s);
}
}
LocationExpr.prototype.prependStep = function(s) {
var combinedStep = this._combineSteps(s, this.steps[0]);
if (combinedStep) {
this.steps[0] = combinedStep;
} else {
this.steps.unshift(s);
}
};
// DGF try to combine two steps into one step (perf enhancement)
LocationExpr.prototype._combineSteps = function(prevStep, nextStep) {
if (!prevStep) return null;
if (!nextStep) return null;
var hasPredicates = (prevStep.predicates && prevStep.predicates.length > 0);
if (prevStep.nodetest instanceof NodeTestAny && !hasPredicates) {
// maybe suitable to be combined
if (prevStep.axis == xpathAxis.DESCENDANT_OR_SELF) {
if (nextStep.axis == xpathAxis.CHILD) {
// HBC - commenting out, because this is not a valid reduction
//nextStep.axis = xpathAxis.DESCENDANT;
//return nextStep;
} else if (nextStep.axis == xpathAxis.SELF) {
nextStep.axis = xpathAxis.DESCENDANT_OR_SELF;
return nextStep;
}
} else if (prevStep.axis == xpathAxis.DESCENDANT) {
if (nextStep.axis == xpathAxis.SELF) {
nextStep.axis = xpathAxis.DESCENDANT;
return nextStep;
}
}
}
return null;
}
LocationExpr.prototype.evaluate = function(ctx) {
var start;
if (this.absolute) {
start = ctx.root;
} else {
start = ctx.node;
}
var nodes = [];
xPathStep(nodes, this.steps, 0, start, ctx);
return new NodeSetValue(nodes);
};
function xPathStep(nodes, steps, step, input, ctx) {
var s = steps[step];
var ctx2 = ctx.clone(input);
if (ctx.returnOnFirstMatch && !s.hasPositionalPredicate) {
var nodelist = s.evaluate(ctx2).nodeSetValue();
// the predicates were not processed in the last evaluate(), so that we can
// process them here with the returnOnFirstMatch optimization. We do a
// depth-first grab at any nodes that pass the predicate tests. There is no
// way to optimize when predicates contain positional selectors, including
// indexes or uses of the last() or position() functions, because they
// typically require the entire nodelist for context. Process without
// optimization if we encounter such selectors.
var nLength = nodelist.length;
var pLength = s.predicate.length;
nodelistLoop:
for (var i = 0; i < nLength; ++i) {
var n = nodelist[i];
for (var j = 0; j < pLength; ++j) {
if (!s.predicate[j].evaluate(ctx.clone(n, i, nodelist)).booleanValue()) {
continue nodelistLoop;
}
}
// n survived the predicate tests!
if (step == steps.length - 1) {
nodes.push(n);
}
else {
xPathStep(nodes, steps, step + 1, n, ctx);
}
if (nodes.length > 0) {
break;
}
}
}
else {
// set returnOnFirstMatch to false for the cloned ExprContext, because
// behavior in StepExpr.prototype.evaluate is driven off its value. Note
// that the original context may still have true for this value.
ctx2.returnOnFirstMatch = false;
var nodelist = s.evaluate(ctx2).nodeSetValue();
for (var i = 0; i < nodelist.length; ++i) {
if (step == steps.length - 1) {
nodes.push(nodelist[i]);
} else {
xPathStep(nodes, steps, step + 1, nodelist[i], ctx);
}
}
}
}
function StepExpr(axis, nodetest, opt_predicate) {
this.axis = axis;
this.nodetest = nodetest;
this.predicate = opt_predicate || [];
this.hasPositionalPredicate = false;
for (var i = 0; i < this.predicate.length; ++i) {
if (predicateExprHasPositionalSelector(this.predicate[i].expr)) {
this.hasPositionalPredicate = true;
break;
}
}
}
StepExpr.prototype.appendPredicate = function(p) {
this.predicate.push(p);
if (!this.hasPositionalPredicate) {
this.hasPositionalPredicate = predicateExprHasPositionalSelector(p.expr);
}
}
StepExpr.prototype.evaluate = function(ctx) {
var input = ctx.node;
var nodelist = [];
var skipNodeTest = false;
if (this.nodetest instanceof NodeTestAny) {
skipNodeTest = true;
}
// NOTE(mesch): When this was a switch() statement, it didn't work
// in Safari/2.0. Not sure why though; it resulted in the JavaScript
// console output "undefined" (without any line number or so).
if (this.axis == xpathAxis.ANCESTOR_OR_SELF) {
nodelist.push(input);
for (var n = input.parentNode; n; n = n.parentNode) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.ANCESTOR) {
for (var n = input.parentNode; n; n = n.parentNode) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.ATTRIBUTE) {
if (this.nodetest.name != undefined) {
// single-attribute step
if (input.attributes) {
if (input.attributes instanceof Array) {
// probably evaluating on document created by xmlParse()
copyArray(nodelist, input.attributes);
}
else {
if (this.nodetest.name == 'style') {
var value = input.getAttribute('style');
if (value && typeof(value) != 'string') {
// this is the case where indexing into the attributes array
// doesn't give us the attribute node in IE - we create our own
// node instead
nodelist.push(XNode.create(DOM_ATTRIBUTE_NODE, 'style',
value.cssText, document));
}
else {
nodelist.push(input.attributes[this.nodetest.name]);
}
}
else {
nodelist.push(input.attributes[this.nodetest.name]);
}
}
}
}
else {
// all-attributes step
if (ctx.ignoreAttributesWithoutValue) {
copyArrayIgnoringAttributesWithoutValue(nodelist, input.attributes);
}
else {
copyArray(nodelist, input.attributes);
}
}
} else if (this.axis == xpathAxis.CHILD) {
copyArray(nodelist, input.childNodes);
} else if (this.axis == xpathAxis.DESCENDANT_OR_SELF) {
if (this.nodetest.evaluate(ctx).booleanValue()) {
nodelist.push(input);
}
var tagName = xpathExtractTagNameFromNodeTest(this.nodetest, ctx.ignoreNonElementNodesForNTA);
xpathCollectDescendants(nodelist, input, tagName);
if (tagName) skipNodeTest = true;
} else if (this.axis == xpathAxis.DESCENDANT) {
var tagName = xpathExtractTagNameFromNodeTest(this.nodetest, ctx.ignoreNonElementNodesForNTA);
xpathCollectDescendants(nodelist, input, tagName);
if (tagName) skipNodeTest = true;
} else if (this.axis == xpathAxis.FOLLOWING) {
for (var n = input; n; n = n.parentNode) {
for (var nn = n.nextSibling; nn; nn = nn.nextSibling) {
nodelist.push(nn);
xpathCollectDescendants(nodelist, nn);
}
}
} else if (this.axis == xpathAxis.FOLLOWING_SIBLING) {
for (var n = input.nextSibling; n; n = n.nextSibling) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.NAMESPACE) {
alert('not implemented: axis namespace');
} else if (this.axis == xpathAxis.PARENT) {
if (input.parentNode) {
nodelist.push(input.parentNode);
}
} else if (this.axis == xpathAxis.PRECEDING) {
for (var n = input; n; n = n.parentNode) {
for (var nn = n.previousSibling; nn; nn = nn.previousSibling) {
nodelist.push(nn);
xpathCollectDescendantsReverse(nodelist, nn);
}
}
} else if (this.axis == xpathAxis.PRECEDING_SIBLING) {
for (var n = input.previousSibling; n; n = n.previousSibling) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.SELF) {
nodelist.push(input);
} else {
throw 'ERROR -- NO SUCH AXIS: ' + this.axis;
}
if (!skipNodeTest) {
// process node test
var nodelist0 = nodelist;
nodelist = [];
for (var i = 0; i < nodelist0.length; ++i) {
var n = nodelist0[i];
if (this.nodetest.evaluate(ctx.clone(n, i, nodelist0)).booleanValue()) {
nodelist.push(n);
}
}
}
// process predicates
if (!ctx.returnOnFirstMatch) {
for (var i = 0; i < this.predicate.length; ++i) {
var nodelist0 = nodelist;
nodelist = [];
for (var ii = 0; ii < nodelist0.length; ++ii) {
var n = nodelist0[ii];
if (this.predicate[i].evaluate(ctx.clone(n, ii, nodelist0)).booleanValue()) {
nodelist.push(n);
}
}
}
}
return new NodeSetValue(nodelist);
};
function NodeTestAny() {
this.value = new BooleanValue(true);
}
NodeTestAny.prototype.evaluate = function(ctx) {
return this.value;
};
function NodeTestElementOrAttribute() {}
NodeTestElementOrAttribute.prototype.evaluate = function(ctx) {
return new BooleanValue(
ctx.node.nodeType == DOM_ELEMENT_NODE ||
ctx.node.nodeType == DOM_ATTRIBUTE_NODE);
}
function NodeTestText() {}
NodeTestText.prototype.evaluate = function(ctx) {
return new BooleanValue(ctx.node.nodeType == DOM_TEXT_NODE);
}
function NodeTestComment() {}
NodeTestComment.prototype.evaluate = function(ctx) {
return new BooleanValue(ctx.node.nodeType == DOM_COMMENT_NODE);
}
function NodeTestPI(target) {
this.target = target;
}
NodeTestPI.prototype.evaluate = function(ctx) {
return new
BooleanValue(ctx.node.nodeType == DOM_PROCESSING_INSTRUCTION_NODE &&
(!this.target || ctx.node.nodeName == this.target));
}
function NodeTestNC(nsprefix) {
this.regex = new RegExp("^" + nsprefix + ":");
this.nsprefix = nsprefix;
}
NodeTestNC.prototype.evaluate = function(ctx) {
var n = ctx.node;
return new BooleanValue(this.regex.match(n.nodeName));
}