Debian Codegraph @

net/sf/saxon/expr/ArithmeticExpression.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.compat.ArithmeticExpression10;
11 import net.sf.saxon.Configuration;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.om.GroundedValue;
14 import net.sf.saxon.om.StandardNames;
15 import net.sf.saxon.trace.ExpressionPresenter;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.*;
18 import net.sf.saxon.value.*;
19
20 /**
21 * Arithmetic Expression: an expression using one of the operators
22 * plus, minus, multiply, div, idiv, mod. Note that this code does not handle backwards
23 * compatibility mode: see {@link ArithmeticExpression10}
24 */
25
26 public class ArithmeticExpression extends BinaryExpression {
27
28 protected Calculator calculator;
29 private PlainType itemType;
30
31 /**
32 * Create an arithmetic expression
33 *
34 * @param p0 the first operand
35 * @param operator the operator, for example {@link Token#PLUS}
36 * @param p1 the second operand
37 */
38
39 public ArithmeticExpression(Expression p0, int operator, Expression p1) {
40 super(p0, operator, p1);
41 }
42
43 /**
44 * Get a name identifying the kind of expression, in terms meaningful to a user.
45 *
46 * @return a name identifying the kind of expression, in terms meaningful to a user.
47 * The name will always be in the form of a lexical XML QName, and should match the name used
48 * in explain() output displaying the expression.
49 */
50
51 public String getExpressionName() {
52 return "arithmetic";
53 }
54
55 /**
56 * Determine the special properties of this expression
57 *
58 * @return {@link StaticProperty#NO_NODES_NEWLY_CREATED}. This is overridden
59 * for some subclasses.
60 */
61 @Override
62 public int computeSpecialProperties() {
63 int p = super.computeSpecialProperties();
64 return p | StaticProperty.NOT_UNTYPED_ATOMIC;
65 }
66
67 /**
68 * Set the calculator allocated to evaluate this expression
69 * @param calculator the calculator to be used
70 */
71
72 public void setCalculator(Calculator calculator) {
73 this.calculator = calculator;
74 }
75
76 /**
77 * Get the calculator allocated to evaluate this expression
78 *
79 * @return the calculator, a helper object that does the actual calculation
80 */
81
82 public Calculator getCalculator() {
83 return calculator;
84 }
85
86 /**
87 * Type-check the expression statically. We try to work out which particular
88 * arithmetic function to use if the types of operands are known an compile time.
89 */
90
91 /*@NotNull*/
92 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
93
94 resetLocalStaticProperties();
95 getLhs().typeCheck(visitor, contextInfo);
96 getRhs().typeCheck(visitor, contextInfo);
97
98 Configuration config = visitor.getConfiguration();
99 final TypeHierarchy th = config.getTypeHierarchy();
100 final TypeChecker tc = config.getTypeChecker(false);
101
102 Expression oldOp0 = getLhsExpression();
103 Expression oldOp1 = getRhsExpression();
104
105 SequenceType atomicType = SequenceType.OPTIONAL_ATOMIC;
106
107 RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 0);
108 //role0.setSourceLocator(this);
109 setLhsExpression(tc.staticTypeCheck(getLhsExpression(), atomicType, role0, visitor));
110 final ItemType itemType0 = getLhsExpression().getItemType();
111 if (itemType0 instanceof ErrorType) {
112 return Literal.makeEmptySequence();
113 }
114 AtomicType type0 = (AtomicType) itemType0.getPrimitiveItemType();
115 if (type0.getFingerprint() == StandardNames.XS_UNTYPED_ATOMIC) {
116 setLhsExpression(UntypedSequenceConverter.makeUntypedSequenceConverter(config, getLhsExpression(), BuiltInAtomicType.DOUBLE));
117 type0 = BuiltInAtomicType.DOUBLE;
118 } else if (/*!(operand0 instanceof UntypedAtomicConverter)*/
119 (getLhsExpression().getSpecialProperties() & StaticProperty.NOT_UNTYPED_ATOMIC) == 0 &&
120 th.relationship(type0, BuiltInAtomicType.UNTYPED_ATOMIC) != TypeHierarchy.DISJOINT) {
121 setLhsExpression(UntypedSequenceConverter.makeUntypedSequenceConverter(config, getLhsExpression(), BuiltInAtomicType.DOUBLE));
122 type0 = (AtomicType) getLhsExpression().getItemType().getPrimitiveItemType();
123 }
124
125 // System.err.println("First operand"); operand0.display(10);
126
127 RoleDiagnostic role1 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 1);
128 //role1.setSourceLocator(this);
129 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), atomicType, role1, visitor));
130 final ItemType itemType1 = getRhsExpression().getItemType();
131 if (itemType1 instanceof ErrorType) {
132 return Literal.makeEmptySequence();
133 }
134 AtomicType type1 = (AtomicType) itemType1.getPrimitiveItemType();
135 if (type1.getFingerprint() == StandardNames.XS_UNTYPED_ATOMIC) {
136 setRhsExpression(UntypedSequenceConverter.makeUntypedSequenceConverter(config, getRhsExpression(), BuiltInAtomicType.DOUBLE));
137 type1 = BuiltInAtomicType.DOUBLE;
138 } else if (/*!(operand1 instanceof UntypedAtomicConverter) &&*/
139 (getRhsExpression().getSpecialProperties() & StaticProperty.NOT_UNTYPED_ATOMIC) == 0 &&
140 th.relationship(type1, BuiltInAtomicType.UNTYPED_ATOMIC) != TypeHierarchy.DISJOINT) {
141 setRhsExpression(UntypedSequenceConverter.makeUntypedSequenceConverter(config, getRhsExpression(), BuiltInAtomicType.DOUBLE));
142 type1 = (AtomicType) getRhsExpression().getItemType().getPrimitiveItemType();
143 }
144
145 if (getLhsExpression() != oldOp0) {
146 adoptChildExpression(getLhsExpression());
147 }
148
149 if (getRhsExpression() != oldOp1) {
150 adoptChildExpression(getRhsExpression());
151 }
152
153 if (Literal.isEmptySequence(getLhsExpression()) ||
154 Literal.isEmptySequence(getRhsExpression())) {
155 return Literal.makeEmptySequence();
156 }
157
158 if (type0.isExternalType() || type1.isExternalType()) {
159 XPathException de = new XPathException("Arithmetic operators are not defined for external objects");
160 de.setLocation(getLocation());
161 de.setErrorCode("XPTY0004");
162 throw de;
163 }
164
165 if (operator == Token.NEGATE) {
166 if (getRhsExpression() instanceof Literal && ((Literal) getRhsExpression()).getValue() instanceof NumericValue) {
167 NumericValue nv = (NumericValue) ((Literal) getRhsExpression()).getValue();
168 return Literal.makeLiteral(nv.negate(), this);
169 } else {
170 NegateExpression ne = new NegateExpression(getRhsExpression());
171 ne.setBackwardsCompatible(false);
172 return ne.typeCheck(visitor, contextInfo);
173 }
174 }
175
176 // Get a calculator to implement the arithmetic operation. If the types are not yet specifically known,
177 // we allow this to return an "ANY" calculator which defers the decision. However, we only allow this if
178 // at least one of the operand types is AnyAtomicType or (otherwise unspecified) numeric.
179
180 boolean mustResolve = !(type0.equals(BuiltInAtomicType.ANY_ATOMIC) || type1.equals(BuiltInAtomicType.ANY_ATOMIC)
181 || type0.equals(NumericType.getInstance()) || type1.equals(NumericType.getInstance()));
182
183 calculator = Calculator.getCalculator(
184 type0.getFingerprint(), type1.getFingerprint(), mapOpCode(operator), mustResolve);
185
186 if (calculator == null) {
187 XPathException de = new XPathException("Arithmetic operator is not defined for arguments of types (" +
188 type0.getDescription() + ", " + type1.getDescription() + ")");
189 de.setLocation(getLocation());
190 de.setIsTypeError(true);
191 de.setErrorCode("XPTY0004");
192 throw de;
193 }
194
195 // If the calculator is going to promote arguments to xs:double, then promote any literal arguments now.
196 // (Could generalize this, but this is the common case)
197 if (calculator.code().matches("d.d")) {
198 if (getLhsExpression() instanceof Literal && !type0.equals(BuiltInAtomicType.DOUBLE)) {
199 GroundedValue value = ((Literal) getLhsExpression()).getValue();
200 if (value instanceof NumericValue) {
201 setLhsExpression(Literal.makeLiteral(new DoubleValue(((NumericValue) value).getDoubleValue()), this));
202 }
203 }
204 if (getRhsExpression() instanceof Literal && !type1.equals(BuiltInAtomicType.DOUBLE)) {
205 GroundedValue value = ((Literal) getRhsExpression()).getValue();
206 if (value instanceof NumericValue) {
207 setRhsExpression(Literal.makeLiteral(new DoubleValue(((NumericValue) value).getDoubleValue()), this));
208 }
209 }
210 }
211
212 try {
213 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
214 return Literal.makeLiteral(evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()).materialize(), this);
215 }
216 } catch (XPathException err) {
217 // if early evaluation fails, suppress the error: the value might
218 // not be needed at run-time, or it might be due to context such as the implicit timezone
219 // not being available yet
220 }
221 return this;
222 }
223
224 /**
225 * For an expression that returns an integer or a sequence of integers, get
226 * a lower and upper bound on the values of the integers that may be returned, from
227 * static analysis. The default implementation returns null, meaning "unknown" or
228 * "not applicable". Other implementations return an array of two IntegerValue objects,
229 * representing the lower and upper bounds respectively. The values
230 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
231 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
232 * are used to indicate values limited by the size of a string or the size of a sequence.
233 *
234 * @return the lower and upper bounds of integer values in the result, or null to indicate
235 * unknown or not applicable.
236 */
237 /*@Nullable*/
238 @Override
239 public IntegerValue[] getIntegerBounds() {
240 IntegerValue[] bounds0 = getLhsExpression().getIntegerBounds();
241 IntegerValue[] bounds1 = getRhsExpression().getIntegerBounds();
242 if (bounds0 == null || bounds1 == null) {
243 return null;
244 } else {
245 switch (operator) {
246 case Token.PLUS:
247 return new IntegerValue[]{bounds0[0].plus(bounds1[0]), bounds0[1].plus(bounds1[1])};
248 case Token.MINUS:
249 return new IntegerValue[]{bounds0[0].minus(bounds1[1]), bounds0[1].minus(bounds1[0])};
250 case Token.MULT:
251 if (getRhsExpression() instanceof Literal) {
252 IntegerValue val1 = bounds1[0];
253 if (val1.signum() > 0) {
254 return new IntegerValue[]{bounds0[0].times(val1), bounds0[1].times(val1)};
255 } else {
256 return null;
257 }
258 } else if (getLhsExpression() instanceof Literal) {
259 IntegerValue val0 = bounds1[0];
260 if (val0.signum() > 0) {
261 return new IntegerValue[]{bounds1[0].times(val0), bounds1[1].times(val0)};
262 } else {
263 return null;
264 }
265 }
266 case Token.DIV:
267 case Token.IDIV:
268 if (getRhsExpression() instanceof Literal) {
269 IntegerValue val1 = bounds1[0];
270 if (val1.signum() > 0) {
271 try {
272 return new IntegerValue[]{bounds0[0].idiv(val1), bounds0[1].idiv(val1)};
273 } catch (XPathException e) {
274 return null;
275 }
276 }
277 }
278 return null;
279 default:
280 return null;
281 }
282 }
283 }
284
285 /**
286 * Copy an expression. This makes a deep copy.
287 *
288 * @return the copy of the original expression
289 * @param rebindings
290 */
291
292 /*@NotNull*/
293 public Expression copy(RebindingMap rebindings) {
294 ArithmeticExpression ae = new ArithmeticExpression(getLhsExpression().copy(rebindings), operator, getRhsExpression().copy(rebindings));
295 ExpressionTool.copyLocationInfo(this, ae);
296 ae.calculator = calculator;
297 return ae;
298 }
299
300 /**
301 * Static method to apply arithmetic to two values
302 *
303 * @param value0 the first value
304 * @param operator the operator as denoted in the Calculator class, for example {@link Calculator#PLUS}
305 * @param value1 the second value
306 * @param context the XPath dynamic evaluation context
307 * @return the result of the arithmetic operation
308 * @throws XPathException if a dynamic error occurs during evaluation
309 */
310
311 public static AtomicValue compute(AtomicValue value0, int operator, AtomicValue value1, XPathContext context)
312 throws XPathException {
313 int p0 = value0.getPrimitiveType().getFingerprint();
314 int p1 = value1.getPrimitiveType().getFingerprint();
315 Calculator calculator = Calculator.getCalculator(p0, p1, operator, false);
316 return calculator.compute(value0, value1, context);
317 }
318
319 /**
320 * Map operator codes from those in the Token class to those in the Calculator class
321 *
322 * @param op an operator denoted by a constant in the {@link Token} class, for example {@link Token#PLUS}
323 * @return an operator denoted by a constant defined in the {@link Calculator} class, for example
324 * {@link Calculator#PLUS}
325 */
326
327 public static int mapOpCode(int op) {
328 switch (op) {
329 case Token.PLUS:
330 return Calculator.PLUS;
331 case Token.MINUS:
332 case Token.NEGATE:
333 return Calculator.MINUS;
334 case Token.MULT:
335 return Calculator.TIMES;
336 case Token.DIV:
337 return Calculator.DIV;
338 case Token.IDIV:
339 return Calculator.IDIV;
340 case Token.MOD:
341 return Calculator.MOD;
342 default:
343 throw new IllegalArgumentException();
344 }
345
346 }
347
348 /**
349 * Determine the data type of the expression, insofar as this is known statically
350 *
351 * @return the atomic type of the result of this arithmetic expression
352 */
353
354 /*@NotNull*/
355 public PlainType getItemType() {
356 if (itemType != null) {
357 return itemType;
358 }
359 if (calculator == null) {
360 return BuiltInAtomicType.ANY_ATOMIC; // type is not known statically
361 } else {
362 ItemType t1 = getLhsExpression().getItemType();
363 if (!(t1 instanceof AtomicType)) {
364 t1 = t1.getAtomizedItemType();
365 }
366 ItemType t2 = getRhsExpression().getItemType();
367 if (!(t2 instanceof AtomicType)) {
368 t2 = t2.getAtomizedItemType();
369 }
370 PlainType resultType = calculator.getResultType((AtomicType) t1.getPrimitiveItemType(),
371 (AtomicType) t2.getPrimitiveItemType());
372
373 if (resultType.equals(BuiltInAtomicType.ANY_ATOMIC)) {
374 // there are a few special cases where we can do better. For example, given X+1, where the type of X
375 // is unknown, we can still infer that the result is numeric. (Not so for X*2, however, where it could
376 // be a duration)
377 TypeHierarchy th = getConfiguration().getTypeHierarchy();
378 if ((operator == Token.PLUS || operator == Token.MINUS) &&
379 (th.isSubType(t2, NumericType.getInstance()) || th.isSubType(t1, NumericType.getInstance()))) {
380 resultType = NumericType.getInstance();
381 }
382 }
383 return itemType = resultType;
384 }
385 }
386
387 /**
388 * Get the static type of the expression as a UType, following precisely the type
389 * inference rules defined in the XSLT 3.0 specification.
390 *
391 * @return the static item type of the expression according to the XSLT 3.0 defined rules
392 * @param contextItemType
393 */
394 @Override
395 public UType getStaticUType(UType contextItemType) {
396 // The rationale for this is in the XSLT 3.0 spec
397 if (getParentExpression() instanceof FilterExpression && ((FilterExpression)getParentExpression()).getRhsExpression() == this) {
398 return UType.NUMERIC;
399 } else if (operator == Token.NEGATE) {
400 return UType.NUMERIC;
401 } else {
402 return UType.ANY_ATOMIC;
403 }
404 }
405
406 /**
407 * Reset the static properties of the expression to -1, so that they have to be recomputed
408 * next time they are used.
409 */
410 @Override
411 public void resetLocalStaticProperties() {
412 super.resetLocalStaticProperties();
413 itemType = null;
414 }
415
416 /**
417 * Evaluate the expression.
418 */
419
420 public AtomicValue evaluateItem(XPathContext context) throws XPathException {
421
422 AtomicValue v0 = (AtomicValue) getLhsExpression().evaluateItem(context);
423 if (v0 == null) {
424 return null;
425 }
426
427 AtomicValue v1 = (AtomicValue) getRhsExpression().evaluateItem(context);
428 if (v1 == null) {
429 return null;
430 }
431
432 try {
433 return calculator.compute(v0, v1, context);
434 } catch (XPathException e) {
435 e.maybeSetLocation(getLocation());
436 e.maybeSetFailingExpression(this);
437 e.maybeSetContext(context);
438 throw e;
439 }
440 }
441
442 @Override
443 protected String tag() {
444 return "arith";
445 }
446
447 @Override
448 protected void explainExtraAttributes(ExpressionPresenter out) {
449 if (calculator != null) { // May be null during optimizer tracing
450 out.emitAttribute("calc", calculator.code());
451 }
452 }
453
454
455
456 }
457