Debian Codegraph @

net/sf/saxon/expr/compat/ArithmeticExpression10.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.instruct.Choose;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.functions.Number_1;
15 import net.sf.saxon.functions.SystemFunction;
16 import net.sf.saxon.lib.NamespaceConstant;
17 import net.sf.saxon.om.GroundedValue;
18 import net.sf.saxon.om.Sequence;
19 import net.sf.saxon.om.StructuredQName;
20 import net.sf.saxon.trace.ExpressionPresenter;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.*;
23 import net.sf.saxon.value.*;
24
25 /**
26 * Arithmetic Expression: an expression using one of the operators
27 * plus, minus, multiply, div, idiv, mod, in backwards
28 * compatibility mode: see {@link ArithmeticExpression} for the non-backwards
29 * compatible case.
30 */
31
32 public class ArithmeticExpression10 extends ArithmeticExpression implements Callable {
33
34 /**
35 * Create an arithmetic expression to be evaluated in XPath 1.0 mode
36 *
37 * @param p0 the first operand
38 * @param operator the operator, for example {@link Token#PLUS}
39 * @param p1 the second operand
40 */
41
42 public ArithmeticExpression10(Expression p0, int operator, Expression p1) {
43 super(p0, operator, p1);
44 }
45
46 /**
47 * Type-check the expression statically. We try to work out which particular
48 * arithmetic function to use if the types of operands are known an compile time.
49 */
50
51 /*@NotNull*/
52 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
53
54 getLhs().typeCheck(visitor, contextInfo);
55 getRhs().typeCheck(visitor, contextInfo);
56
57 final Configuration config = visitor.getConfiguration();
58 final TypeHierarchy th = config.getTypeHierarchy();
59
60 if (Literal.isEmptySequence(getLhsExpression())) {
61 return Literal.makeLiteral(DoubleValue.NaN, this);
62 }
63
64 if (Literal.isEmptySequence(getRhsExpression())) {
65 return Literal.makeLiteral(DoubleValue.NaN, this);
66 }
67
68 Expression oldOp0 = getLhsExpression();
69 Expression oldOp1 = getRhsExpression();
70
71
72 SequenceType atomicType = SequenceType.OPTIONAL_ATOMIC;
73 TypeChecker tc = visitor.getConfiguration().getTypeChecker(true);
74
75 RoleDiagnostic role0 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 0);
76 setLhsExpression(tc.staticTypeCheck(getLhsExpression(), atomicType, role0, visitor));
77
78 RoleDiagnostic role1 = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, Token.tokens[operator], 1);
79 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), atomicType, role1, visitor));
80
81 final ItemType itemType0 = getLhsExpression().getItemType();
82 if (itemType0 instanceof ErrorType) {
83 return Literal.makeLiteral(DoubleValue.NaN, this);
84 }
85 AtomicType type0 = (AtomicType) itemType0.getPrimitiveItemType();
86
87 final ItemType itemType1 = getRhsExpression().getItemType();
88 if (itemType1 instanceof ErrorType) {
89 return Literal.makeLiteral(DoubleValue.NaN, this);
90 }
91 AtomicType type1 = (AtomicType) itemType1.getPrimitiveItemType();
92
93 // If both operands are integers, use integer arithmetic and convert the result to a double
94 if (th.isSubType(type0, BuiltInAtomicType.INTEGER) &&
95 th.isSubType(type1, BuiltInAtomicType.INTEGER) &&
96 (operator == Token.PLUS || operator == Token.MINUS || operator == Token.MULT)) {
97 ArithmeticExpression arith = new ArithmeticExpression(getLhsExpression(), operator, getRhsExpression());
98 Expression n = SystemFunction.makeCall("number", getRetainedStaticContext(), arith);
99 return n.typeCheck(visitor, contextInfo);
100 }
101
102 if (calculator == null) {
103 setLhsExpression(createConversionCode(getLhsExpression(), config, type0));
104 }
105 type0 = (AtomicType) getLhsExpression().getItemType().getPrimitiveItemType();
106
107 // System.err.println("First operand"); operand0.display(10);
108
109
110 if (calculator == null) {
111 setRhsExpression(createConversionCode(getRhsExpression(), config, type1));
112 }
113
114 type1 = (AtomicType) getRhsExpression().getItemType().getPrimitiveItemType();
115
116 if (getLhsExpression() != oldOp0) {
117 adoptChildExpression(getLhsExpression());
118 }
119
120 if (getRhsExpression() != oldOp1) {
121 adoptChildExpression(getRhsExpression());
122 }
123
124 if (operator == Token.NEGATE) {
125 if (getRhsExpression() instanceof Literal) {
126 GroundedValue v = ((Literal) getRhsExpression()).getValue();
127 if (v instanceof NumericValue) {
128 return Literal.makeLiteral(((NumericValue) v).negate(), this);
129 }
130 }
131 NegateExpression ne = new NegateExpression(getRhsExpression());
132 ne.setBackwardsCompatible(true);
133 return ne.typeCheck(visitor, contextInfo);
134 }
135
136 // Get a calculator to implement the arithmetic operation. If the types are not yet specifically known,
137 // we allow this to return an "ANY" calculator which defers the decision. However, we only allow this if
138 // at least one of the operand types is AnyAtomicType or (otherwise unspecified) numeric.
139
140 boolean mustResolve = !(type0.equals(BuiltInAtomicType.ANY_ATOMIC) || type1.equals(BuiltInAtomicType.ANY_ATOMIC)
141 || type0.equals(NumericType.getInstance()) || type1.equals(NumericType.getInstance()));
142
143 calculator = assignCalculator(type0, type1, mustResolve);
144
145 try {
146 if ((getLhsExpression() instanceof Literal) && (getRhsExpression() instanceof Literal)) {
147 return Literal.makeLiteral(
148 evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()).materialize(), this);
149 }
150 } catch (XPathException err) {
151 // if early evaluation fails, suppress the error: the value might
152 // not be needed at run-time
153 }
154 return this;
155 }
156
157 /**
158 * Set the calculator externally (used when reconstructing the expression tree)
159 * @param calc the calculator to be used
160 */
161
162 public void setCalculator(Calculator calc) {
163 this.calculator = calc;
164 }
165
166 private Calculator assignCalculator(AtomicType type0, AtomicType type1, boolean mustResolve) throws XPathException {
167 Calculator calculator = Calculator.getCalculator(type0.getFingerprint(), type1.getFingerprint(),
168 ArithmeticExpression.mapOpCode(operator), mustResolve);
169
170 if (calculator == null) {
171 XPathException de = new XPathException("Arithmetic operator is not defined for arguments of types (" +
172 type0.getDescription() + ", " + type1.getDescription() + ")");
173 de.setLocation(getLocation());
174 de.setErrorCode("XPTY0004");
175 throw de;
176 }
177 return calculator;
178 }
179
180 private Expression createConversionCode(
181 Expression operand, final Configuration config, AtomicType type) {
182 TypeHierarchy th = config.getTypeHierarchy();
183 if (Cardinality.allowsMany(operand.getCardinality())) {
184 Expression fie = FirstItemExpression.makeFirstItemExpression(operand);
185 ExpressionTool.copyLocationInfo(this, fie);
186 operand = fie;
187 }
188
189 if (th.isSubType(type, BuiltInAtomicType.DOUBLE) ||
190 th.isSubType(type, BuiltInAtomicType.DATE) ||
191 th.isSubType(type, BuiltInAtomicType.TIME) ||
192 th.isSubType(type, BuiltInAtomicType.DATE_TIME) ||
193 th.isSubType(type, BuiltInAtomicType.DURATION)) {
194 return operand;
195 }
196 if (th.isSubType(type, BuiltInAtomicType.BOOLEAN) ||
197 th.isSubType(type, BuiltInAtomicType.STRING) ||
198 th.isSubType(type, BuiltInAtomicType.UNTYPED_ATOMIC) ||
199 th.isSubType(type, BuiltInAtomicType.FLOAT) ||
200 th.isSubType(type, BuiltInAtomicType.DECIMAL)) {
201 if (operand instanceof Literal) {
202 GroundedValue val = ((Literal) operand).getValue();
203 return Literal.makeLiteral(Number_1.convert((AtomicValue) val, config), this);
204 } else {
205 return SystemFunction.makeCall("number", getRetainedStaticContext(), operand);
206 }
207 }
208 // If we can't determine the primitive type at compile time, we generate a run-time typeswitch
209
210 LetExpression let = new LetExpression();
211 let.setRequiredType(SequenceType.OPTIONAL_ATOMIC);
212 let.setVariableQName(new StructuredQName("nn", NamespaceConstant.SAXON, "nn" + let.hashCode()));
213 let.setSequence(operand);
214
215 LocalVariableReference var = new LocalVariableReference(let);
216 Expression isDouble = new InstanceOfExpression(
217 var, BuiltInAtomicType.DOUBLE.zeroOrOne());
218
219 var = new LocalVariableReference(let);
220 Expression isDecimal = new InstanceOfExpression(
221 var, BuiltInAtomicType.DECIMAL.zeroOrOne());
222
223 var = new LocalVariableReference(let);
224 Expression isFloat = new InstanceOfExpression(
225 var, BuiltInAtomicType.FLOAT.zeroOrOne());
226
227 var = new LocalVariableReference(let);
228 Expression isString = new InstanceOfExpression(
229 var, BuiltInAtomicType.STRING.zeroOrOne());
230
231 var = new LocalVariableReference(let);
232 Expression isUntypedAtomic = new InstanceOfExpression(
233 var, BuiltInAtomicType.UNTYPED_ATOMIC.zeroOrOne());
234
235 var = new LocalVariableReference(let);
236 Expression isBoolean = new InstanceOfExpression(
237 var, BuiltInAtomicType.BOOLEAN.zeroOrOne());
238
239 Expression condition = new OrExpression(isDouble, isDecimal);
240 condition = new OrExpression(condition, isFloat);
241 condition = new OrExpression(condition, isString);
242 condition = new OrExpression(condition, isUntypedAtomic);
243 condition = new OrExpression(condition, isBoolean);
244
245 var = new LocalVariableReference(let);
246 Expression fn = SystemFunction.makeCall("number", getRetainedStaticContext(), var);
247
248 var = new LocalVariableReference(let);
249 var.setStaticType(SequenceType.SINGLE_ATOMIC, null, 0);
250 Expression action = Choose.makeConditional(condition, fn, var);
251 let.setAction(action);
252 return let;
253 }
254
255 /**
256 * Determine the data type of the expression, if this is known statically
257 */
258
259 /*@NotNull*/
260 public PlainType getItemType() {
261 if (calculator == null) {
262 return BuiltInAtomicType.ANY_ATOMIC; // type is not known statically
263 } else {
264 ItemType t1 = getLhsExpression().getItemType();
265 if (!(t1 instanceof AtomicType)) {
266 t1 = t1.getAtomizedItemType();
267 }
268 ItemType t2 = getRhsExpression().getItemType();
269 if (!(t2 instanceof AtomicType)) {
270 t2 = t2.getAtomizedItemType();
271 }
272 return calculator.getResultType((AtomicType) t1.getPrimitiveItemType(),
273 (AtomicType) t2.getPrimitiveItemType());
274 }
275 }
276
277
278 /**
279 * Copy an expression. This makes a deep copy.
280 *
281 * @return the copy of the original expression
282 * @param rebindings
283 */
284
285 /*@NotNull*/
286 public Expression copy(RebindingMap rebindings) {
287 ArithmeticExpression10 a2 = new ArithmeticExpression10(getLhsExpression().copy(rebindings), operator, getRhsExpression().copy(rebindings));
288 ExpressionTool.copyLocationInfo(this, a2);
289 a2.calculator = calculator;
290 return a2;
291 }
292
293 @Override
294 protected String tag() {
295 return "arith10";
296 }
297
298 @Override
299 protected void explainExtraAttributes(ExpressionPresenter out) {
300 out.emitAttribute("calc", calculator.code());
301 }
302
303 /**
304 * Evaluate the expression.
305 */
306
307 public AtomicValue evaluateItem(XPathContext context) throws XPathException {
308
309 Calculator calc = calculator;
310 AtomicValue v1 = (AtomicValue) getLhsExpression().evaluateItem(context);
311 if (v1 == null) {
312 return DoubleValue.NaN;
313 }
314
315 AtomicValue v2 = (AtomicValue) getRhsExpression().evaluateItem(context);
316 if (v2 == null) {
317 return DoubleValue.NaN;
318 }
319
320 if (calc == null) {
321 // This shouldn't happen. It's a fallback for a failure to assign the calculator earlier
322 // at compile time. It has been known to happen when simplify() is called without typeCheck().
323 calc = assignCalculator(v1.getPrimitiveType(), v2.getPrimitiveType(), true);
324 }
325
326 return calc.compute(v1, v2, context);
327 }
328
329 /**
330 * Evaluate the expression
331 *
332 * @param context the dynamic evaluation context
333 * @param arguments the values of the arguments, supplied as SequenceIterators
334 * @return the result of the evaluation, in the form of a SequenceIterator
335 * @throws XPathException
336 * if a dynamic error occurs during the evaluation of the expression
337 */
338 public AtomicValue call(XPathContext context, Sequence[] arguments) throws XPathException {
339 Calculator calc = calculator;
340 AtomicValue v1 = (AtomicValue) arguments[0].head();
341 if (v1 == null) {
342 return DoubleValue.NaN;
343 }
344
345 AtomicValue v2 = (AtomicValue) arguments[1].head();
346 if (v2 == null) {
347 return DoubleValue.NaN;
348 }
349
350 if (calc == null) {
351 // This shouldn't happen. It's a fallback for a failure to assign the calculator earlier
352 // at compile time. It has been known to happen when simplify() is called without typeCheck().
353 calc = assignCalculator(v1.getPrimitiveType(), v2.getPrimitiveType(), true);
354 }
355
356 return calc.compute(v1, v2, context);
357 }
358 }
359