Debian Codegraph @

net/sf/saxon/expr/BinaryExpression.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.expr.parser.*;
11 import net.sf.saxon.om.GroundedValue;
12 import net.sf.saxon.om.Item;
13 import net.sf.saxon.trace.ExpressionPresenter;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.jiter.PairIterator;
16 import net.sf.saxon.type.AtomicType;
17 import net.sf.saxon.value.Cardinality;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 /**
23 * Binary Expression: a numeric or boolean expression consisting of the
24 * two operands and an operator
25 */
26
27 public abstract class BinaryExpression extends Expression {
28
29 private Operand lhs;
30 private Operand rhs;
31 protected int operator; // represented by the token number from class Tokenizer
32
33 /**
34 * Create a binary expression identifying the two operands and the operator
35 *
36 * @param p0 the left-hand operand
37 * @param op the operator, as a token returned by the Tokenizer (e.g. Token.AND)
38 * @param p1 the right-hand operand
39 */
40
41 public BinaryExpression(Expression p0, int op, Expression p1) {
42 operator = op;
43 // p0.verifyParentPointers();
44 // p1.verifyParentPointers();
45 lhs = new Operand(this, p0, getOperandRole(0));
46 rhs = new Operand(this, p1, getOperandRole(1));
47 adoptChildExpression(p0);
48 adoptChildExpression(p1);
49 }
50
51 @Override
52 final public Iterable<Operand> operands() {
53 return () -> new PairIterator<>(lhs, rhs);
54 }
55
56
57 /**
58 * Get the operand role
59 * @param arg which argument: 0 for the lhs, 1 for the rhs
60 * @return the operand role
61 */
62
63 protected OperandRole getOperandRole(int arg) {
64 return OperandRole.SINGLE_ATOMIC;
65 }
66
67 /**
68 * Get the left-hand operand
69 * @return the left-hand operand
70 */
71
72 public Operand getLhs() {
73 return lhs;
74 }
75
76 /**
77 * Get the left-hand operand expression
78 * @return the left-hand operand child expression
79 */
80
81 public final Expression getLhsExpression() {
82 return lhs.getChildExpression();
83 }
84
85 /**
86 * Set the left-hand operand expression
87 * @param child the left-hand operand expression
88 */
89
90 public void setLhsExpression(Expression child) {
91 lhs.setChildExpression(child);
92 }
93
94 /**
95 * Get the right-hand operand
96 * @return the right-hand operand
97 */
98
99 public Operand getRhs() {
100 return rhs;
101 }
102
103 /**
104 * Get the right-hand operand expression
105 * @return the right-hand operand expression
106 */
107
108 public final Expression getRhsExpression() {
109 return rhs.getChildExpression();
110 }
111
112 /**
113 * Set the right-hand operand expression
114 * @param child the right-hand operand expression
115 */
116
117 public void setRhsExpression(Expression child) {
118 rhs.setChildExpression(child);
119 }
120
121 /**
122 * Type-check the expression. Default implementation for binary operators that accept
123 * any kind of operand
124 */
125
126 /*@NotNull*/
127 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
128 resetLocalStaticProperties();
129 lhs.typeCheck(visitor, contextInfo);
130 rhs.typeCheck(visitor, contextInfo);
131
132 // if both operands are known, pre-evaluate the expression
133 try {
134 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
135 GroundedValue<?> v = evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()).materialize();
136 return Literal.makeLiteral(v, this);
137 }
138 } catch (XPathException err) {
139 // if early evaluation fails, suppress the error: the value might
140 // not be needed at run-time
141 }
142 return this;
143 }
144
145 /**
146 * Perform optimisation of an expression and its subexpressions.
147 * <p>This method is called after all references to functions and variables have been resolved
148 * to the declaration of the function or variable, and after all type checking has been done.</p>
149 *
150 * @param visitor an expression visitor
151 * @param contextItemType the static type of "." at the point where this expression is invoked.
152 * The parameter is set to null if it is known statically that the context item will be undefined.
153 * If the type of the context item is not known statically, the argument is set to
154 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
155 * @return the original expression, rewritten if appropriate to optimize execution
156 * @throws XPathException if an error is discovered during this phase
157 * (typically a type error)
158 */
159
160 /*@NotNull*/
161 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
162 lhs.optimize(visitor, contextItemType);
163 rhs.optimize(visitor, contextItemType);
164
165 // if both operands are known, pre-evaluate the expression
166 try {
167 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
168 Item<?> item = evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext());
169 if (item != null) {
170 GroundedValue<?> v = item.materialize();
171 return Literal.makeLiteral(v, this);
172 }
173 }
174 } catch (XPathException err) {
175 // if early evaluation fails, suppress the error: the value might
176 // not be needed at run-time
177 }
178 return this;
179 }
180
181 /**
182 * Mark an expression as being "flattened". This is a collective term that includes extracting the
183 * string value or typed value, or operations such as simple value construction that concatenate text
184 * nodes before atomizing. The implication of all of these is that although the expression might
185 * return nodes, the identity of the nodes has no significance. This is called during type checking
186 * of the parent expression.
187 *
188 * @param flattened set to true if the result of the expression is atomized or otherwise turned into
189 * an atomic value
190 */
191
192 public void setFlattened(boolean flattened) {
193 getLhsExpression().setFlattened(flattened);
194 getRhsExpression().setFlattened(flattened);
195 }
196
197 /**
198 * Get the operator
199 *
200 * @return the operator, for example {@link Token#PLUS}
201 */
202
203 public int getOperator() {
204 return operator;
205 }
206
207 /**
208 * Determine the static cardinality. Default implementation returns [0..1] if either operand
209 * can be empty, or [1..1] otherwise, provided that the arguments are of atomic type. This
210 * caveat is necessary because the method can be called before type-checking, and a node
211 * or array with cardinality [1..n] might be atomized to an empty sequence.
212 */
213
214 public int computeCardinality() {
215 Expression lhs = getLhsExpression();
216 Expression rhs = getRhsExpression();
217 if (!Cardinality.allowsZero(lhs.getCardinality()) &&
218 lhs.getItemType() instanceof AtomicType &&
219 !Cardinality.allowsZero(rhs.getCardinality()) &&
220 rhs.getItemType() instanceof AtomicType) {
221 return StaticProperty.EXACTLY_ONE;
222 } else {
223 return StaticProperty.ALLOWS_ZERO_OR_ONE;
224 }
225 }
226
227 /**
228 * Determine the special properties of this expression
229 *
230 * @return {@link StaticProperty#NO_NODES_NEWLY_CREATED}. This is overridden
231 * for some subclasses.
232 */
233
234 public int computeSpecialProperties() {
235 int p = super.computeSpecialProperties();
236 return p | StaticProperty.NO_NODES_NEWLY_CREATED;
237 }
238
239 /**
240 * Determine whether a binary operator is commutative, that is, A op B = B op A.
241 *
242 * @param operator the operator, for example {@link Token#PLUS}
243 * @return true if the operator is commutative
244 */
245
246 protected static boolean isCommutative(int operator) {
247 return operator == Token.AND ||
248 operator == Token.OR ||
249 operator == Token.UNION ||
250 operator == Token.INTERSECT ||
251 operator == Token.PLUS ||
252 operator == Token.MULT ||
253 operator == Token.EQUALS ||
254 operator == Token.FEQ ||
255 operator == Token.NE ||
256 operator == Token.FNE;
257 }
258
259 /**
260 * Determine whether an operator is associative, that is, ((a^b)^c) = (a^(b^c))
261 *
262 * @param operator the operator, for example {@link Token#PLUS}
263 * @return true if the operator is associative
264 */
265
266 protected static boolean isAssociative(int operator) {
267 return operator == Token.AND ||
268 operator == Token.OR ||
269 operator == Token.UNION ||
270 operator == Token.INTERSECT ||
271 operator == Token.PLUS ||
272 operator == Token.MULT;
273 }
274
275 /**
276 * Test if one operator is the inverse of another, so that (A op1 B) is
277 * equivalent to (B op2 A). Commutative operators are the inverse of themselves
278 * and are therefore not listed here.
279 *
280 * @param op1 the first operator
281 * @param op2 the second operator
282 * @return true if the operators are the inverse of each other
283 */
284 protected static boolean isInverse(int op1, int op2) {
285 return op1 != op2 && op1 == Token.inverse(op2);
286 }
287
288 /**
289 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
290 * This method indicates which of these methods is provided directly. The other methods will always be available
291 * indirectly, using an implementation that relies on one of the other methods.
292 *
293 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
294 * {@link #PROCESS_METHOD}
295 */
296 @Override
297 public int getImplementationMethod() {
298 return EVALUATE_METHOD | ITERATE_METHOD;
299 }
300
301 /**
302 * Is this expression the same as another expression?
303 */
304
305 public boolean equals(Object other) {
306 if (other instanceof BinaryExpression && hasCompatibleStaticContext((Expression)other)) {
307 BinaryExpression b = (BinaryExpression) other;
308 Expression lhs1 = getLhsExpression();
309 Expression rhs1 = getRhsExpression();
310 Expression lhs2 = b.getLhsExpression();
311 Expression rhs2 = b.getRhsExpression();
312 if (operator == b.operator) {
313 if (lhs1.isEqual(lhs2) && rhs1.isEqual(rhs2)) {
314 return true;
315 }
316 if (isCommutative(operator) && lhs1.isEqual(rhs2) && rhs1.isEqual(lhs2)) {
317 return true;
318 }
319 if (isAssociative(operator) &&
320 pairwiseEqual(flattenExpression(new ArrayList<>(4)),
321 b.flattenExpression(new ArrayList<>(4)))) {
322 return true;
323 }
324 }
325 return isInverse(operator, b.operator) && lhs1.isEqual(rhs2) && rhs1.isEqual(lhs2);
326 }
327 return false;
328 }
329
330 /**
331 * Flatten an expression with respect to an associative operator: for example
332 * the expression (a+b) + (c+d) becomes list(a,b,c,d), with the list in canonical
333 * order (sorted by hashCode)
334 *
335 * @param list a list provided by the caller to contain the result
336 * @return the list of expressions
337 */
338
339 private List<Expression> flattenExpression(List<Expression> list) {
340 if (getLhsExpression() instanceof BinaryExpression &&
341 ((BinaryExpression) getLhsExpression()).operator == operator) {
342 ((BinaryExpression) getLhsExpression()).flattenExpression(list);
343 } else {
344 int h = getLhsExpression().hashCode();
345 list.add(getLhsExpression());
346 int i = list.size() - 1;
347 while (i > 0 && h > list.get(i - 1).hashCode()) {
348 list.set(i, list.get(i - 1));
349 list.set(i - 1, getLhsExpression());
350 i--;
351 }
352 }
353 if (getRhsExpression() instanceof BinaryExpression &&
354 ((BinaryExpression) getRhsExpression()).operator == operator) {
355 ((BinaryExpression) getRhsExpression()).flattenExpression(list);
356 } else {
357 int h = getRhsExpression().hashCode();
358 list.add(getRhsExpression());
359 int i = list.size() - 1;
360 while (i > 0 && h > list.get(i - 1).hashCode()) {
361 list.set(i, list.get(i - 1));
362 list.set(i - 1, getRhsExpression());
363 i--;
364 }
365 }
366 return list;
367 }
368
369 /**
370 * Compare whether two lists of expressions are pairwise equal
371 *
372 * @param a the first list of expressions
373 * @param b the second list of expressions
374 * @return true if the two lists are equal
375 */
376
377 private boolean pairwiseEqual(List a, List b) {
378 if (a.size() != b.size()) {
379 return false;
380 }
381 for (int i = 0; i < a.size(); i++) {
382 if (!a.get(i).equals(b.get(i))) {
383 return false;
384 }
385 }
386 return true;
387 }
388
389 /**
390 * Get a hashCode for comparing two expressions. Note that this hashcode gives the same
391 * result for (A op B) and for (B op A), whether or not the operator is commutative.
392 */
393
394 public int computeHashCode() {
395 // Ensure that an operator and its inverse get the same hash code,
396 // so that (A lt B) has the same hash code as (B gt A)
397 int op = Math.min(operator, Token.inverse(operator));
398 return ("BinaryExpression " + op).hashCode()
399 ^ getLhsExpression().hashCode()
400 ^ getRhsExpression().hashCode();
401 }
402
403 /**
404 * Represent the expression as a string. The resulting string will be a valid XPath 3.0 expression
405 * with no dependencies on namespace bindings other than the binding of the prefix "xs" to the XML Schema
406 * namespace.
407 *
408 * @return the expression as a string in XPath 3.0 syntax
409 */
410
411 public String toString() {
412 return ExpressionTool.parenthesize(getLhsExpression()) +
413 " " + displayOperator() + " " +
414 ExpressionTool.parenthesize(getRhsExpression());
415 }
416
417 @Override
418 public String toShortString() {
419 return parenthesize(getLhsExpression()) + " " + displayOperator() + " " + parenthesize(getRhsExpression());
420 }
421
422 private String parenthesize(Expression operand) {
423 String operandStr = operand.toShortString();
424 if (operand instanceof BinaryExpression &&
425 XPathParser.operatorPrecedence(((BinaryExpression) operand).operator) < XPathParser.operatorPrecedence(operator)) {
426 operandStr = "(" + operandStr + ")";
427 }
428 return operandStr;
429 }
430
431 /**
432 * Diagnostic print of expression structure. The abstract expression tree
433 * is written to the supplied output destination.
434 *
435 * @param out the output destination for the displayed expression tree
436 */
437
438 public void export(ExpressionPresenter out) throws XPathException {
439 out.startElement(tag(), this);
440 out.emitAttribute("op", displayOperator());
441 explainExtraAttributes(out);
442 getLhsExpression().export(out);
443 getRhsExpression().export(out);
444 out.endElement();
445 }
446
447 /**
448 * Get the element name used to identify this expression in exported expression format
449 * @return the element name used to identify this expression
450 */
451
452 protected String tag() {
453 return "operator";
454 }
455
456 /**
457 * Add subclass-specific attributes to the expression tree explanation. Default implementation
458 * does nothing; this is provided for subclasses to override.
459 *
460 * @param out the output destination for the displayed expression tree
461 */
462
463 protected void explainExtraAttributes(ExpressionPresenter out) {
464 }
465
466 /**
467 * Display the operator used by this binary expression
468 *
469 * @return String representation of the operator (for diagnostic display only)
470 */
471
472 protected String displayOperator() {
473 return Token.tokens[operator];
474 }
475
476
477 }
478