Debian Codegraph @

net/sf/saxon/expr/SlashExpression.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.instruct.CopyOf;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.expr.sort.DocumentSorter;
14 import net.sf.saxon.functions.Doc;
15 import net.sf.saxon.functions.DocumentFn;
16 import net.sf.saxon.functions.KeyFn;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.pattern.*;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.type.*;
22 import net.sf.saxon.value.Cardinality;
23 import net.sf.saxon.value.IntegerValue;
24 import net.sf.saxon.value.SequenceType;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Stack;
29
30
31 /**
32 * A slash expression is any expression using the binary slash operator "/". The parser initially generates a slash
33 * expression for all occurrences of the binary "/" operator, wrapped in a documentSort() function to do the sorting
34 * and de-duplication required by the semantics of path expressions. The documentSort() is subsequently stripped off
35 * by the optimizer if sorting and deduplication is found to be unnecessary. The slash expression itself, therefore,
36 * does not perform sorting or de-duplication.
37 */
38
39 public class SlashExpression extends BinaryExpression
40 implements ContextSwitchingExpression {
41
42 boolean contextFree;
43
44 /**
45 * Constructor
46 *
47 * @param start The left hand operand (which must always select a sequence of nodes).
48 * @param step The step to be followed from each node in the start expression to yield a new
49 * sequence; this may return either nodes or atomic values (but not a mixture of the two)
50 */
51
52 public SlashExpression(Expression start, Expression step) {
53 super(start, Token.SLASH, step);
54 }
55
56 @Override
57 protected OperandRole getOperandRole(int arg) {
58 return arg==0 ? OperandRole.FOCUS_CONTROLLING_SELECT : OperandRole.FOCUS_CONTROLLED_ACTION;
59 }
60
61 /**
62 * Get the left-hand operand
63 * @return the left-hand operand
64 */
65
66 public Expression getStart() {
67 return getLhsExpression();
68 }
69
70 /**
71 * Set the left-hand operand
72 * @param start the left-hand operand
73 */
74
75 public void setStart(Expression start) {
76 setLhsExpression(start);
77 }
78
79 /**
80 * Get the right-hand operand
81 * @return the right-hand operand
82 */
83
84 public Expression getStep() {
85 return getRhsExpression();
86 }
87
88 /**
89 * Set the right-hand operand
90 * @param step the right-hand operand
91 */
92
93 public void setStep(Expression step) {
94 setRhsExpression(step);
95 }
96
97 @Override
98 public String getExpressionName() {
99 return "pathExpression";
100 }
101
102 /**
103 * Get the start expression (the left-hand operand)
104 *
105 * @return the first operand
106 */
107
108 public Expression getSelectExpression() {
109 return getStart();
110 }
111
112 /**
113 * Get the step expression (the right-hand operand)
114 *
115 * @return the second operand
116 */
117
118 public Expression getActionExpression() {
119 return getStep();
120 }
121
122 /**
123 * Determine the data type of the items returned by this exprssion
124 *
125 * @return the type of the step
126 */
127
128 /*@NotNull*/
129 public final ItemType getItemType() {
130 return getStep().getItemType();
131 }
132
133
134 /**
135 * Get the static type of the expression as a UType, following precisely the type
136 * inference rules defined in the XSLT 3.0 specification.
137 *
138 * @return the static item type of the expression according to the XSLT 3.0 defined rules
139 * @param contextItemType
140 */
141 @Override
142 public UType getStaticUType(UType contextItemType) {
143 return getStep().getStaticUType(getStart().getStaticUType(contextItemType));
144 }
145
146
147 /**
148 * For an expression that returns an integer or a sequence of integers, get
149 * a lower and upper bound on the values of the integers that may be returned, from
150 * static analysis. The default implementation returns null, meaning "unknown" or
151 * "not applicable". Other implementations return an array of two IntegerValue objects,
152 * representing the lower and upper bounds respectively. The values
153 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
154 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
155 * are used to indicate values limited by the size of a string or the size of a sequence.
156 *
157 * @return the lower and upper bounds of integer values in the result, or null to indicate
158 * unknown or not applicable.
159 */
160 @Override
161 public IntegerValue[] getIntegerBounds() {
162 return getStep().getIntegerBounds();
163 }
164
165 /**
166 * Type-check the expression
167 */
168
169 /*@NotNull*/
170 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
171
172 getLhs().typeCheck(visitor, contextInfo);
173
174 // If the first expression is known to be empty, just return empty without checking the step expression.
175 // (Checking the step expression can cause spurious errors, such as "the context item is absent")
176
177 if (Literal.isEmptySequence(getStart())) {
178 return getStart();
179 }
180
181 // The first operand must be of type node()*
182
183 Configuration config = visitor.getConfiguration();
184 TypeChecker tc = config.getTypeChecker(false);
185 RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, "/", 0);
186 role0.setErrorCode("XPTY0019");
187 setStart(tc.staticTypeCheck(getStart(), SequenceType.NODE_SEQUENCE, role0, visitor));
188
189 // Now check the second operand
190
191 ItemType startType = getStart().getItemType();
192 if (startType == ErrorType.getInstance()) {
193 // implies the start expression will return an empty sequence, so the whole expression is void
194 return Literal.makeEmptySequence();
195 }
196
197 ContextItemStaticInfo cit = config.makeContextItemStaticInfo(startType, false);
198 cit.setContextSettingExpression(getStart());
199 getRhs().typeCheck(visitor, cit);
200
201 // If the expression has the form (a//descendant-or-self::node())/b, try to simplify it to
202 // use the descendant axis
203
204 Expression e2 = simplifyDescendantPath(visitor.getStaticContext());
205 if (e2 != null) {
206 return e2.typeCheck(visitor, contextInfo);
207 }
208
209 if (getStart() instanceof ContextItemExpression &&
210 getStep().hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
211 return getStep();
212 }
213
214 if (getStep() instanceof ContextItemExpression &&
215 getStart().hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
216 return getStart();
217 }
218
219 if (getStep() instanceof AxisExpression && ((AxisExpression) getStep()).getAxis() == AxisInfo.SELF &&
220 config.getTypeHierarchy().isSubType(startType, getStep().getItemType())) {
221 return getStart();
222 }
223
224 return this;
225 }
226
227 // Simplify an expression of the form a//b, where b has no positional filters.
228 // This comes out of the constructor above as (a/descendent-or-self::node())/child::b,
229 // but it is equivalent to a/descendant::b; and the latter is better as it
230 // doesn't require sorting. Note that we can't do this until type information is available,
231 // as we need to know whether any filters are positional or not.
232
233 public SlashExpression simplifyDescendantPath(StaticContext env) {
234
235 Expression underlyingStep = getStep();
236 while (underlyingStep instanceof FilterExpression) {
237 if (((FilterExpression) underlyingStep).isPositional(env.getConfiguration().getTypeHierarchy())) {
238 return null;
239 }
240 underlyingStep = ((FilterExpression) underlyingStep).getSelectExpression();
241 }
242
243 if (!(underlyingStep instanceof AxisExpression)) {
244 return null;
245 }
246
247 Expression st = getStart();
248
249 // detect .//x as a special case; this will appear as descendant-or-self::node()/x
250
251 if (st instanceof AxisExpression) {
252 AxisExpression stax = (AxisExpression) st;
253 if (stax.getAxis() != AxisInfo.DESCENDANT_OR_SELF) {
254 return null;
255 }
256 ContextItemExpression cie = new ContextItemExpression();
257 ExpressionTool.copyLocationInfo(this, cie);
258 st = ExpressionTool.makePathExpression(cie, stax.copy(new RebindingMap()));
259 ExpressionTool.copyLocationInfo(this, st);
260 }
261
262 if (!(st instanceof SlashExpression)) {
263 return null;
264 }
265
266 SlashExpression startPath = (SlashExpression) st;
267 if (!(startPath.getStep() instanceof AxisExpression)) {
268 return null;
269 }
270
271 AxisExpression mid = (AxisExpression) startPath.getStep();
272 if (mid.getAxis() != AxisInfo.DESCENDANT_OR_SELF) {
273 return null;
274 }
275
276
277
278 NodeTest test = mid.getNodeTest();
279 if (!(test == null || test instanceof AnyNodeTest)) {
280 return null;
281 }
282
283
284
285 byte underlyingAxis = ((AxisExpression) underlyingStep).getAxis();
286 if (underlyingAxis == AxisInfo.CHILD ||
287 underlyingAxis == AxisInfo.DESCENDANT ||
288 underlyingAxis == AxisInfo.DESCENDANT_OR_SELF) {
289 byte newAxis = underlyingAxis == AxisInfo.DESCENDANT_OR_SELF ? AxisInfo.DESCENDANT_OR_SELF : AxisInfo.DESCENDANT;
290 Expression newStep =
291 new AxisExpression(newAxis,
292 ((AxisExpression) underlyingStep).getNodeTest());
293 ExpressionTool.copyLocationInfo(this, newStep);
294
295 underlyingStep = getStep();
296 // Add any filters to the new expression. We know they aren't
297 // positional, so the order of the filters doesn't technically matter
298 // (XPath section 2.3.4 explicitly allows us to change it.)
299 // However, in the interests of predictable execution, hand-optimization, and
300 // diagnosable error behaviour, we retain the original order.
301 Stack<Expression> filters = new Stack<Expression>();
302 while (underlyingStep instanceof FilterExpression) {
303 filters.add(((FilterExpression) underlyingStep).getFilter());
304 underlyingStep = ((FilterExpression) underlyingStep).getSelectExpression();
305 }
306 while (!filters.isEmpty()) {
307 newStep = new FilterExpression(newStep, filters.pop());
308 ExpressionTool.copyLocationInfo(getStep(), newStep);
309 }
310
311 //System.err.println("Simplified this:");
312 // display(10);
313 //System.err.println("as this:");
314 // new PathExpression(startPath.start, newStep).display(10);
315
316 Expression newPath = ExpressionTool.makePathExpression(startPath.getStart(), newStep);
317 if (!(newPath instanceof SlashExpression)) {
318 return null;
319 }
320 ExpressionTool.copyLocationInfo(this, newPath);
321 return (SlashExpression) newPath;
322 }
323
324 if (underlyingAxis == AxisInfo.ATTRIBUTE) {
325
326 // turn the expression a//@b into a/descendant-or-self::*/@b
327
328 Expression newStep =
329 new AxisExpression(AxisInfo.DESCENDANT_OR_SELF, NodeKindTest.ELEMENT);
330 ExpressionTool.copyLocationInfo(this, newStep);
331 Expression e2 = ExpressionTool.makePathExpression(startPath.getStart(), newStep);
332 Expression e3 = ExpressionTool.makePathExpression(e2, getStep());
333 if (!(e3 instanceof SlashExpression)) {
334 return null;
335 }
336 ExpressionTool.copyLocationInfo(this, e3);
337 return (SlashExpression) e3;
338 }
339
340 return null;
341 }
342
343 /*@NotNull*/
344 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
345 Configuration config = visitor.getConfiguration();
346 TypeHierarchy th = config.getTypeHierarchy();
347 Optimizer opt = visitor.obtainOptimizer();
348
349 getLhs().optimize(visitor, contextItemType);
350 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(getStart().getItemType(), false);
351 cit.setContextSettingExpression(getStart());
352 getRhs().optimize(visitor, cit);
353
354 if (Literal.isEmptySequence(getStart()) || Literal.isEmptySequence(getStep())) {
355 return Literal.makeEmptySequence();
356 }
357
358 if (getStart() instanceof RootExpression && th.isSubType(contextItemType.getItemType(), NodeKindTest.DOCUMENT)) {
359 // remove unnecessary leading "/" - helps streaming
360 return getStep();
361 }
362
363 // Try to simplify descendant-or-self::node()/child::node
364
365 Expression e2 = simplifyDescendantPath(visitor.getStaticContext());
366 if (e2 != null) {
367 return e2.optimize(visitor, contextItemType);
368 }
369
370 // Rewrite a/b[filter] as (a/b)[filter] to improve the chance of indexing
371
372 Expression firstStep = getFirstStep();
373 if (!(firstStep.isCallOn(Doc.class) || firstStep.isCallOn(DocumentFn.class))) {
374 // Avoid the rewrite if the path starts with doc() for streaming reasons
375 Expression lastStep = getLastStep();
376 if (lastStep instanceof FilterExpression && !((FilterExpression) lastStep).isPositional(th)) {
377 Expression leading = getLeadingSteps();
378 Expression p2 = ExpressionTool.makePathExpression(leading, ((FilterExpression) lastStep).getSelectExpression());
379 Expression f2 = new FilterExpression(p2, ((FilterExpression) lastStep).getFilter());
380 ExpressionTool.copyLocationInfo(this, f2);
381 return f2.optimize(visitor, contextItemType);
382 }
383 }
384
385 if (!visitor.isOptimizeForStreaming()) {
386 Expression k = opt.convertPathExpressionToKey(this, visitor);
387 if (k != null) {
388 return k.typeCheck(visitor, contextItemType).optimize(visitor, contextItemType);
389 }
390 }
391
392 // Replace //x/y by descendant::y[parent::x] to eliminate the need for sorting
393 // into document order, and to make the expression streamable
394
395 e2 = tryToMakeSorted(visitor, contextItemType);
396 if (e2 != null) {
397 return e2;
398 }
399
400 // Replace $x/child::abcd by a SimpleStepExpression, to avoid the need for creating
401 // a new dynamic context at run-time.
402
403 if (getStep() instanceof AxisExpression) {
404 if (!Cardinality.allowsMany(getStart().getCardinality())) {
405 SimpleStepExpression sse = new SimpleStepExpression(getStart(), getStep());
406 ExpressionTool.copyLocationInfo(this, sse);
407 sse.setParentExpression(getParentExpression());
408 return sse;
409 } else {
410 contextFree = true;
411 }
412 }
413
414 if (getStart() instanceof RootExpression && getStep().isCallOn(KeyFn.class)) {
415 // This happens after optimizations to convert filter expressions to key() calls
416 SystemFunctionCall keyCall = (SystemFunctionCall)getStep();
417 if (keyCall.getArity() == 3 && keyCall.getArg(2) instanceof ContextItemExpression) {
418 keyCall.setArg(2, new RootExpression());
419 keyCall.setParentExpression(getParentExpression());
420 ExpressionTool.resetStaticProperties(keyCall);
421 return keyCall;
422 }
423 }
424
425 Expression k = promoteFocusIndependentSubexpressions(visitor, contextItemType);
426 if (k != this) {
427 return k;
428 }
429
430 if (visitor.isOptimizeForStreaming()) {
431 // rewrite a/copy-of(.) as copy-of(a)
432 Expression rawStep = ExpressionTool.unfilteredExpression(getStep(), true);
433 if (rawStep instanceof CopyOf && ((CopyOf) rawStep).getSelect() instanceof ContextItemExpression) {
434 ((CopyOf) rawStep).setSelect(getStart());
435 rawStep.resetLocalStaticProperties();
436 getStep().resetLocalStaticProperties();
437 return getStep();
438 }
439 }
440
441 return this;
442 }
443
444 /**
445 * Test whether a path expression is an absolute path - that is, a path whose first step selects a
446 * document node; if not, see if it can be converted to an absolute path. This is possible in cases where
447 * the path expression has the form a/b/c and it is known that the context item is a document node; in this
448 * case it is safe to change the path expression to /a/b/c
449 *
450 * @return the path expression if it is absolute; the converted path expression if it can be made absolute;
451 * or null if neither condition applies.
452 */
453
454 public SlashExpression tryToMakeAbsolute() {
455 Expression first = getFirstStep();
456 if (first.getItemType().getPrimitiveType() == Type.DOCUMENT) {
457 return this;
458 }
459 if (first instanceof AxisExpression) {
460 // This second test allows keys to be built. See XMark q9.
461 ItemType contextItemType = ((AxisExpression) first).getContextItemType();
462 if (contextItemType != null && contextItemType.getPrimitiveType() == Type.DOCUMENT) {
463 RootExpression root = new RootExpression();
464 ExpressionTool.copyLocationInfo(this, root);
465 Expression path = ExpressionTool.makePathExpression(root, this.copy(new RebindingMap()));
466 if (!(path instanceof SlashExpression)) {
467 return null;
468 }
469 ExpressionTool.copyLocationInfo(this, path);
470 return (SlashExpression) path;
471 }
472 }
473 if (first instanceof DocumentSorter && ((DocumentSorter) first).getBaseExpression() instanceof SlashExpression) {
474 // see test case filter-001 in xqts-extra
475 SlashExpression se = (SlashExpression) ((DocumentSorter) first).getBaseExpression();
476 SlashExpression se2 = se.tryToMakeAbsolute();
477 if (se2 != null) {
478 if (se2 == se) {
479 return this;
480 } else {
481 Expression rest = getRemainingSteps();
482 DocumentSorter ds = new DocumentSorter(se2);
483 return new SlashExpression(ds, rest);
484 }
485 }
486 }
487 return null;
488 }
489
490 /**
491 * Return the estimated cost of evaluating an expression. This is a very crude measure based
492 * on the syntactic form of the expression (we have no knowledge of data values). We take
493 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
494 * and we assume that a sequence has length 5. The resulting estimates may be used, for
495 * example, to reorder the predicates in a filter expression so cheaper predicates are
496 * evaluated first.
497 */
498 @Override
499 public int getCost() {
500 int factor = Cardinality.allowsMany(getLhsExpression().getCardinality()) ? 10 : 1;
501 int lh = getLhsExpression().getCost() + 1;
502 int rh = getRhsExpression().getCost();
503 double product = (double) lh + factor * (double) rh;
504 return product > 1e7 ? 10000000 : Math.max(lh + factor * rh, 10000000);
505 }
506
507 public Expression tryToMakeSorted(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
508 // Replace //x/y by descendant::y[parent::x] to eliminate the need for sorting
509 // into document order, and to make the expression streamable
510
511 Configuration config = visitor.getConfiguration();
512 TypeHierarchy th = config.getTypeHierarchy();
513 Optimizer opt = visitor.obtainOptimizer();
514 Expression s1 = ExpressionTool.unfilteredExpression(getStart(), false);
515 if (!(s1 instanceof AxisExpression && ((AxisExpression) s1).getAxis() == AxisInfo.DESCENDANT)) {
516 return null;
517 }
518 Expression s2 = ExpressionTool.unfilteredExpression(getStep(), false);
519 if (!(s2 instanceof AxisExpression && ((AxisExpression) s2).getAxis() == AxisInfo.CHILD)) {
520 return null;
521 }
522
523 // We're in business; construct the new expression
524 Expression x = getStart().copy(new RebindingMap());
525 AxisExpression ax = (AxisExpression) ExpressionTool.unfilteredExpression(x, false);
526 ax.setAxis(AxisInfo.PARENT);
527
528 Expression y = getStep().copy(new RebindingMap());
529 AxisExpression ay = (AxisExpression) ExpressionTool.unfilteredExpression(y, false);
530 ay.setAxis(AxisInfo.DESCENDANT);
531
532 Expression k = new FilterExpression(y, x);
533 // If we're not starting at the root, ensure we go down at least one level
534 if (!th.isSubType(contextItemType.getItemType(), NodeKindTest.DOCUMENT)) {
535 k = new SlashExpression(new AxisExpression(AxisInfo.CHILD, NodeKindTest.ELEMENT), k);
536 ExpressionTool.copyLocationInfo(this, k);
537 opt.trace("Rewrote descendant::X/child::Y as child::*/descendant::Y[parent::X]", k);
538 } else {
539 ExpressionTool.copyLocationInfo(this, k);
540 opt.trace("Rewrote descendant::X/child::Y as descendant::Y[parent::X]", k);
541 }
542 return k;
543 }
544
545
546 /**
547 * If any subexpressions within the step are not dependent on the focus,
548 * and if they are not "creative" expressions (expressions that can create new nodes), then
549 * promote them: this causes them to be evaluated once, outside the path expression
550 *
551 * @param visitor the expression visitor
552 * @param contextItemType the type of the context item for evaluating the start expression
553 * @return the rewritten expression, or the original expression if no rewrite was possible
554 * @throws net.sf.saxon.trans.XPathException
555 * if a static error is detected
556 */
557
558 protected Expression promoteFocusIndependentSubexpressions(
559 ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
560
561 // Optimizer opt = getConfiguration().obtainOptimizer();
562 //
563 // PromotionOffer offer = new PromotionOffer(opt);
564 // offer.action = PromotionOffer.FOCUS_INDEPENDENT;
565 // offer.promoteDocumentDependent = (getStart().getSpecialProperties() & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0;
566 // offer.containingExpression = this;
567 //
568 // setStep(doPromotion(getStep(), offer));
569 // ExpressionTool.resetStaticProperties(this);
570 // if (offer.containingExpression != this) {
571 // offer.containingExpression =
572 // offer.containingExpression.typeCheck(visitor, contextItemType).optimize(visitor, contextItemType);
573 // return offer.containingExpression;
574 // }
575 return this;
576 }
577
578 /**
579 * Replace this expression by a simpler expression that delivers the results without regard
580 * to order.
581 *
582 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
583 * original; set to false if the result can eliminate (or introduce) duplicates.
584 * @param forStreaming set to true if optimizing for streaming
585 */
586 @Override
587 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
588 setStart(getStart().unordered(retainAllNodes, forStreaming));
589 setStep(getStep().unordered(retainAllNodes, forStreaming));
590 return this;
591 }
592
593
594 /**
595 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
596 * by an expression in a source tree.
597 *
598 * @param pathMap the PathMap to which the expression should be added
599 * @param pathMapNodeSet
600 * @return the pathMapNode representing the focus established by this expression, in the case where this
601 * expression is the first operand of a path expression or filter expression
602 */
603
604 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
605 PathMap.PathMapNodeSet target = getStart().addToPathMap(pathMap, pathMapNodeSet);
606 return getStep().addToPathMap(pathMap, target);
607 }
608
609 /**
610 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
611 * This method indicates which of these methods is provided directly. The other methods will always be available
612 * indirectly, using an implementation that relies on one of the other methods.
613 *
614 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
615 * {@link #PROCESS_METHOD}
616 */
617 @Override
618 public int getImplementationMethod() {
619 return ITERATE_METHOD;
620 }
621
622 /**
623 * Determine which aspects of the context the expression depends on. The result is
624 * a bitwise-or'ed value composed from constants such as XPathContext.VARIABLES and
625 * XPathContext.CURRENT_NODE
626 */
627
628 // public int computeDependencies() {
629 // return getStart().getDependencies() |
630 // // not all dependencies in the step matter, because the context node, etc,
631 // // are not those of the outer expression
632 // (getStep().getDependencies() &
633 // (StaticProperty.DEPENDS_ON_XSLT_CONTEXT |
634 // StaticProperty.DEPENDS_ON_LOCAL_VARIABLES |
635 // StaticProperty.DEPENDS_ON_USER_FUNCTIONS));
636 // }
637
638 /**
639 * Copy an expression. This makes a deep copy.
640 *
641 * @return the copy of the original expression
642 * @param rebindings
643 */
644
645 /*@NotNull*/
646 public Expression copy(RebindingMap rebindings) {
647 Expression exp = ExpressionTool.makePathExpression(getStart().copy(rebindings), getStep().copy(rebindings));
648 ExpressionTool.copyLocationInfo(this, exp);
649 return exp;
650 }
651
652 /**
653 * Get the static properties of this expression (other than its type). The result is
654 * bit-signficant. These properties are used for optimizations. In general, if
655 * property bit is set, it is true, but if it is unset, the value is unknown.
656 */
657
658 public int computeSpecialProperties() {
659
660 int startProperties = getStart().getSpecialProperties();
661 int stepProperties = getStep().getSpecialProperties();
662
663 if ((stepProperties & StaticProperty.ALL_NODES_NEWLY_CREATED) != 0) {
664 // Deem copies/snapshots to be in document order
665 return StaticProperty.ORDERED_NODESET | StaticProperty.PEER_NODESET | StaticProperty.NO_NODES_NEWLY_CREATED;
666 }
667
668
669 // System.err.println("====" + toShortString() + "====");
670 // System.err.println("START: " + StaticProperty.display(startProperties));
671 // System.err.println("STEP: " + StaticProperty.display(stepProperties));
672
673 int p = 0;
674 if (!Cardinality.allowsMany(getStart().getCardinality())) {
675 startProperties |= StaticProperty.ORDERED_NODESET |
676 StaticProperty.PEER_NODESET |
677 StaticProperty.SINGLE_DOCUMENT_NODESET;
678 }
679 if (!Cardinality.allowsMany(getStep().getCardinality())) {
680 stepProperties |= StaticProperty.ORDERED_NODESET |
681 StaticProperty.PEER_NODESET |
682 StaticProperty.SINGLE_DOCUMENT_NODESET;
683 }
684
685 if ((startProperties & stepProperties & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0) {
686 p |= StaticProperty.CONTEXT_DOCUMENT_NODESET;
687 }
688 if (((startProperties & StaticProperty.SINGLE_DOCUMENT_NODESET) != 0) &&
689 ((stepProperties & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0)) {
690 p |= StaticProperty.SINGLE_DOCUMENT_NODESET;
691 }
692 if ((startProperties & stepProperties & StaticProperty.PEER_NODESET) != 0) {
693 p |= StaticProperty.PEER_NODESET;
694 }
695 if ((startProperties & stepProperties & StaticProperty.SUBTREE_NODESET) != 0) {
696 p |= StaticProperty.SUBTREE_NODESET;
697 }
698
699 if (testNaturallySorted(startProperties, stepProperties)) {
700 p |= StaticProperty.ORDERED_NODESET;
701 }
702
703 if (testNaturallyReverseSorted()) {
704 p |= StaticProperty.REVERSE_DOCUMENT_ORDER;
705 }
706
707 if ((startProperties & stepProperties & StaticProperty.NO_NODES_NEWLY_CREATED) != 0) {
708 p |= StaticProperty.NO_NODES_NEWLY_CREATED;
709 }
710
711 return p;
712 }
713
714 /**
715 * Determine if we can guarantee that the nodes are delivered in document order.
716 * This is true if the start nodes are sorted peer nodes
717 * and the step is based on an Axis within the subtree rooted at each node.
718 * It is also true if the start is a singleton node and the axis is sorted.
719 *
720 * @param startProperties the properties of the left-hand expression
721 * @param stepProperties the properties of the right-hand expression
722 * @return true if the natural nested-loop evaluation strategy for the expression
723 * is known to deliver results with no duplicates and in document order, that is,
724 * if no additional sort is required
725 */
726
727 private boolean testNaturallySorted(int startProperties, int stepProperties) {
728
729 // System.err.println("**** Testing pathExpression.isNaturallySorted()");
730 // display(20);
731 // System.err.println("Start is ordered node-set? " + start.isOrderedNodeSet());
732 // System.err.println("Start is naturally sorted? " + start.isNaturallySorted());
733 // System.err.println("Start is singleton? " + start.isSingleton());
734
735 if ((stepProperties & StaticProperty.ORDERED_NODESET) == 0) {
736 return false;
737 }
738 if (Cardinality.allowsMany(getStart().getCardinality())) {
739 if ((startProperties & StaticProperty.ORDERED_NODESET) == 0) {
740 return false;
741 }
742 } else {
743 //if ((stepProperties & StaticProperty.ORDERED_NODESET) != 0) {
744 return true;
745 //}
746 }
747
748 // We know now that both the start and the step are sorted. But this does
749 // not necessarily mean that the combination is sorted.
750
751 // The result is sorted if the start is sorted and the step selects attributes
752 // or namespaces
753
754 if ((stepProperties & StaticProperty.ATTRIBUTE_NS_NODESET) != 0) {
755 return true;
756 }
757
758 // The result is sorted if the step is creative (e.g. a call to copy-of())
759
760 if ((stepProperties & StaticProperty.ALL_NODES_NEWLY_CREATED) != 0) {
761 return true;
762 }
763
764 // The result is sorted if the start selects "peer nodes" (that is, a node-set in which
765 // no node is an ancestor of another) and the step selects within the subtree rooted
766 // at the context node
767
768 return ((startProperties & StaticProperty.PEER_NODESET) != 0) &&
769 ((stepProperties & StaticProperty.SUBTREE_NODESET) != 0);
770
771 }
772
773 /**
774 * Determine if the path expression naturally returns nodes in reverse document order
775 *
776 * @return true if the natural nested-loop evaluation strategy returns nodes in reverse
777 * document order
778 */
779
780 private boolean testNaturallyReverseSorted() {
781
782 // Some examples of path expressions that are naturally reverse sorted:
783 // ancestor::*/@x
784 // ../preceding-sibling::x
785 // $x[1]/preceding-sibling::node()
786
787 // This information is used to do a simple reversal of the nodes
788 // instead of a full sort, which is significantly cheaper, especially
789 // when using tree models (such as DOM and JDOM) in which comparing
790 // nodes in document order is an expensive operation.
791
792
793 if (!Cardinality.allowsMany(getStart().getCardinality()) &&
794 (getStep() instanceof AxisExpression)) {
795 return !AxisInfo.isForwards[((AxisExpression) getStep()).getAxis()];
796 }
797
798 return !Cardinality.allowsMany(getStep().getCardinality()) &&
799 (getStart() instanceof AxisExpression) &&
800 !AxisInfo.isForwards[((AxisExpression) getStart()).getAxis()];
801
802 }
803
804
805 /**
806 * Determine the static cardinality of the expression
807 */
808
809 public int computeCardinality() {
810 int c1 = getStart().getCardinality();
811 int c2 = getStep().getCardinality();
812 return Cardinality.multiply(c1, c2);
813 }
814
815 /**
816 * Convert this expression to an equivalent XSLT pattern
817 *
818 * @param config the Saxon configuration
819 * @return the equivalent pattern
820 * @throws net.sf.saxon.trans.XPathException
821 * if conversion is not possible
822 */
823 @Override
824 public Pattern toPattern(Configuration config) throws XPathException {
825 Expression head = getLeadingSteps();
826 Expression tail = getLastStep();
827 if (head instanceof ItemChecker) {
828 // No need to typecheck the context item
829 ItemChecker checker = (ItemChecker) head;
830 if (checker.getBaseExpression() instanceof ContextItemExpression) {
831 return tail.toPattern(config);
832 }
833 }
834
835 Pattern tailPattern = tail.toPattern(config);
836 if (tailPattern instanceof NodeTestPattern) {
837 if (tailPattern.getItemType() instanceof ErrorType) {
838 return tailPattern;
839 }
840 } else if (tailPattern instanceof GeneralNodePattern) {
841 return new GeneralNodePattern(this, (NodeTest)tailPattern.getItemType());
842 }
843
844 byte axis = AxisInfo.PARENT;
845 Pattern headPattern = null;
846 if (head instanceof SlashExpression) {
847 SlashExpression start = (SlashExpression) head;
848 if (start.getActionExpression() instanceof AxisExpression) {
849 AxisExpression mid = (AxisExpression) start.getActionExpression();
850 if (mid.getAxis() == AxisInfo.DESCENDANT_OR_SELF &&
851 (mid.getNodeTest() == null || mid.getNodeTest() instanceof AnyNodeTest)) {
852 axis = AxisInfo.ANCESTOR;
853 headPattern = start.getSelectExpression().toPattern(config);
854 }
855 }
856 }
857 if (headPattern == null) {
858 axis = PatternMaker.getAxisForPathStep(tail);
859 headPattern = head.toPattern(config);
860 }
861 return new AncestorQualifiedPattern(tailPattern, headPattern, axis);
862 }
863
864 /**
865 * A SlashExpression is context free if the right-hand argument is an AxisExpression.
866 * This allows evaluation without creating a new XPathContext or FocusTrackingIterator;
867 * the expression can be evaluated as a simple flat-mapping function from nodes to nodes.
868 * @return true if the expression has been assessed as context-free, that is, if the
869 * right-hand operand is an AxisExpression
870 */
871
872 public boolean isContextFree() {
873 return contextFree;
874 }
875
876 /**
877 * Mark this expression as being context free (or not). This is done during reloading from a SEF file.
878 * @param free true if the expression has been assessed as context-free, that is, if the
879 * right-hand operand is an AxisExpression
880 */
881
882 public void setContextFree(boolean free) {
883 this.contextFree = free;
884 }
885
886 /**
887 * Is this expression the same as another expression?
888 */
889
890 public boolean equals(Object other) {
891 if (!(other instanceof SlashExpression)) {
892 return false;
893 }
894 SlashExpression p = (SlashExpression) other;
895 return getStart().isEqual(p.getStart()) && getStep().isEqual(p.getStep());
896 }
897
898 /**
899 * get HashCode for comparing two expressions
900 */
901
902 public int computeHashCode() {
903 return "SlashExpression".hashCode() + getStart().hashCode() + getStep().hashCode();
904 }
905
906 /**
907 * Iterate the path-expression in a given context
908 *
909 * @param context the evaluation context
910 */
911
912 /*@NotNull*/
913 public SequenceIterator<?> iterate(final XPathContext context) throws XPathException {
914
915 // This class delivers the result of the path expression in unsorted order,
916 // without removal of duplicates. If sorting and deduplication are needed,
917 // this is achieved by wrapping the path expression in a DocumentSorter
918
919 if (contextFree) {
920 return new MappingIterator<>(
921 getStart().iterate(context),
922 (MappingFunction<Item<?>, NodeInfo>) item ->
923 ((AxisExpression) getRhsExpression()).iterate((NodeInfo)item));
924 }
925
926 XPathContext context2 = context.newMinorContext();
927 context2.trackFocus(getStart().iterate(context));
928 return new ContextMappingIterator<Item<?>>(c1 -> getStep().iterate(c1), context2);
929 }
930
931 // /**
932 // * Mapping function, from a node returned by the start iteration, to a sequence
933 // * returned by the child.
934 // */
935 //
936 // public SequenceIterator<?> map(XPathContext context) throws XPathException {
937 // return getStep().iterate(context);
938 // }
939
940 /**
941 * Diagnostic print of expression structure. The abstract expression tree
942 * is written to the supplied output destination.
943 */
944
945 public void export(ExpressionPresenter destination) throws XPathException {
946 destination.startElement("slash", this);
947 if (this instanceof SimpleStepExpression) {
948 destination.emitAttribute("simple", "1");
949 } else if (isContextFree()) {
950 destination.emitAttribute("simple", "2");
951 }
952 getStart().export(destination);
953 getStep().export(destination);
954 destination.endElement();
955 }
956
957 /**
958 * The toString() method for an expression attempts to give a representation of the expression
959 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
960 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
961 *
962 * @return a representation of the expression as a string
963 */
964
965 public String toString() {
966 return ExpressionTool.parenthesize(getStart()) + "/" + ExpressionTool.parenthesize(getStep());
967 }
968
969 @Override
970 public String toShortString() {
971 return ExpressionTool.parenthesizeShort(getStart()) + "/" + ExpressionTool.parenthesizeShort(getStep());
972 }
973
974 /**
975 * Get the first step in this expression. A path expression A/B/C is represented as (A/B)/C, but
976 * the first step is A
977 *
978 * @return the first step in the expression, after expanding any nested path expressions
979 */
980
981 public Expression getFirstStep() {
982 if (getStart() instanceof SlashExpression) {
983 return ((SlashExpression) getStart()).getFirstStep();
984 } else {
985 return getStart();
986 }
987 }
988
989
990 /**
991 * Get all steps after the first.
992 * This is complicated by the fact that A/B/C is represented as ((A/B)/C; we are required
993 * to return B/C
994 *
995 * @return a path expression containing all steps in this path expression other than the first,
996 * after expanding any nested path expressions
997 */
998
999 public Expression getRemainingSteps() {
1000 if (getStart() instanceof SlashExpression) {
1001 List<Expression> list = new ArrayList<Expression>(8);
1002 gatherSteps(list);
1003 Expression rem = rebuildSteps(list.subList(1, list.size()));
1004 ExpressionTool.copyLocationInfo(this, rem);
1005 return rem;
1006 } else {
1007 return getStep();
1008 }
1009 }
1010
1011 /**
1012 * Flatten the path expression into a flat list of steps
1013 * @param list a list of expressions making up this path expression
1014 */
1015
1016 private void gatherSteps(List<Expression> list) {
1017 if (getStart() instanceof SlashExpression) {
1018 ((SlashExpression)getStart()).gatherSteps(list);
1019 } else {
1020 list.add(getStart());
1021 }
1022 if (getStep() instanceof SlashExpression) {
1023 ((SlashExpression) getStep()).gatherSteps(list);
1024 } else {
1025 list.add(getStep());
1026 }
1027 }
1028
1029 /**
1030 * Build a tree from a flat list of steps
1031 * @param list the list of steps
1032 * @return an Expression, generally a right-heavy binary tree
1033 */
1034
1035 private Expression rebuildSteps(List<Expression> list) {
1036 if (list.size() == 1) {
1037 return list.get(0).copy(new RebindingMap());
1038 } else {
1039 return new SlashExpression(list.get(0).copy(new RebindingMap()), rebuildSteps(list.subList(1, list.size())));
1040 }
1041 }
1042
1043 /**
1044 * Get the last step of the path expression
1045 *
1046 * @return the last step in the expression, after expanding any nested path expressions
1047 */
1048
1049 public Expression getLastStep() {
1050 if (getStep() instanceof SlashExpression) {
1051 return ((SlashExpression) getStep()).getLastStep();
1052 } else {
1053 return getStep();
1054 }
1055 }
1056
1057 /**
1058 * Get a path expression consisting of all steps except the last
1059 *
1060 * @return a path expression containing all steps in this path expression other than the last,
1061 * after expanding any nested path expressions
1062 */
1063
1064 public Expression getLeadingSteps() {
1065 if (getStep() instanceof SlashExpression) {
1066 List<Expression> list = new ArrayList<Expression>(8);
1067 gatherSteps(list);
1068 Expression rem = rebuildSteps(list.subList(0, list.size()-1));
1069 ExpressionTool.copyLocationInfo(this, rem);
1070 return rem;
1071 } else {
1072 return getStart();
1073 }
1074 }
1075
1076 /**
1077 * Test whether a path expression is an absolute path - that is, a path whose first step selects a
1078 * document node
1079 *
1080 * @return true if the first step in this path expression selects a document node
1081 */
1082
1083 public boolean isAbsolute() {
1084 return getFirstStep().getItemType().getPrimitiveType() == Type.DOCUMENT;
1085 }
1086
1087
1088 /**
1089 * Get the (partial) name of a class that supports streaming of this kind of expression
1090 *
1091 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
1092 * or null if there is no such class
1093 */
1094 @Override
1095 public String getStreamerName() {
1096 return "ForEach"; // sic
1097 }
1098 }
1099