Debian Codegraph @

net/sf/saxon/expr/GeneralComparison.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.parser.*;
12 import net.sf.saxon.expr.sort.AtomicComparer;
13 import net.sf.saxon.expr.sort.CodepointCollator;
14 import net.sf.saxon.expr.sort.GenericAtomicComparer;
15 import net.sf.saxon.expr.sort.UntypedNumericComparer;
16 import net.sf.saxon.functions.Minimax;
17 import net.sf.saxon.functions.SystemFunction;
18 import net.sf.saxon.lib.ConversionRules;
19 import net.sf.saxon.lib.StringCollator;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.type.*;
24 import net.sf.saxon.value.*;
25 import net.sf.saxon.value.StringValue;
26
27 import java.util.ArrayList;
28 import java.util.List;
29
30
31 /**
32 * GeneralComparison: a boolean expression that compares two expressions
33 * for equals, not-equals, greater-than or less-than. This implements the operators
34 * =, !=, <, >, etc. This implementation is not used when in backwards-compatible mode
35 */
36
37 public abstract class GeneralComparison extends BinaryExpression implements ComparisonExpression, Callable {
38
39 public static final int ONE_TO_ONE = 0;
40 public static final int MANY_TO_ONE = 1;
41 public static final int MANY_TO_MANY = 2;
42 // Note, a one-to-many comparison is inverted into a many-to-one comparison
43
44 protected int singletonOperator;
45 protected AtomicComparer comparer;
46 protected boolean needsRuntimeCheck = true;
47 protected int comparisonCardinality = MANY_TO_MANY;
48 protected boolean doneWarnings = false;
49
50
51 /**
52 * Create a relational expression identifying the two operands and the operator
53 *
54 * @param p0 the left-hand operand
55 * @param op the operator, as a token returned by the Tokenizer (e.g. Token.LT)
56 * @param p1 the right-hand operand
57 */
58
59 public GeneralComparison(Expression p0, int op, Expression p1) {
60 super(p0, op, p1);
61 singletonOperator = getCorrespondingSingletonOperator(op);
62 }
63
64 /**
65 * Ask whether a runtime check of the types of the operands is needed
66 *
67 * @return true if the types of the operands need to be checked at run-time
68 */
69
70 public boolean needsRuntimeCheck() {
71 return needsRuntimeCheck;
72 }
73
74 /**
75 * Say whether a runtime check of the types of the operands is needed
76 *
77 * @param needsCheck true if the types of the operands need to be checked at run-time
78 */
79
80 public void setNeedsRuntimeCheck(boolean needsCheck) {
81 needsRuntimeCheck = needsCheck;
82 }
83
84 /**
85 * Ask whether the comparison is known to be many-to-one, one-to-one, or many-to-many.
86 * (Note, an expression that is one-to-many will be converted to one that is many-to-one).
87 *
88 * @return the Cardinality of the comparison as one of the values {@link #ONE_TO_ONE},
89 * {@link #MANY_TO_MANY}, {@link #MANY_TO_ONE}
90 */
91
92 public int getComparisonCardinality() {
93 return comparisonCardinality;
94 }
95
96 /**
97 * Say whether the comparison is known to be many-to-one, one-to-one, or many-to-many.
98 *
99 * @param card the Cardinality of the comparison as one of the values {@link #ONE_TO_ONE},
100 * {@link #MANY_TO_MANY}, {@link #MANY_TO_ONE}
101 */
102 public void setComparisonCardinality(int card) {
103 comparisonCardinality = card;
104 }
105
106 /**
107 * Set the comparer to be used
108 *
109 * @param comparer the comparer to be used
110 */
111
112 public void setAtomicComparer(AtomicComparer comparer) {
113 this.comparer = comparer;
114 }
115
116 /**
117 * Get a name identifying the kind of expression, in terms meaningful to a user.
118 *
119 * @return a name identifying the kind of expression, in terms meaningful to a user.
120 * The name will always be in the form of a lexical XML QName, and should match the name used
121 * in explain() output displaying the expression.
122 */
123
124 public String getExpressionName() {
125 return "GeneralComparison";
126 }
127
128 /**
129 * Get the namespace context for this expression, needed in the event that one operand contains untyped
130 * atomic values and the other contains QNames
131 */
132
133 public NamespaceResolver getNamespaceResolver() {
134 return getRetainedStaticContext();
135 }
136
137 /**
138 * Get the AtomicComparer used to compare atomic values. This encapsulates any collation that is used
139 */
140
141 public AtomicComparer getAtomicComparer() {
142 return comparer;
143 }
144
145 /**
146 * Get the primitive (singleton) operator used: one of Token.FEQ, Token.FNE, Token.FLT, Token.FGT,
147 * Token.FLE, Token.FGE
148 */
149
150 public int getSingletonOperator() {
151 return singletonOperator;
152 }
153
154 /**
155 * Determine whether untyped atomic values should be converted to the type of the other operand
156 *
157 * @return true if untyped values should be converted to the type of the other operand, false if they
158 * should be converted to strings.
159 */
160
161 public boolean convertsUntypedToOther() {
162 return true;
163 }
164
165 /**
166 * Determine the static cardinality. Returns [1..1]
167 */
168
169 public int computeCardinality() {
170 return StaticProperty.EXACTLY_ONE;
171 }
172
173 /**
174 * Type-check the expression
175 *
176 * @return the checked expression
177 */
178
179 /*@NotNull*/
180 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
181
182 final Configuration config = visitor.getConfiguration();
183 final TypeHierarchy th = config.getTypeHierarchy();
184
185 Expression oldOp0 = getLhsExpression();
186 Expression oldOp1 = getRhsExpression();
187
188 getLhs().typeCheck(visitor, contextInfo);
189 getRhs().typeCheck(visitor, contextInfo);
190
191 // If either operand is statically empty, return false
192
193 if (Literal.isEmptySequence(getLhsExpression()) || Literal.isEmptySequence(getRhsExpression())) {
194 return Literal.makeLiteral(BooleanValue.FALSE, this);
195 }
196
197 // Neither operand needs to be sorted
198
199 setLhsExpression(getLhsExpression().unordered(false, false));
200 setRhsExpression(getRhsExpression().unordered(false, false));
201
202 SequenceType atomicType = SequenceType.ATOMIC_SEQUENCE;
203
204 TypeChecker tc = config.getTypeChecker(false);
205 RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 0);
206 //role0.setSourceLocator(this);
207 setLhsExpression(tc.staticTypeCheck(getLhsExpression(), atomicType, role0, visitor));
208
209 RoleDiagnostic role1 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 1);
210 //role1.setSourceLocator(this);
211 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), atomicType, role1, visitor));
212
213 if (getLhsExpression() != oldOp0) {
214 adoptChildExpression(getLhsExpression());
215 }
216
217 if (getRhsExpression() != oldOp1) {
218 adoptChildExpression(getRhsExpression());
219 }
220
221 ItemType t0 = getLhsExpression().getItemType(); // this is always an atomic type or union type or xs:error
222 ItemType t1 = getRhsExpression().getItemType(); // this is always an atomic type or union type or xs:error
223
224 if (t0 instanceof ErrorType || t1 instanceof ErrorType) {
225 return Literal.makeLiteral(BooleanValue.FALSE, this);
226 }
227
228 if (((PlainType) t0).isExternalType() || ((PlainType) t1).isExternalType()) {
229 XPathException err = new XPathException("Cannot perform comparisons involving external objects");
230 err.setIsTypeError(true);
231 err.setErrorCode("XPTY0004");
232 err.setLocator(getLocation());
233 throw err;
234 }
235
236 BuiltInAtomicType pt0 = (BuiltInAtomicType) t0.getPrimitiveItemType();
237 BuiltInAtomicType pt1 = (BuiltInAtomicType) t1.getPrimitiveItemType();
238
239 int c0 = getLhsExpression().getCardinality();
240 int c1 = getRhsExpression().getCardinality();
241
242 if (c0 == StaticProperty.EMPTY || c1 == StaticProperty.EMPTY) {
243 return Literal.makeLiteral(BooleanValue.FALSE, this);
244 }
245
246 if (t0.equals(BuiltInAtomicType.ANY_ATOMIC) || t0.equals(BuiltInAtomicType.UNTYPED_ATOMIC) ||
247 t1.equals(BuiltInAtomicType.ANY_ATOMIC) || t1.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
248 // then no static type checking is possible
249 } else {
250 if (!Type.isPossiblyComparable(pt0, pt1, Token.isOrderedOperator(singletonOperator))) {
251 String message = "In {" + toShortString() + "}: cannot compare " + t0 + " to " + t1;
252 if (Cardinality.allowsZero(c0) || Cardinality.allowsZero(c1)) {
253 if (!doneWarnings) { // avoid duplicate warnings
254 doneWarnings = true;
255 String which = "one";
256 if (Cardinality.allowsZero(c0) && !Cardinality.allowsZero(c1)) {
257 which = "the first";
258 } else if (Cardinality.allowsZero(c1) && !Cardinality.allowsZero(c0)) {
259 which = "the second";
260 }
261 visitor.getStaticContext().issueWarning(
262 message + ". The comparison can succeed only if " + which +
263 " operand is empty, and in that case will always be false", getLocation());
264 }
265 } else {
266 XPathException err = new XPathException(message);
267 err.setErrorCode("XPTY0004");
268 err.setIsTypeError(true);
269 err.setLocator(getLocation());
270 throw err;
271 }
272 }
273
274 }
275
276 needsRuntimeCheck = !Type.isGuaranteedGenerallyComparable(pt0, pt1, Token.isOrderedOperator(singletonOperator));
277
278 if (!Cardinality.allowsMany(c0) /*c0 == StaticProperty.EXACTLY_ONE*/ &&
279 !Cardinality.allowsMany(c1) /*c1 == StaticProperty.EXACTLY_ONE */ &&
280 !t0.equals(BuiltInAtomicType.ANY_ATOMIC) &&
281 !t1.equals(BuiltInAtomicType.ANY_ATOMIC)) {
282
283 // Use a value comparison if both arguments are singletons, and if the comparison operator to
284 // be used can be determined.
285
286 Expression e0 = getLhsExpression();
287 Expression e1 = getRhsExpression();
288
289 if (t0.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
290 if (t1.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
291 e0 = new CastExpression(getLhsExpression(), BuiltInAtomicType.STRING, Cardinality.allowsZero(c0));
292 adoptChildExpression(e0);
293 e1 = new CastExpression(getRhsExpression(), BuiltInAtomicType.STRING, Cardinality.allowsZero(c1));
294 adoptChildExpression(e1);
295 } else if (th.isSubType(t1, NumericType.getInstance())) {
296 // e0 = new CastExpression(getLhsExpression(), BuiltInAtomicType.DOUBLE, false);
297 // adoptChildExpression(e0);
298 Expression vun = makeCompareUntypedToNumeric(getLhsExpression(), getRhsExpression(), singletonOperator);
299 return vun.typeCheck(visitor, contextInfo);
300 } else {
301 e0 = new CastExpression(getLhsExpression(), pt1, Cardinality.allowsZero(c0));
302 adoptChildExpression(e0);
303 }
304 } else if (t1.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
305 if (th.isSubType(t0, NumericType.getInstance())) {
306 // e1 = new CastExpression(getRhsExpression(), BuiltInAtomicType.DOUBLE, false);
307 // adoptChildExpression(e1);
308 Expression vun = makeCompareUntypedToNumeric(getRhsExpression(), getLhsExpression(), Token.inverse(singletonOperator));
309 return vun.typeCheck(visitor, contextInfo);
310 } else {
311 e1 = new CastExpression(getRhsExpression(), pt0, Cardinality.allowsZero(c1));
312 adoptChildExpression(e1);
313 }
314 }
315
316 ValueComparison vc = new ValueComparison(e0, singletonOperator, e1);
317 vc.setAtomicComparer(comparer);
318 vc.setResultWhenEmpty(BooleanValue.FALSE);
319 ExpressionTool.copyLocationInfo(this, vc);
320 Optimizer.trace(config, "Replaced general comparison by value comparison", vc);
321 return vc.typeCheck(visitor, contextInfo);
322 }
323
324 StaticContext env = visitor.getStaticContext();
325 if (comparer == null) {
326 // In XSLT, only do this the first time through, otherwise default-collation may be missed
327 final String defaultCollationName = env.getDefaultCollationName();
328 StringCollator collation = config.getCollation(defaultCollationName);
329 if (collation == null) {
330 collation = CodepointCollator.getInstance();
331 }
332 comparer = GenericAtomicComparer.makeAtomicComparer(
333 pt0, pt1, collation, config.getConversionContext());
334 }
335
336 // evaluate the expression now if both arguments are constant
337
338 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
339 return Literal.makeLiteral(evaluateItem(env.makeEarlyEvaluationContext()), this);
340 }
341 return this;
342 }
343
344 private Expression makeCompareUntypedToNumeric(Expression lhs, Expression rhs, int operator) {
345 ValueComparison vc = new ValueComparison(lhs, operator, rhs);
346 vc.setAtomicComparer(new UntypedNumericComparer());
347 ExpressionTool.copyLocationInfo(this, vc);
348 Optimizer.trace(getConfiguration(), "Replaced general comparison by untyped-numeric value comparison", vc);
349 return vc;
350 }
351
352
353 private static Expression makeMinOrMax(Expression exp, String function) {
354 if (Cardinality.allowsMany(exp.getCardinality())) {
355 Expression fn = SystemFunction.makeCall(function, exp.getRetainedStaticContext(), exp);
356 assert fn != null;
357 ((Minimax) ((SystemFunctionCall) fn).getTargetFunction()).setIgnoreNaN(true);
358 return fn;
359 } else {
360 return exp;
361 }
362 }
363
364 @Override
365 public int getIntrinsicDependencies() {
366 // The expression is dependent on the static namespace context if one operand might deliver
367 // untypedAtomic and the other might deliver a QName
368 TypeHierarchy th = getConfiguration().getTypeHierarchy();
369 if (mayInvolveCastToQName(th, getLhsExpression(), getRhsExpression()) ||
370 mayInvolveCastToQName(th, getRhsExpression(), getLhsExpression())) {
371 return StaticProperty.DEPENDS_ON_STATIC_CONTEXT;
372 } else {
373 return 0;
374 }
375 }
376
377 private boolean mayInvolveCastToQName(TypeHierarchy th, Expression e1, Expression e2) {
378 SimpleType s1 = (SimpleType) e1.getItemType().getAtomizedItemType();
379 return (s1 == BuiltInAtomicType.ANY_ATOMIC || s1.isNamespaceSensitive()) &&
380 th.relationship(e2.getItemType().getAtomizedItemType(), BuiltInAtomicType.UNTYPED_ATOMIC) != TypeHierarchy.DISJOINT &&
381 (e2.getSpecialProperties() & StaticProperty.NOT_UNTYPED_ATOMIC) == 0;
382 }
383
384 @Override
385 public boolean equals(Object other) {
386 return other instanceof GeneralComparison &&
387 super.equals(other) &&
388 comparer.equals(((GeneralComparison) other).comparer);
389 }
390
391
392 /**
393 * Optimize the expression
394 *
395 * @return the checked expression
396 */
397
398 /*@NotNull*/
399 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
400
401 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
402 final StaticContext env = visitor.getStaticContext();
403
404 getLhs().optimize(visitor, contextInfo);
405 getRhs().optimize(visitor, contextInfo);
406
407 // If either operand is statically empty, return false
408
409 if (Literal.isEmptySequence(getLhsExpression()) || Literal.isEmptySequence(getRhsExpression())) {
410 return Literal.makeLiteral(BooleanValue.FALSE, this);
411 }
412
413 // Neither operand needs to be sorted
414
415 setLhsExpression(getLhsExpression().unordered(false, false));
416 setRhsExpression(getRhsExpression().unordered(false, false));
417
418 if (getLhsExpression() instanceof Literal && getRhsExpression() instanceof Literal) {
419 return Literal.makeLiteral(
420 evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()).materialize(), this
421 );
422 }
423
424 ItemType t0 = getLhsExpression().getItemType();
425 ItemType t1 = getRhsExpression().getItemType();
426
427 int c0 = getLhsExpression().getCardinality();
428 int c1 = getRhsExpression().getCardinality();
429
430 // Check if neither argument allows a sequence of >1
431
432 boolean many0 = Cardinality.allowsMany(c0);
433 boolean many1 = Cardinality.allowsMany(c1);
434
435 if (many0) {
436 if (many1) {
437 comparisonCardinality = MANY_TO_MANY;
438 } else {
439 comparisonCardinality = MANY_TO_ONE;
440 }
441 } else {
442 if (many1) {
443 GeneralComparison mc = getInverseComparison();
444 mc.comparisonCardinality = MANY_TO_ONE;
445 ExpressionTool.copyLocationInfo(this, mc);
446 mc.comparer = comparer;
447 mc.needsRuntimeCheck = needsRuntimeCheck;
448 return mc.optimize(visitor, contextInfo);
449 } else {
450 comparisonCardinality = ONE_TO_ONE;
451 }
452 }
453
454 // look for (N to M = I)
455 if (operator == Token.EQUALS) {
456
457 // First a variable range...
458
459 if (getLhsExpression() instanceof RangeExpression) {
460 Expression min = ((RangeExpression) getLhsExpression()).getLhsExpression();
461 Expression max = ((RangeExpression) getLhsExpression()).getRhsExpression();
462 IntegerRangeTest ir = new IntegerRangeTest(getRhsExpression(), min, max);
463 ExpressionTool.copyLocationInfo(this, ir);
464 return ir;
465 }
466
467 if (getRhsExpression() instanceof RangeExpression) {
468 Expression min = ((RangeExpression) getRhsExpression()).getLhsExpression();
469 Expression max = ((RangeExpression) getRhsExpression()).getRhsExpression();
470 IntegerRangeTest ir = new IntegerRangeTest(getLhsExpression(), min, max);
471 ExpressionTool.copyLocationInfo(this, ir);
472 return ir;
473 }
474
475 // Now a fixed range...
476
477 if (getLhsExpression() instanceof Literal) {
478 GroundedValue value0 = ((Literal) getLhsExpression()).getValue();
479 if (value0 instanceof IntegerRange) {
480 long min = ((IntegerRange) value0).getStart();
481 long max = ((IntegerRange) value0).getEnd();
482 IntegerRangeTest ir = new IntegerRangeTest(getRhsExpression(),
483 Literal.makeLiteral(Int64Value.makeIntegerValue(min), this),
484 Literal.makeLiteral(Int64Value.makeIntegerValue(max), this));
485 ExpressionTool.copyLocationInfo(this, ir);
486 return ir;
487 }
488 }
489
490 if (getRhsExpression() instanceof Literal) {
491 GroundedValue value1 = ((Literal) getRhsExpression()).getValue();
492 if (value1 instanceof IntegerRange) {
493 long min = ((IntegerRange) value1).getStart();
494 long max = ((IntegerRange) value1).getEnd();
495 IntegerRangeTest ir = new IntegerRangeTest(getLhsExpression(),
496 Literal.makeLiteral(Int64Value.makeIntegerValue(min), this),
497 Literal.makeLiteral(Int64Value.makeIntegerValue(max), this));
498 ExpressionTool.copyLocationInfo(this, ir);
499 return ir;
500 }
501 }
502 }
503
504 // If the operator is gt, ge, lt, le then replace X < Y by min(X) < max(Y)
505
506 // This optimization is done only in the case where at least one of the
507 // sequences is known to be purely numeric. It isn't safe if both sequences
508 // contain untyped atomic values, because in that case, the type of the
509 // comparison isn't known in advance. For example [(1, U1) < ("fred", U2)]
510 // involves both string and numeric comparisons.
511
512 // Generally, do this optimization for a many-to-many comparison, because it prevents
513 // early exit on a many-to-one comparison. But with a many-to-one comparison, do it
514 // if the "many" branch can be lifted up the expression tree.
515
516 if (operator != Token.EQUALS &&
517 operator != Token.NE &&
518 (comparisonCardinality == MANY_TO_MANY || comparisonCardinality == MANY_TO_ONE && manyOperandIsLiftable()) &&
519 (th.isSubType(t0, NumericType.getInstance()) || th.isSubType(t1, NumericType.getInstance()))) {
520
521 // System.err.println("** using minimax optimization **");
522 ValueComparison vc;
523 switch (operator) {
524 case Token.LT:
525 case Token.LE:
526 vc = new ValueComparison(makeMinOrMax(getLhsExpression(), "min"),
527 singletonOperator,
528 makeMinOrMax(getRhsExpression(), "max"));
529 vc.setResultWhenEmpty(BooleanValue.FALSE);
530 vc.setAtomicComparer(comparer);
531 break;
532 case Token.GT:
533 case Token.GE:
534 vc = new ValueComparison(makeMinOrMax(getLhsExpression(), "max"),
535 singletonOperator,
536 makeMinOrMax(getRhsExpression(), "min"));
537 vc.setResultWhenEmpty(BooleanValue.FALSE);
538 vc.setAtomicComparer(comparer);
539 break;
540 default:
541 throw new UnsupportedOperationException("Unknown operator " + operator);
542 }
543
544 ExpressionTool.copyLocationInfo(this, vc);
545 vc.setRetainedStaticContext(getRetainedStaticContext());
546 return vc.typeCheck(visitor, contextInfo);
547 }
548
549 // evaluate the expression now if both arguments are constant
550
551 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
552 return Literal.makeLiteral(evaluateItem(env.makeEarlyEvaluationContext()), this);
553 }
554
555 // Finally, convert to use the GeneralComparisonEE algorithm if in Saxon-EE
556 return visitor.obtainOptimizer()
557 .optimizeGeneralComparison(visitor, this, false, contextInfo);
558 }
559
560 private boolean manyOperandIsLiftable() {
561 if (getParentExpression() instanceof ContextSwitchingExpression &&
562 ((ContextSwitchingExpression)getParentExpression()).getActionExpression() == this) {
563 for (Operand o : operands()) {
564 if (Cardinality.allowsMany(o.getChildExpression().getCardinality())) {
565 if (ExpressionTool.dependsOnFocus(o.getChildExpression())) {
566 return false;
567 }
568 }
569 }
570 return true;
571 }
572 return false;
573 }
574
575 /**
576 * Evaluate the expression in a given context
577 *
578 * @param context the given context for evaluation
579 * @return a BooleanValue representing the result of the numeric comparison of the two operands
580 */
581
582 /*@Nullable*/
583 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
584 switch (comparisonCardinality) {
585 case ONE_TO_ONE: {
586 AtomicValue value0 = (AtomicValue) getLhsExpression().evaluateItem(context);
587 AtomicValue value1 = (AtomicValue) getRhsExpression().evaluateItem(context);
588 return BooleanValue.get(evaluateOneToOne(value0, value1, context));
589 }
590 case MANY_TO_ONE: {
591 SequenceIterator iter0 = getLhsExpression().iterate(context);
592 AtomicValue value1 = (AtomicValue) getRhsExpression().evaluateItem(context);
593 return BooleanValue.get(evaluateManyToOne(iter0, value1, context));
594 }
595 case MANY_TO_MANY: {
596 SequenceIterator iter1 = getLhsExpression().iterate(context);
597 SequenceIterator iter2 = getRhsExpression().iterate(context);
598 return BooleanValue.get(evaluateManyToMany(iter1, iter2, context));
599 }
600 }
601 return null;
602 }
603
604 /**
605 * Evaluate the expression
606 *
607 * @param context the dynamic evaluation context
608 * @param arguments the values of the arguments, supplied as SequenceIterators
609 * @return the result of the evaluation, in the form of a SequenceIterator
610 * @throws XPathException if a dynamic error occurs during the evaluation of the expression
611 */
612
613 public BooleanValue call(XPathContext context, Sequence[] arguments) throws XPathException {
614 switch (comparisonCardinality) {
615 case ONE_TO_ONE: {
616 AtomicValue value0 = (AtomicValue) arguments[0].head();
617 AtomicValue value1 = (AtomicValue) arguments[1].head();
618 return BooleanValue.get(evaluateOneToOne(value0, value1, context));
619 }
620 case MANY_TO_ONE: {
621 SequenceIterator iter0 = arguments[0].iterate();
622 AtomicValue value1 = (AtomicValue) arguments[1].head();
623 return BooleanValue.get(evaluateManyToOne(iter0, value1, context));
624 }
625 case MANY_TO_MANY: {
626 SequenceIterator iter1 = arguments[0].iterate();
627 SequenceIterator iter2 = arguments[1].iterate();
628 return BooleanValue.get(evaluateManyToMany(iter1, iter2, context));
629 }
630 }
631 return null;
632 }
633
634 /**
635 * Evaluate the expression in a boolean context
636 *
637 * @param context the given context for evaluation
638 * @return a boolean representing the result of the numeric comparison of the two operands
639 */
640
641 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
642 switch (comparisonCardinality) {
643 case ONE_TO_ONE: {
644 AtomicValue value0 = (AtomicValue) getLhsExpression().evaluateItem(context);
645 AtomicValue value1 = (AtomicValue) getRhsExpression().evaluateItem(context);
646 return evaluateOneToOne(value0, value1, context);
647 }
648 case MANY_TO_ONE: {
649 SequenceIterator iter0 = getLhsExpression().iterate(context);
650 AtomicValue value1 = (AtomicValue) getRhsExpression().evaluateItem(context);
651 return evaluateManyToOne(iter0, value1, context);
652 }
653 case MANY_TO_MANY: {
654 SequenceIterator iter1 = getLhsExpression().iterate(context);
655 SequenceIterator iter2 = getRhsExpression().iterate(context);
656 return evaluateManyToMany(iter1, iter2, context);
657 }
658 }
659 return false;
660 }
661
662 /**
663 * Evaluate a (zero-or-one)-to-(zero-or-one) comparison
664 *
665 * @param value0 the first value, or null if empty
666 * @param value1 the second value, or null if empty
667 * @param context dynamic evaluation context
668 * @return the comparison result
669 * @throws XPathException if a dynamic error occurs
670 */
671
672 private boolean evaluateOneToOne(AtomicValue value0, AtomicValue value1, XPathContext context) throws XPathException {
673 try {
674 return !(value0 == null || value1 == null) &&
675 compare(value0, singletonOperator, value1, comparer.provideContext(context),
676 needsRuntimeCheck, context, getRetainedStaticContext());
677 } catch (XPathException e) {
678 // re-throw the exception with location information added
679 e.maybeSetLocation(getLocation());
680 e.maybeSetContext(context);
681 throw e;
682 }
683
684 }
685
686 /**
687 * Evaluate a (zero-to-many)-to-(zero-or-one) comparison
688 *
689 * @param iter0 iterator over the first value
690 * @param value1 the second value, or null if empty
691 * @param context dynamic evaluation context
692 * @return the comparison result
693 * @throws XPathException if a dynamic error occurs
694 */
695
696 private boolean evaluateManyToOne(SequenceIterator iter0, AtomicValue value1, XPathContext context) throws XPathException {
697 try {
698 if (value1 == null) {
699 return false;
700 }
701 AtomicValue item0;
702 AtomicComparer boundComparer = comparer.provideContext(context);
703 while ((item0 = (AtomicValue) iter0.next()) != null) {
704 if (compare(item0, singletonOperator, value1, boundComparer, needsRuntimeCheck, context, getRetainedStaticContext())) {
705 iter0.close();
706 return true;
707 }
708 }
709 return false;
710 } catch (XPathException e) {
711 // re-throw the exception with location information added
712 e.maybeSetLocation(getLocation());
713 e.maybeSetContext(context);
714 throw e;
715 }
716
717 }
718
719 /**
720 * Evaluate a (zero-or-one)-to-(zero-or-one) comparison
721 *
722 * @param iter0 iterator over the first value
723 * @param iter1 iterator the second value
724 * @param context dynamic evaluation context
725 * @return the comparison result
726 * @throws XPathException if a dynamic error occurs
727 */
728
729 public boolean evaluateManyToMany(SequenceIterator iter0, SequenceIterator iter1, XPathContext context) throws XPathException {
730 try {
731 boolean exhausted0 = false;
732 boolean exhausted1 = false;
733
734 List<AtomicValue> value0 = new ArrayList<>();
735 List<AtomicValue> value1 = new ArrayList<>();
736
737 AtomicComparer boundComparer = comparer.provideContext(context);
738
739 // Read items from the two sequences alternately, in each case comparing the item to
740 // all items that have previously been read from the other sequence. In the worst case
741 // the number of comparisons is N*M, and the memory usage is (max(N,M)*2) where N and M
742 // are the number of items in the two sequences. In practice, either M or N is often 1,
743 // meaning that in this case neither list will ever hold more than one item.
744
745 while (true) {
746 if (!exhausted0) {
747 AtomicValue item0 = (AtomicValue) iter0.next();
748 if (item0 == null) {
749 if (exhausted1) {
750 return false;
751 }
752 exhausted0 = true;
753 } else {
754 for (AtomicValue item1 : value1) {
755 if (compare(item0, singletonOperator, item1, boundComparer, needsRuntimeCheck, context, getRetainedStaticContext())) {
756 iter0.close();
757 iter1.close();
758 return true;
759 }
760 }
761 if (!exhausted1) {
762 value0.add(item0);
763 }
764 }
765 }
766 if (!exhausted1) {
767 AtomicValue item1 = (AtomicValue) iter1.next();
768 if (item1 == null) {
769 if (exhausted0) {
770 return false;
771 }
772 exhausted1 = true;
773 } else {
774 for (AtomicValue item0 : value0) {
775 if (compare(item0, singletonOperator, item1, boundComparer, needsRuntimeCheck, context, getRetainedStaticContext())) {
776 iter0.close();
777 iter1.close();
778 return true;
779 }
780 }
781 if (!exhausted0) {
782 value1.add(item1);
783 }
784 }
785 }
786 }
787 } catch (XPathException e) {
788 // re-throw the exception with location information added
789 e.maybeSetLocation(getLocation());
790 e.maybeSetContext(context);
791 throw e;
792 }
793
794 }
795
796 /**
797 * Compare two atomic values
798 *
799 *
800 * @param a0 the first value
801 * @param operator the singleton version of the comparison operator,
802 * for example {@link net.sf.saxon.expr.parser.Token#FEQ}
803 * @param a1 the second value
804 * @param comparer the comparer to be used to perform the comparison. If the comparer is context-sensitive
805 * then the context must already have been bound using comparer.provideContext().
806 * @param checkTypes set to true if the operand types need to be checked for comparability at runtime
807 * @param context the XPath evaluation context
808 * @param nsResolver namespace resolver
809 * @return true if the comparison succeeds
810 * @throws XPathException if a dynamic error occurs during the comparison
811 */
812
813 public static boolean compare(AtomicValue a0,
814 int operator,
815 AtomicValue a1,
816 AtomicComparer comparer,
817 boolean checkTypes,
818 XPathContext context,
819 NamespaceResolver nsResolver) throws XPathException {
820
821 boolean u0 = a0 instanceof UntypedAtomicValue;
822 boolean u1 = a1 instanceof UntypedAtomicValue;
823 if (u0 != u1) {
824 // one value untyped, the other not
825 final ConversionRules rules = context.getConfiguration().getConversionRules();
826 if (u0) {
827 // a0 is untyped atomic
828 if (a1 instanceof NumericValue) {
829 return UntypedNumericComparer.quickCompare((UntypedAtomicValue) a0, (NumericValue) a1, operator, rules);
830 } else if (a1 instanceof StringValue) {
831 // no conversion needed
832 } else {
833 StringConverter sc = a1.getItemType().getPrimitiveItemType().getStringConverter(rules);
834 if (a1 instanceof QualifiedNameValue) {
835 sc = (StringConverter) sc.setNamespaceResolver(nsResolver);
836 // avoid using cached results - bug 3862
837 a0 = sc.convertString(a0.getStringValueCS()).asAtomic();
838 } else {
839 a0 = ((UntypedAtomicValue) a0).obtainConversionResult(a1.getItemType().getPrimitiveType(), sc).asAtomic();
840 }
841 }
842 } else {
843 // a1 is untyped atomic
844 if (a0 instanceof NumericValue) {
845 return UntypedNumericComparer.quickCompare((UntypedAtomicValue) a1, (NumericValue) a0, Token.inverse(operator), rules);
846 } else if (a0 instanceof StringValue) {
847 // no conversion needed
848 } else {
849 StringConverter sc = a0.getItemType().getPrimitiveItemType().getStringConverter(rules);
850 if (a0 instanceof QualifiedNameValue) {
851 sc = (StringConverter) sc.setNamespaceResolver(nsResolver);
852 // avoid using cached results - bug 3862
853 a1 = sc.convertString(a1.getStringValueCS()).asAtomic();
854 } else {
855 a1 = ((UntypedAtomicValue) a1).obtainConversionResult(a0.getItemType().getPrimitiveType(), sc).asAtomic();
856 }
857 }
858 }
859 checkTypes = false; // No further checking needed if conversion succeeded
860 }
861 return ValueComparison.compare(a0, operator, a1, comparer, checkTypes);
862
863 }
864
865 /**
866 * Determine the data type of the expression
867 *
868 * @return the value BuiltInAtomicType.BOOLEAN
869 */
870
871 /*@NotNull*/
872 public ItemType getItemType() {
873 return BuiltInAtomicType.BOOLEAN;
874 }
875
876 /**
877 * Get the static type of the expression as a UType, following precisely the type
878 * inference rules defined in the XSLT 3.0 specification.
879 *
880 * @return the static item type of the expression according to the XSLT 3.0 defined rules
881 * @param contextItemType static information about the context item
882 */
883 @Override
884 public UType getStaticUType(UType contextItemType) {
885 return UType.BOOLEAN;
886 }
887
888 /**
889 * Return the singleton form of the comparison operator, e.g. FEQ for EQUALS, FGT for GT
890 *
891 * @param op the many-to-many form of the operator, for example {@link Token#LE}
892 * @return the corresponding singleton operator, for example {@link Token#FLE}
893 */
894
895 public static int getCorrespondingSingletonOperator(int op) {
896 switch (op) {
897 case Token.EQUALS:
898 return Token.FEQ;
899 case Token.GE:
900 return Token.FGE;
901 case Token.NE:
902 return Token.FNE;
903 case Token.LT:
904 return Token.FLT;
905 case Token.GT:
906 return Token.FGT;
907 case Token.LE:
908 return Token.FLE;
909 default:
910 return op;
911 }
912 }
913
914 protected GeneralComparison getInverseComparison() {
915 GeneralComparison20 gc2 = new GeneralComparison20(getRhsExpression(), Token.inverse(operator), getLhsExpression());
916 gc2.setRetainedStaticContext(getRetainedStaticContext());
917 return gc2;
918 }
919
920 /**
921 * Get the (partial) name of a class that supports streaming of this kind of expression
922 *
923 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
924 * or null if there is no such class
925 */
926 @Override
927 public String getStreamerName() {
928 return "GeneralComparison";
929 }
930
931
932 // protected String displayOperator() {
933 // return "many-to-many " + super.displayOperator();
934 // }
935
936 /**
937 * Get the element name used to identify this expression in exported expression format
938 * @return the element name used to identify this expression
939 */
940
941 @Override
942 public String tag() {
943 return "gc";
944 }
945
946 protected void explainExtraAttributes(ExpressionPresenter out) {
947 String cc = "";
948 switch (comparisonCardinality) {
949 case ONE_TO_ONE:
950 cc = "1:1";
951 break;
952 case MANY_TO_ONE:
953 cc = "N:1";
954 break;
955 case MANY_TO_MANY:
956 cc = "M:N";
957 break;
958 }
959 out.emitAttribute("card", cc);
960 out.emitAttribute("comp", comparer.save());
961 }
962
963 }
964