Debian Codegraph @

net/sf/saxon/expr/compat/GeneralComparison10.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.compat;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.expr.sort.AtomicComparer;
14 import net.sf.saxon.expr.sort.CodepointCollator;
15 import net.sf.saxon.expr.sort.GenericAtomicComparer;
16 import net.sf.saxon.functions.Number_1;
17 import net.sf.saxon.lib.ConversionRules;
18 import net.sf.saxon.lib.StringCollator;
19 import net.sf.saxon.om.Item;
20 import net.sf.saxon.om.Sequence;
21 import net.sf.saxon.om.SequenceIterator;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.tree.iter.EmptyIterator;
25 import net.sf.saxon.tree.iter.PrependSequenceIterator;
26 import net.sf.saxon.type.*;
27 import net.sf.saxon.value.AtomicValue;
28 import net.sf.saxon.value.BooleanValue;
29 import net.sf.saxon.value.DoubleValue;
30 import net.sf.saxon.value.StringValue;
31
32 import java.util.ArrayList;
33 import java.util.List;
34
35 /**
36 * GeneralComparison10: a boolean expression that compares two expressions
37 * for equals, not-equals, greater-than or less-than. This implements the operators
38 * =, !=, <, >, etc. This version of the class implements general comparisons
39 * in XPath 1.0 backwards compatibility mode.
40 */
41
42 public class GeneralComparison10 extends BinaryExpression implements Callable {
43
44 protected int singletonOperator;
45 protected AtomicComparer comparer;
46 private boolean atomize0 = true;
47 private boolean atomize1 = true;
48 private boolean maybeBoolean0 = true;
49 private boolean maybeBoolean1 = true;
50
51 /**
52 * Create a general comparison 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 GeneralComparison10(Expression p0, int op, Expression p1) {
60 super(p0, op, p1);
61 singletonOperator = GeneralComparison.getCorrespondingSingletonOperator(op);
62 }
63
64 /**
65 * Determine the static cardinality. Returns [1..1]
66 */
67
68 public int computeCardinality() {
69 return StaticProperty.EXACTLY_ONE;
70 }
71
72 /**
73 * Type-check the expression
74 *
75 * @return the checked expression
76 */
77
78 /*@NotNull*/
79 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
80
81 getLhs().typeCheck(visitor, contextInfo);
82 getRhs().typeCheck(visitor, contextInfo);
83
84 StaticContext env = visitor.getStaticContext();
85 StringCollator comp = visitor.getConfiguration().getCollation(env.getDefaultCollationName());
86 if (comp == null) {
87 comp = CodepointCollator.getInstance();
88 }
89
90 XPathContext context = env.makeEarlyEvaluationContext();
91 comparer = new GenericAtomicComparer(comp, context);
92
93 // evaluate the expression now if both arguments are constant
94
95 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
96 return Literal.makeLiteral(evaluateItem(context), this);
97 }
98
99 return this;
100 }
101
102 public void setAtomicComparer(AtomicComparer comparer) {
103 this.comparer = comparer;
104 }
105
106 /**
107 * Optimize the expression
108 *
109 * @return the checked expression
110 */
111
112 /*@NotNull*/
113 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
114
115 Configuration config = visitor.getConfiguration();
116 StaticContext env = visitor.getStaticContext();
117
118 getLhs().optimize(visitor, contextInfo);
119 getRhs().optimize(visitor, contextInfo);
120
121 // Neither operand needs to be sorted
122
123 setLhsExpression(getLhsExpression().unordered(false, false));
124 setRhsExpression(getRhsExpression().unordered(false, false));
125
126 // evaluate the expression now if both arguments are constant
127
128 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
129 return Literal.makeLiteral(
130 evaluateItem(env.makeEarlyEvaluationContext()), this);
131 }
132
133 final TypeHierarchy th = config.getTypeHierarchy();
134 ItemType type0 = getLhsExpression().getItemType();
135 ItemType type1 = getRhsExpression().getItemType();
136
137 if (type0.isPlainType()) {
138 atomize0 = false;
139 }
140 if (type1.isPlainType()) {
141 atomize1 = false;
142 }
143
144 if (th.relationship(type0, BuiltInAtomicType.BOOLEAN) == TypeHierarchy.DISJOINT) {
145 maybeBoolean0 = false;
146 }
147 if (th.relationship(type1, BuiltInAtomicType.BOOLEAN) == TypeHierarchy.DISJOINT) {
148 maybeBoolean1 = false;
149 }
150
151 if (!maybeBoolean0 && !maybeBoolean1) {
152 // First atomize the operands where necessary. We didn't do this earlier because of the
153 // special 1.0 (node-set=boolean) semantics, but if we don't have a boolean we can do it now.
154 if (!(type0 instanceof AtomicType)) {
155 setLhsExpression(Atomizer.makeAtomizer(getLhsExpression(), null).simplify());
156 type0 = getLhsExpression().getItemType();
157 }
158 if (!(type1 instanceof AtomicType)) {
159 setRhsExpression(Atomizer.makeAtomizer(getRhsExpression(), null).simplify());
160 type1 = getRhsExpression().getItemType();
161 }
162 // Now consider numeric operands
163 int n0 = th.relationship(type0, NumericType.getInstance());
164 int n1 = th.relationship(type1, NumericType.getInstance());
165 boolean maybeNumeric0 = n0 != TypeHierarchy.DISJOINT;
166 boolean maybeNumeric1 = n1 != TypeHierarchy.DISJOINT;
167 boolean numeric0 = n0 == TypeHierarchy.SUBSUMED_BY || n0 == TypeHierarchy.SAME_TYPE;
168 boolean numeric1 = n1 == TypeHierarchy.SUBSUMED_BY || n1 == TypeHierarchy.SAME_TYPE;
169 // Use the 2.0 path if we don't have to deal with the possibility of boolean values,
170 // or the complications of converting values to numbers
171
172 if (operator == Token.EQUALS || operator == Token.NE) {
173 if ((!maybeNumeric0 && !maybeNumeric1) || (numeric0 && numeric1)) {
174 GeneralComparison gc = new GeneralComparison20(getLhsExpression(), operator, getRhsExpression());
175 gc.setRetainedStaticContext(getRetainedStaticContext());
176 gc.setAtomicComparer(comparer);
177 Expression binExp = visitor.obtainOptimizer()
178 .optimizeGeneralComparison(visitor, gc, false, contextInfo);
179 ExpressionTool.copyLocationInfo(this, binExp);
180 return binExp.typeCheck(visitor, contextInfo).optimize(visitor, contextInfo);
181 }
182 } else if (numeric0 && numeric1) {
183 GeneralComparison gc = new GeneralComparison20(getLhsExpression(), operator, getRhsExpression());
184 gc.setRetainedStaticContext(getRetainedStaticContext());
185 Expression binExp = visitor.obtainOptimizer()
186 .optimizeGeneralComparison(visitor, gc, false, contextInfo);
187 ExpressionTool.copyLocationInfo(this, binExp);
188 return binExp.typeCheck(visitor, contextInfo).optimize(visitor, contextInfo);
189 }
190 }
191
192 return this;
193 }
194
195
196 /**
197 * Evaluate the expression in a given context
198 *
199 * @param context the given context for evaluation
200 * @return a BooleanValue representing the result of the numeric comparison of the two operands
201 */
202
203 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
204 return BooleanValue.get(effectiveBooleanValue(context));
205 }
206
207 /**
208 * Evaluate the expression: interface for use by compiled bytecode
209 *
210 * @param context the dynamic evaluation context
211 * @param arguments the values of the arguments, supplied as SequenceIterators
212 * @return the result of the evaluation, in the form of a SequenceIterator
213 * @throws XPathException if a dynamic error occurs during the evaluation of the expression
214 */
215
216 public BooleanValue call(XPathContext context, Sequence[] arguments) throws XPathException {
217 return BooleanValue.get(effectiveBooleanValue(arguments[0].iterate(), arguments[1].iterate(), context));
218 }
219
220 /**
221 * Evaluate the expression giving a boolean result
222 *
223 * @param context the given context for evaluation
224 * @return a boolean representing the result of the comparison of the two operands
225 */
226
227 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
228 return effectiveBooleanValue(getLhsExpression().iterate(context), getRhsExpression().iterate(context), context);
229 }
230
231 /**
232 * Evaluate the expression giving a boolean result
233 *
234 * @param iter0 iterator over the value of the first argument
235 * @param iter1 iterator over the value of the second argument
236 * @param context the given context for evaluation
237 * @return a boolean representing the result of the comparison of the two operands
238 * @throws XPathException if an error occurs evaluating either operand or if the results are not comparable
239 */
240
241 private boolean effectiveBooleanValue(SequenceIterator iter0, SequenceIterator iter1, XPathContext context)
242 throws XPathException {
243
244 // If the first operand is a singleton boolean,
245 // compare it with the effective boolean value of the other operand
246
247 //boolean iter0used = false;
248 boolean iter1used = false;
249
250 if (maybeBoolean0) {
251 Item i01 = iter0.next();
252 Item i02 = i01 == null ? null : iter0.next();
253 if (i01 instanceof BooleanValue && i02 == null) {
254 iter0.close();
255 boolean b = ExpressionTool.effectiveBooleanValue(iter1);
256 return compare((BooleanValue) i01, singletonOperator, BooleanValue.get(b), comparer, context);
257 }
258 if (i01 == null && !maybeBoolean1) {
259 iter0.close();
260 return false;
261 }
262 // Reconstitute the original iterator
263 if (i02 != null) {
264 iter0 = new PrependSequenceIterator(i02, iter0);
265 }
266 if (i01 != null) {
267 iter0 = new PrependSequenceIterator(i01, iter0);
268 }
269 }
270
271 // If the second operand is a singleton boolean,
272 // compare it with the effective boolean value of the other operand
273
274 if (maybeBoolean1) {
275 Item i11 = iter1.next();
276 Item i12 = i11 == null ? null : iter1.next();
277 if (i11 instanceof BooleanValue && i12 == null) {
278 iter1.close();
279 boolean b = ExpressionTool.effectiveBooleanValue(iter0);
280 return compare(BooleanValue.get(b), singletonOperator, (BooleanValue) i11, comparer, context);
281 }
282 if (i11 == null && !maybeBoolean0) {
283 iter1.close();
284 return false;
285 }
286 // Reconstitute the original iterator
287 if (i12 != null) {
288 iter1 = new PrependSequenceIterator(i12, iter1);
289 }
290 if (i11 != null) {
291 iter1 = new PrependSequenceIterator(i11, iter1);
292 }
293 }
294
295 // Atomize both operands where necessary
296
297 if (atomize0) {
298 iter0 = Atomizer.getAtomizingIterator(iter0, false);
299 }
300
301 if (atomize1) {
302 iter1 = Atomizer.getAtomizingIterator(iter1, false);
303 }
304
305 // If either iterator is known to be empty, quit now
306
307 if (iter0 instanceof EmptyIterator || iter1 instanceof EmptyIterator) {
308 return false;
309 }
310
311 // If the operator is one of <, >, <=, >=, then convert both operands to sequences of xs:double
312 // using the number() function
313
314 if (operator == Token.LT || operator == Token.LE || operator == Token.GT || operator == Token.GE) {
315 final Configuration config = context.getConfiguration();
316 ItemMappingFunction map = new ItemMappingFunction() {
317 public DoubleValue mapItem(Item item) throws XPathException {
318 return Number_1.convert((AtomicValue)item, config);
319 }
320 };
321 iter0 = new ItemMappingIterator(iter0, map, true);
322 iter1 = new ItemMappingIterator(iter1, map, true);
323 }
324
325 // Compare all pairs of atomic values in the two atomized sequences
326
327 List<AtomicValue> seq1 = null;
328 AtomicValue item0;
329 while ((item0 = (AtomicValue) iter0.next()) != null) {
330 if (iter1 != null) {
331 while (true) {
332 AtomicValue item1 = (AtomicValue) iter1.next();
333 if (item1 == null) {
334 iter1 = null;
335 if (seq1 == null) {
336 // second operand is empty
337 return false;
338 }
339 break;
340 }
341 try {
342 if (compare(item0, singletonOperator, item1, comparer, context)) {
343 return true;
344 }
345 if (seq1 == null) {
346 seq1 = new ArrayList<AtomicValue>(40);
347 }
348 seq1.add(item1);
349 } catch (XPathException e) {
350 // re-throw the exception with location information added
351 e.maybeSetLocation(getLocation());
352 e.maybeSetContext(context);
353 throw e;
354 }
355 }
356 } else {
357 for (AtomicValue item1 : seq1) {
358 if (compare(item0, singletonOperator, item1, comparer, context)) {
359 return true;
360 }
361 }
362 }
363 }
364 return false;
365 }
366
367
368 /**
369 * Copy an expression. This makes a deep copy.
370 *
371 * @return the copy of the original expression
372 * @param rebindings
373 */
374
375 /*@NotNull*/
376 public Expression copy(RebindingMap rebindings) {
377 GeneralComparison10 gc = new GeneralComparison10(getLhsExpression().copy(rebindings), operator, getRhsExpression().copy(rebindings));
378 ExpressionTool.copyLocationInfo(this, gc);
379 gc.setRetainedStaticContext(getRetainedStaticContext());
380 gc.comparer = comparer;
381 gc.atomize0 = atomize0;
382 gc.atomize1 = atomize1;
383 gc.maybeBoolean0 = maybeBoolean0;
384 gc.maybeBoolean1 = maybeBoolean1;
385 return gc;
386 }
387
388 /**
389 * Compare two atomic values
390 *
391 * @param a0 the first value to be compared
392 * @param operator the comparison operator
393 * @param a1 the second value to be compared
394 * @param comparer the comparer to be used (perhaps including a collation)
395 * @param context the XPath dynamic context
396 * @return the result of the comparison
397 * @throws XPathException if the values are not comparable
398 */
399
400 private static boolean compare(AtomicValue a0,
401 int operator,
402 AtomicValue a1,
403 AtomicComparer comparer,
404 XPathContext context) throws XPathException {
405
406 comparer = comparer.provideContext(context);
407 ConversionRules rules = context.getConfiguration().getConversionRules();
408
409 BuiltInAtomicType t0 = a0.getPrimitiveType();
410 BuiltInAtomicType t1 = a1.getPrimitiveType();
411
412 // If either operand is a number, convert both operands to xs:double using
413 // the rules of the number() function, and compare them
414
415 if (t0.isPrimitiveNumeric() || t1.isPrimitiveNumeric()) {
416 DoubleValue v0 = Number_1.convert(a0, context.getConfiguration());
417 DoubleValue v1 = Number_1.convert(a1, context.getConfiguration());
418 return ValueComparison.compare(v0, operator, v1, comparer, false);
419 }
420
421 // If either operand is a string, or if both are untyped atomic, convert
422 // both operands to strings and compare them
423
424 if (t0.equals(BuiltInAtomicType.STRING) || t1.equals(BuiltInAtomicType.STRING) ||
425 (t0.equals(BuiltInAtomicType.UNTYPED_ATOMIC) && t1.equals(BuiltInAtomicType.UNTYPED_ATOMIC))) {
426 StringValue s0 = StringValue.makeStringValue(a0.getStringValueCS());
427 StringValue s1 = StringValue.makeStringValue(a1.getStringValueCS());
428 return ValueComparison.compare(s0, operator, s1, comparer, false);
429 }
430
431 // If either operand is untyped atomic,
432 // convert it to the type of the other operand, and compare
433
434 if (t0.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
435 a0 = t1.getStringConverter(rules).convert((StringValue)a0).asAtomic();
436 }
437
438 if (t1.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
439 a1 = t0.getStringConverter(rules).convert((StringValue)a1).asAtomic();
440 }
441
442 return ValueComparison.compare(a0, operator, a1, comparer, false);
443 }
444
445 /**
446 * Determine the data type of the expression
447 *
448 * @return Type.BOOLEAN
449 */
450
451 /*@NotNull*/
452 public ItemType getItemType() {
453 return BuiltInAtomicType.BOOLEAN;
454 }
455
456
457 protected void explainExtraAttributes(ExpressionPresenter out) {
458 out.emitAttribute("cardinality", "many-to-many (1.0)");
459 out.emitAttribute("comp", comparer.save());
460 }
461
462 @Override
463 public String tag() {
464 return "gc10";
465 }
466 }
467