Debian Codegraph @

net/sf/saxon/expr/EquivalenceComparison.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.lib.StringCollator;
15 import net.sf.saxon.om.GroundedValue;
16 import net.sf.saxon.trace.ExpressionPresenter;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.type.*;
19 import net.sf.saxon.value.AtomicValue;
20 import net.sf.saxon.value.BooleanValue;
21 import net.sf.saxon.value.SequenceType;
22
23
24 /**
25 * Class to handle equivalence comparisons of singletons. This only handles equality comparison.
26 * It follows the rules used for grouping and for XQuery 3.0 switch expressions:
27 * - each operand must be zero or one atomic values
28 * - untypedAtomic is treated as string
29 * - non-comparable values are not equal (no type errors)
30 * - two empty sequences are equal to each other
31 * - two NaN values are equal to each other
32 */
33
34 public class EquivalenceComparison extends BinaryExpression implements ComparisonExpression {
35
36 private AtomicComparer comparer;
37 private boolean knownToBeComparable = false;
38
39 /**
40 * Create a singleton comparison - that is, a comparison between two singleton (0:1) sequences
41 * using the general comparison semantics
42 *
43 * @param p1 the first operand
44 * @param operator the operator
45 * @param p2 the second operand
46 */
47
48 public EquivalenceComparison(Expression p1, int operator, Expression p2) {
49 super(p1, operator, p2);
50 }
51
52 /**
53 * Type-check the expression. Default implementation for binary operators that accept
54 * any kind of operand
55 */
56
57 /*@NotNull*/
58 @Override
59 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
60 StaticContext env = visitor.getStaticContext();
61 String defaultCollationName = env.getDefaultCollationName();
62 final Configuration config = visitor.getConfiguration();
63 StringCollator collation = config.getCollation(defaultCollationName);
64 if (collation == null) {
65 collation = CodepointCollator.getInstance();
66 }
67 comparer = new EquivalenceComparer(collation, config.getConversionContext());
68
69 Expression oldOp0 = getLhsExpression();
70 Expression oldOp1 = getRhsExpression();
71
72 getLhs().typeCheck(visitor, contextInfo);
73 getRhs().typeCheck(visitor, contextInfo);
74
75 // Neither operand needs to be sorted
76
77 setLhsExpression(getLhsExpression().unordered(false, false));
78 setRhsExpression(getRhsExpression().unordered(false, false));
79
80 SequenceType atomicType = SequenceType.OPTIONAL_ATOMIC;
81 TypeChecker tc = config.getTypeChecker(false);
82
83 RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, "eq", 0);
84 setLhsExpression(tc.staticTypeCheck(getLhsExpression(), atomicType, role0, visitor));
85
86 RoleDiagnostic role1 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, "eq", 1);
87 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), atomicType, role1, visitor));
88
89 if (getLhsExpression() != oldOp0) {
90 adoptChildExpression(getLhsExpression());
91 }
92
93 if (getRhsExpression() != oldOp1) {
94 adoptChildExpression(getRhsExpression());
95 }
96
97 ItemType t0 = getLhsExpression().getItemType(); // this is always an atomic type or empty-sequence()
98 ItemType t1 = getRhsExpression().getItemType(); // this is always an atomic type or empty-sequence()
99
100 if (t0 instanceof ErrorType) {
101 t0 = BuiltInAtomicType.ANY_ATOMIC;
102 }
103 if (t1 instanceof ErrorType) {
104 t1 = BuiltInAtomicType.ANY_ATOMIC;
105 }
106
107 if (((AtomicType) t0).isExternalType() || ((AtomicType) t1).isExternalType()) {
108 XPathException err = new XPathException("Cannot perform comparisons involving external objects");
109 err.setIsTypeError(true);
110 err.setErrorCode("XPTY0004");
111 err.setLocation(getLocation());
112 throw err;
113 }
114
115 BuiltInAtomicType pt0 = (BuiltInAtomicType) t0.getPrimitiveItemType();
116 BuiltInAtomicType pt1 = (BuiltInAtomicType) t1.getPrimitiveItemType();
117
118 if (t0.equals(BuiltInAtomicType.ANY_ATOMIC) || t0.equals(BuiltInAtomicType.UNTYPED_ATOMIC) ||
119 t1.equals(BuiltInAtomicType.ANY_ATOMIC) || t1.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
120 // then no static type checking is possible
121 } else {
122 if (Type.isGuaranteedComparable(pt0, pt1, false)) {
123 knownToBeComparable = true;
124 } else if (!Type.isPossiblyComparable(pt0, pt1, false)) {
125 env.issueWarning("Cannot compare " + t0.toString() + " to " + t1.toString(), getLocation());
126 // This is not an error in a switch statement, but it means the branch will never be chosen
127 }
128 }
129
130 try {
131 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
132 GroundedValue v = evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()).materialize();
133 return Literal.makeLiteral(v, this);
134 }
135 } catch (XPathException err) {
136 // if early evaluation fails, suppress the error: the value might
137 // not be needed at run-time
138 }
139
140 // comparer = GenericAtomicComparer.makeAtomicComparer(
141 // pt0, pt1, collation, getConfiguration().getConversionContext());
142
143 return this;
144 }
145
146
147 public AtomicComparer getAtomicComparer() {
148 return comparer;
149 }
150
151 public int getSingletonOperator() {
152 return operator;
153 }
154
155 /**
156 * Determine whether untyped atomic values should be converted to the type of the other operand
157 *
158 * @return true if untyped values should be converted to the type of the other operand, false if they
159 * should be converted to strings.
160 */
161
162 public boolean convertsUntypedToOther() {
163 return false;
164 }
165
166 /**
167 * Determine the static cardinality. Returns [1..1]
168 */
169
170 public int computeCardinality() {
171 return StaticProperty.EXACTLY_ONE;
172 }
173
174 /**
175 * Determine the data type of the expression
176 *
177 * @return Type.BOOLEAN
178 */
179
180 /*@NotNull*/
181 public ItemType getItemType() {
182 return BuiltInAtomicType.BOOLEAN;
183 }
184
185 public boolean isKnownToBeComparable() {
186 return knownToBeComparable;
187 }
188
189 public AtomicComparer getComparer() {
190 return comparer;
191 }
192
193
194 /**
195 * Copy an expression. This makes a deep copy.
196 *
197 * @return the copy of the original expression
198 * @param rebindings
199 */
200
201 /*@NotNull*/
202 public Expression copy(RebindingMap rebindings) {
203 EquivalenceComparison sc = new EquivalenceComparison(getLhsExpression().copy(rebindings), operator, getRhsExpression().copy(rebindings));
204 ExpressionTool.copyLocationInfo(this, sc);
205 sc.comparer = comparer;
206 sc.knownToBeComparable = knownToBeComparable;
207 return sc;
208 }
209
210 /**
211 * Evaluate the expression in a given context
212 *
213 * @param context the given context for evaluation
214 * @return a BooleanValue representing the result of the numeric comparison of the two operands
215 */
216
217 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
218 return BooleanValue.get(effectiveBooleanValue(context));
219 }
220
221 /**
222 * Evaluate the expression in a boolean context
223 *
224 * @param context the given context for evaluation
225 * @return a boolean representing the result of the numeric comparison of the two operands
226 */
227
228 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
229 AtomicValue v0 = (AtomicValue) getLhsExpression().evaluateItem(context);
230 AtomicValue v1 = (AtomicValue) getRhsExpression().evaluateItem(context);
231
232 if (v0 == null || v1 == null) {
233 return (v0 == v1);
234 }
235
236 AtomicComparer comp2 = comparer.provideContext(context);
237 return (knownToBeComparable || Type.isGuaranteedComparable(v0.getPrimitiveType(), v1.getPrimitiveType(), false))
238 && comp2.comparesEqual(v0, v1);
239
240 }
241
242 /**
243 * Get a name identifying the kind of expression, in terms meaningful to a user.
244 *
245 * @return a name identifying the kind of expression, in terms meaningful to a user.
246 * The name will always be in the form of a lexical XML QName, and should match the name used
247 * in export() output displaying the expression.
248 */
249 @Override
250 public String getExpressionName() {
251 return "equivalent";
252 }
253
254 protected void explainExtraAttributes(ExpressionPresenter out) {
255 out.emitAttribute("cardinality", "singleton");
256 }
257 }
258
259 // Copyright (c) 2010 Saxonica Limited.