Debian Codegraph @

net/sf/saxon/expr/ValueComparison.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.*;
13 import net.sf.saxon.functions.*;
14 import net.sf.saxon.lib.StringCollator;
15 import net.sf.saxon.om.Sequence;
16 import net.sf.saxon.om.StandardNames;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.NoDynamicContextException;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.type.*;
21 import net.sf.saxon.value.*;
22
23 /**
24 * ValueComparison: a boolean expression that compares two atomic values
25 * for equals, not-equals, greater-than or less-than. Implements the operators
26 * eq, ne, lt, le, gt, ge
27 */
28
29 public final class ValueComparison extends BinaryExpression implements ComparisonExpression, Negatable {
30
31 private AtomicComparer comparer;
32 /*@Nullable*/ private BooleanValue resultWhenEmpty = null;
33 private boolean needsRuntimeCheck;
34
35 /**
36 * Create a comparison expression identifying the two operands and the operator
37 *
38 * @param p1 the left-hand operand
39 * @param op the operator, as a token returned by the Tokenizer (e.g. Token.LT)
40 * @param p2 the right-hand operand
41 */
42
43 public ValueComparison(Expression p1, int op, Expression p2) {
44 super(p1, op, p2);
45 }
46
47 /**
48 * Get a name identifying the kind of expression, in terms meaningful to a user.
49 *
50 * @return a name identifying the kind of expression, in terms meaningful to a user.
51 * The name will always be in the form of a lexical XML QName, and should match the name used
52 * in explain() output displaying the expression.
53 */
54
55 public String getExpressionName() {
56 return "ValueComparison";
57 }
58
59 /**
60 * Set the AtomicComparer used to compare atomic values
61 *
62 * @param comparer the AtomicComparer
63 */
64
65 public void setAtomicComparer(AtomicComparer comparer) {
66 this.comparer = comparer;
67 }
68
69 /**
70 * Get the AtomicComparer used to compare atomic values. This encapsulates any collation that is used.
71 * Note that the comparer is always known at compile time.
72 */
73
74 public AtomicComparer getAtomicComparer() {
75 return comparer;
76 }
77
78 /**
79 * Get the primitive (singleton) operator used: one of Token.FEQ, Token.FNE, Token.FLT, Token.FGT,
80 * Token.FLE, Token.FGE
81 */
82
83 public int getSingletonOperator() {
84 return operator;
85 }
86
87 /**
88 * Determine whether untyped atomic values should be converted to the type of the other operand
89 *
90 * @return true if untyped values should be converted to the type of the other operand, false if they
91 * should be converted to strings.
92 */
93
94 public boolean convertsUntypedToOther() {
95 return comparer instanceof UntypedNumericComparer;
96 }
97
98 /**
99 * Set the result to be returned if one of the operands is an empty sequence
100 *
101 * @param value the result to be returned if an operand is empty. Supply null to mean the empty sequence.
102 */
103
104 public void setResultWhenEmpty(BooleanValue value) {
105 resultWhenEmpty = value;
106 }
107
108 /**
109 * Get the result to be returned if one of the operands is an empty sequence
110 *
111 * @return BooleanValue.TRUE, BooleanValue.FALSE, or null (meaning the empty sequence)
112 */
113
114 public BooleanValue getResultWhenEmpty() {
115 return resultWhenEmpty;
116 }
117
118 /**
119 * Determine whether a run-time check is needed to check that the types of the arguments
120 * are comparable
121 *
122 * @return true if a run-time check is needed
123 */
124
125 public boolean needsRuntimeComparabilityCheck() {
126 return needsRuntimeCheck;
127 }
128
129 /**
130 * Type-check the expression
131 */
132
133 /*@NotNull*/
134 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
135
136 resetLocalStaticProperties();
137 getLhs().typeCheck(visitor, contextInfo);
138 getRhs().typeCheck(visitor, contextInfo);
139
140 Configuration config = visitor.getConfiguration();
141 StaticContext env = visitor.getStaticContext();
142
143 if (Literal.isEmptySequence(getLhsExpression())) {
144 return resultWhenEmpty == null ? getLhsExpression() : Literal.makeLiteral(resultWhenEmpty, this);
145 }
146
147 if (Literal.isEmptySequence(getRhsExpression())) {
148 return resultWhenEmpty == null ? getRhsExpression() : Literal.makeLiteral(resultWhenEmpty, this);
149 }
150
151 if (comparer instanceof UntypedNumericComparer) {
152 return this; // we've already done all that needs to be done
153 }
154
155 final SequenceType optionalAtomic = SequenceType.OPTIONAL_ATOMIC;
156 TypeChecker tc = config.getTypeChecker(false);
157
158 RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 0);
159 setLhsExpression(tc.staticTypeCheck(getLhsExpression(), optionalAtomic, role0, visitor));
160
161 RoleDiagnostic role1 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 1);
162 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), optionalAtomic, role1, visitor));
163
164 PlainType t0 = getLhsExpression().getItemType().getAtomizedItemType();
165 PlainType t1 = getRhsExpression().getItemType().getAtomizedItemType();
166
167 if (t0.isExternalType() || t1.isExternalType()) {
168 XPathException err = new XPathException("Cannot perform comparisons involving external objects");
169 err.setIsTypeError(true);
170 err.setErrorCode("XPTY0004");
171 err.setLocation(getLocation());
172 throw err;
173 }
174
175 BuiltInAtomicType p0 = (BuiltInAtomicType) t0.getPrimitiveItemType();
176 if (p0.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
177 p0 = BuiltInAtomicType.STRING;
178 }
179 BuiltInAtomicType p1 = (BuiltInAtomicType) t1.getPrimitiveItemType();
180 if (p1.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
181 p1 = BuiltInAtomicType.STRING;
182 }
183
184 needsRuntimeCheck =
185 p0.equals(BuiltInAtomicType.ANY_ATOMIC) || p1.equals(BuiltInAtomicType.ANY_ATOMIC);
186
187 if (!needsRuntimeCheck && !Type.isPossiblyComparable(p0, p1, Token.isOrderedOperator(operator))) {
188 boolean opt0 = Cardinality.allowsZero(getLhsExpression().getCardinality());
189 boolean opt1 = Cardinality.allowsZero(getRhsExpression().getCardinality());
190 if (opt0 || opt1) {
191 // This is a comparison such as (xs:integer? eq xs:date?). This is almost
192 // certainly an error, but we need to let it through because it will work if
193 // one of the operands is an empty sequence.
194
195 String which = null;
196 if (opt0) {
197 which = "the first operand is";
198 }
199 if (opt1) {
200 which = "the second operand is";
201 }
202 if (opt0 && opt1) {
203 which = "one or both operands are";
204 }
205
206 visitor.getStaticContext().issueWarning("Comparison of " + t0.toString() +
207 (opt0 ? "?" : "") + " to " + t1.toString() +
208 (opt1 ? "?" : "") + " will fail unless " + which + " empty", getLocation());
209 needsRuntimeCheck = true;
210 } else {
211 String message = "In {" + toShortString() + "}: cannot compare " +
212 t0.toString() + " to " + t1.toString();
213 XPathException err = new XPathException(message);
214 err.setIsTypeError(true);
215 err.setErrorCode("XPTY0004");
216 err.setLocation(getLocation());
217 throw err;
218 }
219 }
220 if (!(operator == Token.FEQ || operator == Token.FNE)) {
221 mustBeOrdered(t0, p0);
222 mustBeOrdered(t1, p1);
223 }
224
225 if (comparer == null) {
226 // In XSLT, only do this the first time through, otherwise the default-collation attribute may be missed
227 final String defaultCollationName = env.getDefaultCollationName();
228 StringCollator comp = config.getCollation(defaultCollationName);
229 if (comp == null) {
230 comp = CodepointCollator.getInstance();
231 }
232 comparer = GenericAtomicComparer.makeAtomicComparer(
233 p0, p1, comp, env.getConfiguration().getConversionContext());
234 }
235 return this;
236 }
237
238 private void mustBeOrdered(PlainType t1, BuiltInAtomicType p1) throws XPathException {
239 if (!p1.isOrdered(true)) {
240 XPathException err = new XPathException("Type " + t1.toString() + " is not an ordered type");
241 err.setErrorCode("XPTY0004");
242 err.setIsTypeError(true);
243 err.setLocation(getLocation());
244 throw err;
245 }
246 }
247
248 /**
249 * Perform optimisation of an expression and its subexpressions.
250 * <p>This method is called after all references to functions and variables have been resolved
251 * to the declaration of the function or variable, and after all type checking has been done.</p>
252 *
253 * @param visitor an expression visitor
254 * @param contextInfo the static type of "." at the point where this expression is invoked.
255 * The parameter is set to null if it is known statically that the context item will be undefined.
256 * If the type of the context item is not known statically, the argument is set to
257 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
258 * @return the original expression, rewritten if appropriate to optimize execution
259 * @throws XPathException if an error is discovered during this phase
260 * (typically a type error)
261 */
262
263 /*@NotNull*/
264 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
265
266 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
267
268 getLhs().optimize(visitor, contextInfo);
269 getRhs().optimize(visitor, contextInfo);
270
271 Sequence<?> value0 = null;
272 Sequence<?> value1 = null;
273
274 if (getLhsExpression() instanceof Literal) {
275 value0 = ((Literal) getLhsExpression()).getValue();
276 }
277
278 if (getRhsExpression() instanceof Literal) {
279 value1 = ((Literal) getRhsExpression()).getValue();
280 }
281
282 // evaluate the expression now if both arguments are constant
283
284 if ((value0 != null) && (value1 != null)) {
285 try {
286 AtomicValue r = evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext());
287 return Literal.makeLiteral(r == null ? EmptySequence.getInstance() : r, this);
288 } catch (NoDynamicContextException e) {
289 // early evaluation failed, typically because the implicit context isn't available.
290 // Try again at run-time
291 return this;
292 }
293 }
294
295 // optimise count(x) eq N (or gt N, ne N, eq N, etc)
296 // TODO: extend this to cases where N is not a literal
297
298 if (getLhsExpression().isCallOn(Count.class) && Literal.isAtomic(getRhsExpression())) {
299 Expression e2 = optimizeCount(visitor, false);
300 if (e2 != null) {
301 return e2.optimize(visitor, contextInfo);
302 }
303 } else if (getRhsExpression().isCallOn(Count.class) && Literal.isAtomic(getLhsExpression())) {
304 Expression e2 = optimizeCount(visitor, true);
305 if (e2 != null) {
306 return e2.optimize(visitor, contextInfo);
307 }
308 }
309
310
311 // optimise string-length(x) = 0, >0, !=0 etc
312
313 if (getLhsExpression().isCallOn(StringLength_1.class) &&
314 isZero(value1)) {
315 Expression arg = ((SystemFunctionCall) getLhsExpression()).getArg(0);
316 switch (operator) {
317 case Token.FEQ:
318 case Token.FLE:
319 return SystemFunction.makeCall("not", getRetainedStaticContext(), arg);
320 case Token.FNE:
321 case Token.FGT:
322 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), arg);
323 case Token.FGE:
324 return Literal.makeLiteral(BooleanValue.TRUE, this);
325 case Token.FLT:
326 return Literal.makeLiteral(BooleanValue.FALSE, this);
327 }
328 }
329
330 // optimise (0 = string-length(x)), etc
331
332 if (getRhsExpression().isCallOn(StringLength_1.class) &&
333 isZero(value0)) {
334 Expression arg = ((SystemFunctionCall) getRhsExpression()).getArg(0);
335 switch (operator) {
336 case Token.FEQ:
337 case Token.FGE:
338 return SystemFunction.makeCall("not", getRetainedStaticContext(), arg);
339 case Token.FNE:
340 case Token.FLT:
341 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), arg);
342 case Token.FLE:
343 return Literal.makeLiteral(BooleanValue.TRUE, this);
344 case Token.FGT:
345 return Literal.makeLiteral(BooleanValue.FALSE, this);
346 }
347 }
348
349 // optimise string="" etc
350 // Note we can change S!="" to boolean(S) for cardinality zero-or-one, but we can only
351 // change S="" to not(S) for cardinality exactly-one.
352
353 int p0 = getLhsExpression().getItemType().getPrimitiveType();
354 if ((p0 == StandardNames.XS_STRING ||
355 p0 == StandardNames.XS_ANY_URI ||
356 p0 == StandardNames.XS_UNTYPED_ATOMIC) &&
357 resultWhenEmpty != BooleanValue.TRUE &&
358 getRhsExpression() instanceof Literal &&
359 ((Literal) getRhsExpression()).getValue() instanceof StringValue &&
360 ((StringValue) ((Literal) getRhsExpression()).getValue()).isZeroLength() &&
361 comparer instanceof CodepointCollatingComparer) {
362
363 switch (operator) {
364 case Token.FNE:
365 case Token.FGT:
366 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), getLhsExpression());
367 case Token.FEQ:
368 case Token.FLE:
369 if (getLhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE) {
370 return SystemFunction.makeCall("not", getRetainedStaticContext(), getLhsExpression());
371 }
372 }
373 }
374
375 // optimize "" = string etc
376
377 int p1 = getRhsExpression().getItemType().getPrimitiveType();
378 if ((p1 == StandardNames.XS_STRING ||
379 p1 == StandardNames.XS_ANY_URI ||
380 p1 == StandardNames.XS_UNTYPED_ATOMIC) &&
381 resultWhenEmpty != BooleanValue.TRUE &&
382 getLhsExpression() instanceof Literal &&
383 ((Literal) getLhsExpression()).getValue() instanceof StringValue &&
384 ((StringValue) ((Literal) getLhsExpression()).getValue()).isZeroLength() &&
385 comparer instanceof CodepointCollatingComparer) {
386
387 switch (operator) {
388 case Token.FNE:
389 case Token.FLT:
390 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), getRhsExpression());
391 case Token.FEQ:
392 case Token.FGE:
393 if (getRhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE) {
394 return SystemFunction.makeCall("not", getRetainedStaticContext(), getRhsExpression());
395 }
396 }
397 }
398
399
400 // optimise [position()=last()] etc
401
402 if (getLhsExpression().isCallOn(PositionAndLast.Position.class) &&
403 getRhsExpression().isCallOn(PositionAndLast.Last.class)) {
404 switch (operator) {
405 case Token.FEQ:
406 case Token.FGE:
407 IsLastExpression iletrue = new IsLastExpression(true);
408 ExpressionTool.copyLocationInfo(this, iletrue);
409 return iletrue;
410 case Token.FNE:
411 case Token.FLT:
412 IsLastExpression ilefalse = new IsLastExpression(false);
413 ExpressionTool.copyLocationInfo(this, ilefalse);
414 return ilefalse;
415 case Token.FGT:
416 return Literal.makeLiteral(BooleanValue.FALSE, this);
417 case Token.FLE:
418 return Literal.makeLiteral(BooleanValue.TRUE, this);
419 }
420 }
421 if (getLhsExpression().isCallOn(PositionAndLast.Last.class) &&
422 getRhsExpression().isCallOn(PositionAndLast.Position.class)) {
423 switch (operator) {
424 case Token.FEQ:
425 case Token.FLE:
426 IsLastExpression iletrue = new IsLastExpression(true);
427 ExpressionTool.copyLocationInfo(this, iletrue);
428 return iletrue;
429 case Token.FNE:
430 case Token.FGT:
431 IsLastExpression ilefalse = new IsLastExpression(false);
432 ExpressionTool.copyLocationInfo(this, ilefalse);
433 return ilefalse;
434 case Token.FLT:
435 return Literal.makeLiteral(BooleanValue.FALSE, this);
436 case Token.FGE:
437 return Literal.makeLiteral(BooleanValue.TRUE, this);
438 }
439 }
440
441 // optimize comparison against an integer constant
442
443 if (value1 instanceof Int64Value &&
444 getLhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE &&
445 th.isSubType(getLhsExpression().getItemType(), NumericType.getInstance())) {
446 return new CompareToIntegerConstant(getLhsExpression(), operator, ((Int64Value) value1).longValue());
447 }
448
449 if (value0 instanceof Int64Value &&
450 getRhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE &&
451 th.isSubType(getRhsExpression().getItemType(), NumericType.getInstance())) {
452 return new CompareToIntegerConstant(getRhsExpression(), Token.inverse(operator), ((Int64Value) value0).longValue());
453 }
454
455 // optimize (boolean expression) == (boolean literal)
456
457 if (p0 == StandardNames.XS_BOOLEAN &&
458 p1 == StandardNames.XS_BOOLEAN &&
459 (operator == Token.FEQ || operator == Token.FNE) &&
460 getLhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE &&
461 getRhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE &&
462 (getLhsExpression() instanceof Literal || getRhsExpression() instanceof Literal)) {
463 Literal literal = (Literal) (getLhsExpression() instanceof Literal ? getLhsExpression() : getRhsExpression());
464 Expression other = getLhsExpression() instanceof Literal ? getRhsExpression() : getLhsExpression();
465 boolean negate = (operator == Token.FEQ) != ((BooleanValue) literal.getValue()).getBooleanValue();
466 if (negate) {
467 Expression fn = SystemFunction.makeCall("not", getRetainedStaticContext(), other);
468 assert fn != null;
469 ExpressionTool.copyLocationInfo(this, fn);
470 return fn.optimize(visitor, contextInfo);
471 } else {
472 return other;
473 }
474 }
475
476
477 // optimize generate-id(X) = generate-id(Y) as "X is Y"
478 // This construct is often used in XSLT 1.0 stylesheets.
479 // Only do this if we know the arguments are singletons, because "is" doesn't
480 // do first-value extraction.
481
482 if (getLhsExpression().isCallOn(GenerateId_1.class) && getRhsExpression().isCallOn(GenerateId_1.class)) {
483 SystemFunctionCall f0 = (SystemFunctionCall) getLhsExpression();
484 SystemFunctionCall f1 = (SystemFunctionCall) getRhsExpression();
485 if (!Cardinality.allowsMany(f0.getArg(0).getCardinality()) &&
486 !Cardinality.allowsMany(f1.getArg(0).getCardinality()) &&
487 (operator == Token.FEQ)) {
488 IdentityComparison id =
489 new IdentityComparison(f0.getArg(0),
490 Token.IS,
491 f1.getArg(0));
492 id.setGenerateIdEmulation(true);
493 ExpressionTool.copyLocationInfo(this, id);
494 return id.typeCheck(visitor, contextInfo).optimize(visitor, contextInfo);
495 }
496 }
497
498 return this;
499 }
500
501 /**
502 * Optimize comparisons of count(X) to a literal value. The objective here is to count items in the sequence only
503 * until the result of the comparison is deducible; for example to evaluate (count(X)>2) we can stop at the third
504 * item in the sequence.
505 *
506 * @param inverted true if the call to count(X) is the right-hand operand
507 * @return the optimized expression, or null if no optimization is possible
508 * @throws XPathException if an error occurs
509 */
510
511 /*@Nullable*/
512 private Expression optimizeCount(ExpressionVisitor visitor, boolean inverted) throws XPathException {
513 SystemFunctionCall countFn = (SystemFunctionCall) (inverted ? getRhsExpression() : getLhsExpression());
514 Expression sequence = countFn.getArg(0);
515 sequence = sequence.unordered(false, false);
516 Optimizer opt = visitor.obtainOptimizer();
517
518 AtomicValue literalOperand = (AtomicValue) ((Literal) (inverted ? getLhsExpression() : getRhsExpression())).getValue();
519 int op = inverted ? Token.inverse(operator) : operator;
520
521 if (isZero(literalOperand)) {
522 if (op == Token.FEQ || op == Token.FLE) {
523 // rewrite count(x)=0 as empty(x)
524 Expression result = SystemFunction.makeCall("empty", getRetainedStaticContext(), sequence);
525 opt.trace("Rewrite count()=0 as:", result);
526 return result;
527 } else if (op == Token.FNE || op == Token.FGT) {
528 // rewrite count(x)!=0, count(x)>0 as exists(x)
529 Expression result = SystemFunction.makeCall("exists", getRetainedStaticContext(), sequence);
530 opt.trace("Rewrite count()>0 as:", result);
531 return result;
532 } else if (op == Token.FGE) {
533 // rewrite count(x)>=0 as true()
534 return Literal.makeLiteral(BooleanValue.TRUE, this);
535 } else { // singletonOperator == Token.FLT
536 // rewrite count(x)<0 as false()
537 return Literal.makeLiteral(BooleanValue.FALSE, this);
538 }
539 } else if (literalOperand instanceof NumericValue) {
540 long operand;
541 if (literalOperand instanceof IntegerValue) {
542 operand = ((IntegerValue) literalOperand).longValue();
543 } else if (literalOperand.isNaN()) {
544 return Literal.makeLiteral(BooleanValue.get(op == Token.FNE), this);
545 } else if (((NumericValue) literalOperand).isWholeNumber()) {
546 operand = ((NumericValue) literalOperand).longValue();
547 } else if (op == Token.FEQ) {
548 return Literal.makeLiteral(BooleanValue.FALSE, this);
549 } else if (op == Token.FNE) {
550 return Literal.makeLiteral(BooleanValue.TRUE, this);
551 } else if (op == Token.FGT || op == Token.FGE) {
552 operand = ((NumericValue) literalOperand).ceiling().longValue();
553 op = Token.FGE;
554 } else /*if (op == Token.FLT || op == Token.FLE)*/ {
555 operand = ((NumericValue) literalOperand).floor().longValue();
556 op = Token.FLE;
557 }
558 if (operand < 0) {
559 switch (op) {
560 case Token.FEQ:
561 case Token.FLT:
562 case Token.FLE:
563 return Literal.makeLiteral(BooleanValue.FALSE, this);
564 default:
565 return Literal.makeLiteral(BooleanValue.TRUE, this);
566 }
567 }
568 if (operand > Integer.MAX_VALUE) {
569 switch (op) {
570 case Token.FEQ:
571 case Token.FGT:
572 case Token.FGE:
573 return Literal.makeLiteral(BooleanValue.FALSE, this);
574 default:
575 return Literal.makeLiteral(BooleanValue.TRUE, this);
576 }
577 }
578 if (sequence instanceof TailExpression || sequence.isCallOn(Subsequence_2.class)) {
579 // it's probably the result of a previous optimization
580 return null;
581 }
582 switch (op) {
583 case Token.FEQ:
584 case Token.FNE:
585 case Token.FLE:
586 case Token.FLT:
587 // rewrite count(E) op N as count(subsequence(E, 1, N+1)) op N
588 Expression ss = SystemFunction.makeCall("subsequence",
589 getRetainedStaticContext(), sequence,
590 Literal.makeLiteral(Int64Value.PLUS_ONE, this),
591 Literal.makeLiteral(Int64Value.makeIntegerValue(operand + 1), this));
592 Expression ct = SystemFunction.makeCall("count", getRetainedStaticContext(), ss);
593 CompareToIntegerConstant ctic = new CompareToIntegerConstant(ct, op, operand);
594 opt.trace("Rewrite count()~N as:", ctic);
595 ExpressionTool.copyLocationInfo(this, ctic);
596 return ctic;
597 case Token.FGE:
598 case Token.FGT:
599 // rewrite count(x) gt n as exists(x[n+1])
600 // and count(x) ge n as exists(x[n])
601 TailExpression tail = new TailExpression(sequence, (int) (op == Token.FGE ? operand : operand + 1));
602 ExpressionTool.copyLocationInfo(this, tail);
603 Expression result = SystemFunction.makeCall("exists", getRetainedStaticContext(), tail);
604 ExpressionTool.copyLocationInfo(this, result);
605 opt.trace("Rewrite count()>=N as:", result);
606 return result;
607 }
608 }
609 return null;
610 }
611
612
613 /**
614 * Check whether this specific instance of the expression is negatable
615 *
616 * @return true if it is
617 * @param th the type hierarchy
618 */
619
620 public boolean isNegatable(TypeHierarchy th) {
621 // Expression is not negatable if it might involve NaN
622 return isNeverNaN(getLhsExpression(), th) && isNeverNaN(getRhsExpression(), th);
623 }
624
625 private boolean isNeverNaN(Expression exp, TypeHierarchy th) {
626 return th.relationship(exp.getItemType(), BuiltInAtomicType.DOUBLE) == TypeHierarchy.DISJOINT &&
627 th.relationship(exp.getItemType(), BuiltInAtomicType.FLOAT) == TypeHierarchy.DISJOINT;
628 }
629
630 /**
631 * Return the negation of this value comparison: that is, a value comparison that returns true()
632 * if and only if the original returns false(). The result must be the same as not(this) even in the
633 * case where one of the operands is ().
634 *
635 * @return the inverted comparison
636 */
637
638 public Expression negate() {
639 ValueComparison vc = new ValueComparison(getLhsExpression(), Token.negate(operator), getRhsExpression());
640 vc.comparer = comparer;
641 if (resultWhenEmpty == null || resultWhenEmpty == BooleanValue.FALSE) {
642 vc.resultWhenEmpty = BooleanValue.TRUE;
643 } else {
644 vc.resultWhenEmpty = BooleanValue.FALSE;
645 }
646 ExpressionTool.copyLocationInfo(this, vc);
647 return vc;
648 }
649
650
651 /**
652 * Test whether an expression is constant zero
653 *
654 * @param v the value to be tested
655 * @return true if the operand is the constant zero (of any numeric data type)
656 */
657
658 private static boolean isZero(Sequence<?> v) {
659 return v instanceof NumericValue && ((NumericValue) v).compareTo(0) == 0;
660 }
661
662 @Override
663 public boolean equals(Object other) {
664 return other instanceof ValueComparison &&
665 super.equals(other) &&
666 comparer.equals(((ValueComparison) other).comparer);
667 }
668
669 /**
670 * Copy an expression. This makes a deep copy.
671 *
672 * @return the copy of the original expression
673 * @param rebindings variables that need to be re-bound
674 */
675
676 /*@NotNull*/
677 public Expression copy(RebindingMap rebindings) {
678 ValueComparison vc = new ValueComparison(getLhsExpression().copy(rebindings), operator, getRhsExpression().copy(rebindings));
679 ExpressionTool.copyLocationInfo(this, vc);
680 vc.comparer = comparer;
681 vc.resultWhenEmpty = resultWhenEmpty;
682 vc.needsRuntimeCheck = needsRuntimeCheck;
683 return vc;
684 }
685
686 /**
687 * Evaluate the effective boolean value of the expression
688 *
689 * @param context the given context for evaluation
690 * @return a boolean representing the result of the comparison of the two operands
691 */
692
693 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
694 try {
695 AtomicValue v0 = (AtomicValue) getLhsExpression().evaluateItem(context);
696 if (v0 == null) {
697 return resultWhenEmpty == BooleanValue.TRUE; // normally false
698 }
699 AtomicValue v1 = (AtomicValue) getRhsExpression().evaluateItem(context);
700 if (v1 == null) {
701 return resultWhenEmpty == BooleanValue.TRUE; // normally false
702 }
703 return compare(v0, operator, v1, comparer.provideContext(context), needsRuntimeCheck);
704 } catch (XPathException e) {
705 // re-throw the exception with location information added
706 e.maybeSetLocation(getLocation());
707 e.maybeSetContext(context);
708 throw e;
709 }
710 }
711
712 /**
713 * Compare two atomic values, using a specified operator and collation
714 *
715 * @param v0 the first operand
716 * @param op the operator, as defined by constants such as {@link net.sf.saxon.expr.parser.Token#FEQ} or
717 * {@link net.sf.saxon.expr.parser.Token#FLT}
718 * @param v1 the second operand
719 * @param comparer used to compare values. If the comparer is context-sensitive then the context must
720 * already have been bound using comparer.provideContext().
721 * @param checkTypes set to true if it is necessary to check that the types of the arguments are comparable
722 * @return the result of the comparison: -1 for LT, 0 for EQ, +1 for GT
723 * @throws XPathException if the values are not comparable
724 */
725
726 public static boolean compare(AtomicValue v0, int op, AtomicValue v1, AtomicComparer comparer, boolean checkTypes)
727 throws XPathException {
728 if (checkTypes &&
729 !Type.isGuaranteedComparable(v0.getPrimitiveType(), v1.getPrimitiveType(), Token.isOrderedOperator(op))) {
730 XPathException e2 = new XPathException("Cannot compare " + Type.displayTypeName(v0) +
731 " to " + Type.displayTypeName(v1));
732 e2.setErrorCode("XPTY0004");
733 e2.setIsTypeError(true);
734 throw e2;
735 }
736 if (v0.isNaN() || v1.isNaN()) {
737 return op == Token.FNE;
738 }
739 try {
740 switch (op) {
741 case Token.FEQ:
742 return comparer.comparesEqual(v0, v1);
743 case Token.FNE:
744 return !comparer.comparesEqual(v0, v1);
745 case Token.FGT:
746 return comparer.compareAtomicValues(v0, v1) > 0;
747 case Token.FLT:
748 return comparer.compareAtomicValues(v0, v1) < 0;
749 case Token.FGE:
750 return comparer.compareAtomicValues(v0, v1) >= 0;
751 case Token.FLE:
752 return comparer.compareAtomicValues(v0, v1) <= 0;
753 default:
754 throw new UnsupportedOperationException("Unknown operator " + op);
755 }
756 } catch (ComparisonException err) {
757 throw err.getCause();
758 } catch (ClassCastException err) {
759 XPathException e2 = new XPathException("Cannot compare " + Type.displayTypeName(v0) +
760 " to " + Type.displayTypeName(v1));
761 e2.setErrorCode("XPTY0004");
762 e2.setIsTypeError(true);
763 throw e2;
764 }
765 }
766
767 /**
768 * Evaluate the expression in a given context
769 *
770 * @param context the given context for evaluation
771 * @return a BooleanValue representing the result of the numeric comparison of the two operands,
772 * or null representing the empty sequence
773 */
774
775 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
776 try {
777 AtomicValue v0 = (AtomicValue) getLhsExpression().evaluateItem(context);
778 if (v0 == null) {
779 return resultWhenEmpty;
780 }
781 AtomicValue v1 = (AtomicValue) getRhsExpression().evaluateItem(context);
782 if (v1 == null) {
783 return resultWhenEmpty;
784 }
785 return BooleanValue.get(compare(v0, operator, v1, comparer.provideContext(context), needsRuntimeCheck));
786 } catch (XPathException e) {
787 // re-throw the exception with location information added
788 e.maybeSetLocation(getLocation());
789 e.maybeSetContext(context);
790 throw e;
791 }
792 }
793
794 /**
795 * Determine the data type of the expression
796 *
797 * @return Type.BOOLEAN
798 */
799
800 /*@NotNull*/
801 public ItemType getItemType() {
802 return BuiltInAtomicType.BOOLEAN;
803 }
804
805 /**
806 * Get the static type of the expression as a UType, following precisely the type
807 * inference rules defined in the XSLT 3.0 specification.
808 *
809 * @return the static item type of the expression according to the XSLT 3.0 defined rules
810 * @param contextItemType the static type of the context item
811 */
812 @Override
813 public UType getStaticUType(UType contextItemType) {
814 return UType.BOOLEAN;
815 }
816
817 /**
818 * Determine the static cardinality.
819 */
820
821 public int computeCardinality() {
822 if (resultWhenEmpty != null) {
823 return StaticProperty.EXACTLY_ONE;
824 } else {
825 return super.computeCardinality();
826 }
827 }
828
829 @Override
830 public String tag() {
831 return "vc";
832 }
833
834 @Override
835 protected void explainExtraAttributes(ExpressionPresenter out) {
836 if (resultWhenEmpty != null) {
837 out.emitAttribute("onEmpty", resultWhenEmpty.getBooleanValue() ? "1" : "0");
838 }
839 out.emitAttribute("comp", comparer.save());
840 }
841
842
843
844 }
845