Debian Codegraph @

net/sf/saxon/expr/VennExpression.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.Block;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.expr.sort.DocumentSorter;
14 import net.sf.saxon.expr.sort.GlobalOrderComparer;
15 import net.sf.saxon.functions.CurrentGroupCall;
16 import net.sf.saxon.functions.SystemFunction;
17 import net.sf.saxon.om.AxisInfo;
18 import net.sf.saxon.om.NodeInfo;
19 import net.sf.saxon.om.SequenceIterator;
20 import net.sf.saxon.pattern.*;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.ItemType;
23 import net.sf.saxon.type.Type;
24 import net.sf.saxon.type.TypeHierarchy;
25 import net.sf.saxon.type.UType;
26 import net.sf.saxon.value.Cardinality;
27 import net.sf.saxon.value.SequenceType;
28
29 import java.util.HashSet;
30 import java.util.Set;
31
32
33 /**
34 * An expression representing a nodeset that is a union, difference, or
35 * intersection of two other NodeSets
36 */
37
38 public class VennExpression extends BinaryExpression {
39
40 /**
41 * Constructor
42 *
43 * @param p1 the left-hand operand
44 * @param op the operator (union, intersection, or difference)
45 * @param p2 the right-hand operand
46 */
47
48 public VennExpression(final Expression p1, final int op, final Expression p2) {
49 super(p1, op, p2);
50 }
51
52 /**
53 * Simplify an expression. This performs any static optimization (by rewriting the expression
54 * as a different expression). The default implementation simplifies its operands.
55 *
56 * @return the simplified expression (or the original if unchanged, or if modified in-situ)
57 * @throws net.sf.saxon.trans.XPathException if an error is discovered during expression
58 * rewriting
59 */
60 @Override
61 public Expression simplify() throws XPathException {
62 // Force both operands to be sorted in document order. If this turns out to be unnecessary, it will
63 // get optimized away
64 if (!(getLhsExpression() instanceof DocumentSorter)) {
65 setLhsExpression(new DocumentSorter(getLhsExpression()));
66 }
67 if (!(getRhsExpression() instanceof DocumentSorter)) {
68 setRhsExpression(new DocumentSorter(getRhsExpression()));
69 }
70 super.simplify();
71 return this;
72 }
73
74 /**
75 * Get a name identifying the kind of expression, in terms meaningful to a user.
76 *
77 * @return a name identifying the kind of expression, in terms meaningful to a user.
78 * The name will always be in the form of a lexical XML QName, and should match the name used
79 * in explain() output displaying the expression.
80 */
81
82 public String getExpressionName() {
83 switch (operator) {
84 case Token.UNION:
85 return "union";
86 case Token.INTERSECT:
87 return "intersect";
88 case Token.EXCEPT:
89 return "except";
90 default:
91 return "unknown";
92 }
93 }
94
95 /**
96 * Determine the data type of the items returned by this expression
97 *
98 * @return the data type
99 */
100
101 /*@NotNull*/
102 public final ItemType getItemType() {
103 final ItemType t1 = getLhsExpression().getItemType();
104 if (operator == Token.UNION) {
105 ItemType t2 = getRhsExpression().getItemType();
106 TypeHierarchy th = getConfiguration().getTypeHierarchy();
107 return Type.getCommonSuperType(t1, t2, th);
108 } else {
109 return t1;
110 }
111 }
112
113 /**
114 * Get the static type of the expression as a UType, following precisely the type
115 * inference rules defined in the XSLT 3.0 specification.
116 *
117 * @return the static item type of the expression according to the XSLT 3.0 defined rules
118 * @param contextItemType the static type of the context item
119 */
120 @Override
121 public UType getStaticUType(UType contextItemType) {
122 switch (operator) {
123 case Token.UNION:
124 return getLhsExpression().getStaticUType(contextItemType).union(getRhsExpression().getStaticUType(contextItemType));
125 case Token.INTERSECT:
126 return getLhsExpression().getStaticUType(contextItemType).intersection(getRhsExpression().getStaticUType(contextItemType));
127 case Token.EXCEPT:
128 default:
129 return getLhsExpression().getStaticUType(contextItemType);
130 }
131 }
132
133
134 /**
135 * Determine the static cardinality of the expression
136 */
137
138 public final int computeCardinality() {
139 final int c1 = getLhsExpression().getCardinality();
140 final int c2 = getRhsExpression().getCardinality();
141 switch (operator) {
142 case Token.UNION:
143 if (Literal.isEmptySequence(getLhsExpression())) {
144 return c2;
145 }
146 if (Literal.isEmptySequence(getRhsExpression())) {
147 return c1;
148 }
149 return c1 | c2 | StaticProperty.ALLOWS_ONE | StaticProperty.ALLOWS_MANY;
150 // allows ZERO only if one operand allows ZERO
151 case Token.INTERSECT:
152 if (Literal.isEmptySequence(getLhsExpression())) {
153 return StaticProperty.EMPTY;
154 }
155 if (Literal.isEmptySequence(getRhsExpression())) {
156 return StaticProperty.EMPTY;
157 }
158 return (c1 & c2) | StaticProperty.ALLOWS_ZERO | StaticProperty.ALLOWS_ONE;
159 // allows MANY only if both operands allow MANY
160 case Token.EXCEPT:
161 if (Literal.isEmptySequence(getLhsExpression())) {
162 return StaticProperty.EMPTY;
163 }
164 if (Literal.isEmptySequence(getRhsExpression())) {
165 return c1;
166 }
167 return c1 | StaticProperty.ALLOWS_ZERO | StaticProperty.ALLOWS_ONE;
168 // allows MANY only if first operand allows MANY
169 }
170 return StaticProperty.ALLOWS_ZERO_OR_MORE;
171 }
172
173 /**
174 * Get the static properties of this expression (other than its type). The result is
175 * bit-signficant. These properties are used for optimizations. In general, if
176 * property bit is set, it is true, but if it is unset, the value is unknown.
177 */
178
179 public int computeSpecialProperties() {
180 final int prop0 = getLhsExpression().getSpecialProperties();
181 final int prop1 = getRhsExpression().getSpecialProperties();
182 int props = StaticProperty.ORDERED_NODESET;
183 if (testContextDocumentNodeSet(prop0, prop1)) {
184 props |= StaticProperty.CONTEXT_DOCUMENT_NODESET;
185 }
186 if (testSubTree(prop0, prop1)) {
187 props |= StaticProperty.SUBTREE_NODESET;
188 }
189 if (createsNoNewNodes(prop0, prop1)) {
190 props |= StaticProperty.NO_NODES_NEWLY_CREATED;
191 }
192 return props;
193 }
194
195 /**
196 * Determine whether all the nodes in the node-set are guaranteed to
197 * come from the same document as the context node. Used for optimization.
198 *
199 * @param prop0 contains the Context Document Nodeset property of the first operand
200 * @param prop1 contains the Context Document Nodeset property of the second operand
201 * @return true if all the nodes come from the context document
202 */
203
204 private boolean testContextDocumentNodeSet(final int prop0, final int prop1) {
205 switch (operator) {
206 case Token.UNION:
207 return (prop0 & prop1 & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0;
208 case Token.INTERSECT:
209 return ((prop0 | prop1) & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0;
210 case Token.EXCEPT:
211 return (prop0 & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0;
212 }
213 return false;
214 }
215
216 /**
217 * Gather the component operands of a union or intersect expression
218 *
219 * @param operator union or intersect
220 * @param set the set into which the components are to be gathered. If the operator
221 * is union, this follows the tree gathering all operands of union expressions. Ditto,
222 * mutatis mutandis, for intersect expressions.
223 */
224
225 public void gatherComponents(int operator, Set<Expression> set) {
226 if (getLhsExpression() instanceof VennExpression && ((VennExpression) getLhsExpression()).operator == operator) {
227 ((VennExpression) getLhsExpression()).gatherComponents(operator, set);
228 } else {
229 set.add(getLhsExpression());
230 }
231 if (getRhsExpression() instanceof VennExpression && ((VennExpression) getRhsExpression()).operator == operator) {
232 ((VennExpression) getRhsExpression()).gatherComponents(operator, set);
233 } else {
234 set.add(getRhsExpression());
235 }
236 }
237
238 /**
239 * Determine whether all the nodes in the node-set are guaranteed to
240 * come from a subtree rooted at the context node. Used for optimization.
241 *
242 * @param prop0 contains the SubTree property of the first operand
243 * @param prop1 contains the SubTree property of the second operand
244 * @return true if all the nodes come from the tree rooted at the context node
245 */
246
247 private boolean testSubTree(final int prop0, final int prop1) {
248 switch (operator) {
249 case Token.UNION:
250 return (prop0 & prop1 & StaticProperty.SUBTREE_NODESET) != 0;
251 case Token.INTERSECT:
252 return ((prop0 | prop1) & StaticProperty.SUBTREE_NODESET) != 0;
253 case Token.EXCEPT:
254 return (prop0 & StaticProperty.SUBTREE_NODESET) != 0;
255 }
256 return false;
257 }
258
259 /**
260 * Determine whether the expression can create new nodes
261 *
262 * @param prop0 contains the noncreative property of the first operand
263 * @param prop1 contains the noncreative property of the second operand
264 * @return true if the expression can create new nodes
265 */
266
267 private boolean createsNoNewNodes(final int prop0, final int prop1) {
268 return (prop0 & StaticProperty.NO_NODES_NEWLY_CREATED) != 0 &&
269 (prop1 & StaticProperty.NO_NODES_NEWLY_CREATED) != 0;
270 }
271
272 /**
273 * Type-check the expression
274 */
275
276 /*@NotNull*/
277 public Expression typeCheck(ExpressionVisitor visitor, final ContextItemStaticInfo contextInfo) throws XPathException {
278
279 Configuration config = visitor.getConfiguration();
280 TypeChecker tc = config.getTypeChecker(false);
281 getLhs().typeCheck(visitor, contextInfo);
282 getRhs().typeCheck(visitor, contextInfo);
283
284 if (!(getLhsExpression() instanceof Pattern)) {
285 final RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 0);
286 setLhsExpression(tc.staticTypeCheck(getLhsExpression(), SequenceType.NODE_SEQUENCE, role0, visitor));
287 }
288
289 if (!(getRhsExpression() instanceof Pattern)) {
290 final RoleDiagnostic role1 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 1);
291 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), SequenceType.NODE_SEQUENCE, role1, visitor));
292 }
293
294 // For the intersect and except operators, if the types are disjoint then we can simplify
295 if (operator != Token.UNION) {
296 TypeHierarchy th = config.getTypeHierarchy();
297 ItemType t0 = getLhsExpression().getItemType();
298 ItemType t1 = getRhsExpression().getItemType();
299 if (th.relationship(t0, t1) == TypeHierarchy.DISJOINT) {
300 if (operator == Token.INTERSECT) {
301 return Literal.makeEmptySequence();
302 } else {
303 if (getLhsExpression().hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
304 return getLhsExpression();
305 } else {
306 return new DocumentSorter(getLhsExpression());
307 }
308 }
309 }
310 }
311
312 return this;
313 }
314
315
316 /**
317 * Perform optimisation of an expression and its subexpressions.
318 * <p>This method is called after all references to functions and variables have been resolved
319 * to the declaration of the function or variable, and after all type checking has been done.</p>
320 *
321 * @param visitor an expression visitor
322 * @param contextItemType the static type of "." at the point where this expression is invoked.
323 * The parameter is set to null if it is known statically that the context item will be undefined.
324 * If the type of the context item is not known statically, the argument is set to
325 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
326 * @return the original expression, rewritten if appropriate to optimize execution
327 * @throws net.sf.saxon.trans.XPathException
328 * if an error is discovered during this phase
329 * (typically a type error)
330 */
331
332 /*@NotNull*/
333 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
334 Expression e = super.optimize(visitor, contextItemType);
335 if (e != this) {
336 return e;
337 }
338
339 final Configuration config = visitor.getConfiguration();
340 final TypeHierarchy th = config.getTypeHierarchy();
341
342 // If either operand is an empty sequence, simplify the expression. This can happen
343 // after reduction with constructs of the form //a[condition] | //b[not(condition)],
344 // common in XPath 1.0 because there were no conditional expressions.
345
346 Expression lhs = getLhsExpression();
347 Expression rhs = getRhsExpression();
348 switch (operator) {
349 case Token.UNION:
350 if (Literal.isEmptySequence(lhs) &&
351 (rhs.getSpecialProperties() & StaticProperty.ORDERED_NODESET) != 0) {
352 return rhs;
353 }
354 if (Literal.isEmptySequence(rhs) &&
355 (lhs.getSpecialProperties() & StaticProperty.ORDERED_NODESET) != 0) {
356 return lhs;
357 }
358 if (lhs instanceof CurrentGroupCall && rhs instanceof ContextItemExpression) {
359 return lhs;
360 }
361 break;
362 case Token.INTERSECT:
363 if (Literal.isEmptySequence(lhs)) {
364 return lhs;
365 }
366 if (Literal.isEmptySequence(rhs)) {
367 return rhs;
368 }
369 if (lhs instanceof CurrentGroupCall && rhs instanceof ContextItemExpression) {
370 return rhs;
371 }
372 break;
373 case Token.EXCEPT:
374 if (Literal.isEmptySequence(lhs)) {
375 return lhs;
376 }
377 if (Literal.isEmptySequence(rhs) &&
378 (lhs.getSpecialProperties() & StaticProperty.ORDERED_NODESET) != 0) {
379 return lhs;
380 }
381 if (lhs instanceof CurrentGroupCall && rhs instanceof ContextItemExpression) {
382 // Test case si-group-055.
383 // The streaming code has problems with (current-group() except .) so we
384 // optimize it away. This is a bit of a hack, because the difficulty may
385 // affect other expressions as well. The problem arises because part of the
386 // pattern needs to be evaluated with each node in the group as anchor node,
387 // and part with only the first node in the group as anchor node.
388 return new TailExpression(lhs, 2);
389 }
390 break;
391 }
392
393 // If both are axis expressions on the same axis, merge them
394 // ie. rewrite (axis::test1 | axis::test2) as axis::(test1 | test2)
395
396 if (lhs instanceof AxisExpression && rhs instanceof AxisExpression) {
397 final AxisExpression a1 = (AxisExpression) lhs;
398 final AxisExpression a2 = (AxisExpression) rhs;
399 if (a1.getAxis() == a2.getAxis()) {
400 if (a1.getNodeTest().equals(a2.getNodeTest())) {
401 return operator == Token.EXCEPT ? Literal.makeEmptySequence() : a1;
402 } else {
403 AxisExpression ax = new AxisExpression(a1.getAxis(),
404 new CombinedNodeTest(a1.getNodeTest(),
405 operator,
406 a2.getNodeTest()));
407 ExpressionTool.copyLocationInfo(this, ax);
408 return ax;
409 }
410 }
411 }
412
413 // If both are path expressions starting the same way, merge them
414 // i.e. rewrite (/X | /Y) as /(X|Y). This applies recursively, so that
415 // /A/B/C | /A/B/D becomes /A/B/child::(C|D)
416
417 // This optimization was previously done for all three operators. However, it's not safe for "except":
418 // A//B except A//C//B cannot be rewritten as A/descendant-or-self::node()/(B except C//B). As a quick
419 // fix, the optimization has been retained for "union" but dropped for "intersect" and "except". Need to
420 // do a more rigorous analysis of the conditions under which it is safe.
421
422 // TODO: generalize this code to handle all distributive operators
423
424 if (lhs instanceof SlashExpression && rhs instanceof SlashExpression && operator == Token.UNION) {
425 final SlashExpression path1 = (SlashExpression) lhs;
426 final SlashExpression path2 = (SlashExpression) rhs;
427
428 if (path1.getFirstStep().isEqual(path2.getFirstStep())) {
429 final VennExpression venn = new VennExpression(
430 path1.getRemainingSteps(),
431 operator,
432 path2.getRemainingSteps());
433 ExpressionTool.copyLocationInfo(this, venn);
434 final Expression path = ExpressionTool.makePathExpression(path1.getFirstStep(), venn);
435 ExpressionTool.copyLocationInfo(this, path);
436 return path.optimize(visitor, contextItemType);
437 }
438 }
439
440 // Try merging two non-positional filter expressions:
441 // A[exp0] | A[exp1] becomes A[exp0 or exp1]
442
443 if (lhs instanceof FilterExpression && rhs instanceof FilterExpression) {
444 final FilterExpression exp0 = (FilterExpression) lhs;
445 final FilterExpression exp1 = (FilterExpression) rhs;
446
447 if (!exp0.isPositional(th) &&
448 !exp1.isPositional(th) &&
449 exp0.getSelectExpression().isEqual(exp1.getSelectExpression())) {
450 final Expression filter;
451 switch (operator) {
452 case Token.UNION:
453 filter = new OrExpression(exp0.getFilter(),
454 exp1.getFilter());
455 break;
456 case Token.INTERSECT:
457 filter = new AndExpression(exp0.getFilter(),
458 exp1.getFilter());
459 break;
460 case Token.EXCEPT:
461 Expression negate2 = SystemFunction.makeCall("not", getRetainedStaticContext(), exp1.getFilter());
462 filter = new AndExpression(exp0.getFilter(), negate2);
463 break;
464 default:
465 throw new AssertionError("Unknown operator " + operator);
466 }
467 ExpressionTool.copyLocationInfo(this, filter);
468 FilterExpression f = new FilterExpression(exp0.getSelectExpression(), filter);
469 ExpressionTool.copyLocationInfo(this, f);
470 return f.simplify().typeCheck(visitor, contextItemType).optimize(visitor, contextItemType);
471 }
472 }
473
474 // Convert @*|node() into @*,node() to eliminate the sorted merge operation
475 // Avoid doing this when streaming because xsl:value-of select="@*,node()" is not currently streamable
476 if (!visitor.isOptimizeForStreaming() && operator == Token.UNION &&
477 lhs instanceof AxisExpression && rhs instanceof AxisExpression) {
478 AxisExpression a0 = (AxisExpression) lhs;
479 AxisExpression a1 = (AxisExpression) rhs;
480 if (a0.getAxis() == AxisInfo.ATTRIBUTE && a1.getAxis() == AxisInfo.CHILD) {
481 return new Block(new Expression[]{lhs, rhs});
482 } else if (a1.getAxis() == AxisInfo.ATTRIBUTE && a0.getAxis() == AxisInfo.CHILD) {
483 return new Block(new Expression[]{rhs, lhs});
484 }
485 }
486
487 // Convert (A intersect B) to use a serial search where one operand is a singleton
488 if (operator == Token.INTERSECT && !Cardinality.allowsMany(lhs.getCardinality())) {
489 return new SingletonIntersectExpression(lhs, operator, rhs.unordered(false, false));
490 }
491 if (operator == Token.INTERSECT && !Cardinality.allowsMany(rhs.getCardinality())) {
492 return new SingletonIntersectExpression(rhs, operator, lhs.unordered(false, false));
493 }
494
495 // If the types of the operands are disjoint, simplify "intersect" and "except"
496 if (operandsAreDisjoint(th)) {
497 if (operator == Token.INTERSECT) {
498 return Literal.makeEmptySequence();
499 } else if (operator == Token.EXCEPT) {
500 if ((lhs.getSpecialProperties() & StaticProperty.ORDERED_NODESET) != 0) {
501 return lhs;
502 } else {
503 return new DocumentSorter(lhs);
504 }
505 }
506 }
507 return this;
508 }
509
510 private boolean operandsAreDisjoint(TypeHierarchy th) {
511 return th.relationship(getLhsExpression().getItemType(), getRhsExpression().getItemType()) == TypeHierarchy.DISJOINT;
512 }
513
514 /**
515 * Replace this expression by an expression that returns the same result but without
516 * regard to order
517 *
518 * @param retainAllNodes true if all nodes in the result must be retained; false
519 * if duplicates can be eliminated
520 * @param forStreaming set to true if optimizing for streaming
521 */
522 @Override
523 public Expression unordered(boolean retainAllNodes, boolean forStreaming) {
524 if (operator == Token.UNION && !forStreaming &&
525 operandsAreDisjoint(getConfiguration().getTypeHierarchy())) {
526 // replace union operator by comma operator to avoid cost of sorting into document order. See XMark q7
527 Block block = new Block(new Expression[]{getLhsExpression(), getRhsExpression()});
528 ExpressionTool.copyLocationInfo(this, block);
529 return block;
530 }
531 return this;
532 }
533
534
535 /**
536 * Copy an expression. This makes a deep copy.
537 *
538 * @return the copy of the original expression
539 * @param rebindings variables that need to be rebound
540 */
541
542 /*@NotNull*/
543 public Expression copy(RebindingMap rebindings) {
544 VennExpression exp = new VennExpression(getLhsExpression().copy(rebindings), operator, getRhsExpression().copy(rebindings));
545 ExpressionTool.copyLocationInfo(this, exp);
546 return exp;
547 }
548
549 /**
550 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
551 * This method indicates which of these methods is provided directly. The other methods will always be available
552 * indirectly, using an implementation that relies on one of the other methods.
553 *
554 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
555 * {@link #PROCESS_METHOD}
556 */
557 @Override
558 public int getImplementationMethod() {
559 return ITERATE_METHOD;
560 }
561
562 /**
563 * Get the operand role (applies to both operands)
564 * @return the operand role
565 * @param arg which argument: 0 for the lhs, 1 for the rhs
566 */
567
568 protected OperandRole getOperandRole(int arg) {
569 return OperandRole.SAME_FOCUS_ACTION;
570 }
571
572
573 /**
574 * Is this expression the same as another expression?
575 */
576
577 public boolean equals(Object other) {
578 // NOTE: it's possible that the method in the superclass is already adequate for this
579 if (other instanceof VennExpression) {
580 VennExpression b = (VennExpression) other;
581 if (operator != b.operator) {
582 return false;
583 }
584 if (getLhsExpression().isEqual(b.getLhsExpression()) && getRhsExpression().isEqual(b.getRhsExpression())) {
585 return true;
586 }
587 if (operator == Token.UNION || operator == Token.INTERSECT) {
588 // These are commutative and associative, so for example (A|B)|C equals B|(A|C)
589 Set<Expression> s0 = new HashSet<>(10);
590 gatherComponents(operator, s0);
591 Set<Expression> s1 = new HashSet<>(10);
592 ((VennExpression) other).gatherComponents(operator, s1);
593 return s0.equals(s1);
594 }
595 }
596 return false;
597 }
598
599 public int computeHashCode() {
600 return getLhsExpression().hashCode() ^ getRhsExpression().hashCode();
601 }
602
603 /**
604 * Convert this expression to an equivalent XSLT pattern
605 *
606 * @param config the Saxon configuration
607 * @return the equivalent pattern
608 * @throws net.sf.saxon.trans.XPathException
609 * if conversion is not possible
610 */
611 @Override
612 public Pattern toPattern(Configuration config) throws XPathException {
613 if (isPredicatePattern(getLhsExpression()) || isPredicatePattern(getRhsExpression())) {
614 throw new XPathException(
615 "Cannot use a predicate pattern as an operand of a union, intersect, or except operator",
616 "XTSE0340");
617 }
618 if (operator == Token.UNION) {
619 return new UnionPattern(
620 getLhsExpression().toPattern(config),
621 getRhsExpression().toPattern(config));
622 } else {
623 if (operator == Token.EXCEPT) {
624 return new ExceptPattern(
625 getLhsExpression().toPattern(config),
626 getRhsExpression().toPattern(config));
627 } else {
628 return new IntersectPattern(
629 getLhsExpression().toPattern(config),
630 getRhsExpression().toPattern(config));
631 }
632 }
633 }
634
635 private boolean isPredicatePattern(Expression exp) {
636 if (exp instanceof ItemChecker) {
637 exp = ((ItemChecker)exp).getBaseExpression();
638 }
639 return exp instanceof FilterExpression && (((FilterExpression)exp).getSelectExpression() instanceof ContextItemExpression);
640 }
641
642 /**
643 * Get the element name used to identify this expression in exported expression format
644 *
645 * @return the element name used to identify this expression
646 */
647 @Override
648 protected String tag() {
649 if (operator == Token.UNION) {
650 return "union";
651 }
652 return Token.tokens[operator];
653 }
654
655 /**
656 * Iterate over the value of the expression. The result will always be sorted in document order,
657 * with duplicates eliminated
658 *
659 * @param c The context for evaluation
660 * @return a SequenceIterator representing the union of the two operands
661 */
662
663 /*@NotNull*/
664 public SequenceIterator<?> iterate(final XPathContext c) throws XPathException {
665 SequenceIterator<? extends NodeInfo> i1 =
666 (SequenceIterator<? extends NodeInfo>)getLhsExpression().iterate(c);
667 SequenceIterator<? extends NodeInfo> i2 =
668 (SequenceIterator<? extends NodeInfo>)getRhsExpression().iterate(c);
669 switch (operator) {
670 case Token.UNION:
671 return new UnionEnumeration(i1, i2,
672 GlobalOrderComparer.getInstance());
673 case Token.INTERSECT:
674 return new IntersectionEnumeration(i1, i2,
675 GlobalOrderComparer.getInstance());
676 case Token.EXCEPT:
677 return new DifferenceEnumeration(i1, i2,
678 GlobalOrderComparer.getInstance());
679 }
680 throw new UnsupportedOperationException("Unknown operator in Venn Expression");
681 }
682
683 /**
684 * Get the effective boolean value. In the case of a union expression, this
685 * is reduced to an OR expression, for efficiency
686 */
687
688 public boolean effectiveBooleanValue(final XPathContext context) throws XPathException {
689 if (operator == Token.UNION) {
690 // NOTE: this optimization was probably already done statically
691 return getLhsExpression().effectiveBooleanValue(context) || getRhsExpression().effectiveBooleanValue(context);
692 } else {
693 return super.effectiveBooleanValue(context);
694 }
695 }
696
697 /**
698 * Get the (partial) name of a class that supports streaming of this kind of expression
699 *
700 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
701 * or null if there is no such class
702 */
703 @Override
704 public String getStreamerName() {
705 return "VennExpression";
706 }
707 }
708