Debian Codegraph @

net/sf/saxon/expr/CastExpression.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
11 import net.sf.saxon.Configuration;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.functions.String_1;
14 import net.sf.saxon.lib.ConversionRules;
15 import net.sf.saxon.om.GroundedValue;
16 import net.sf.saxon.om.Sequence;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.type.*;
20 import net.sf.saxon.value.*;
21
22
23 /**
24 * Cast Expression: implements "cast as data-type ( expression )". It also allows an internal
25 * cast, which has the same semantics as a user-requested cast, but maps an empty sequence to
26 * an empty sequence.
27 * <p>This expression class does not handle casting to a list or union type.</p>
28 */
29
30 public class CastExpression extends CastingExpression implements Callable {
31
32 /**
33 * Create a cast expression
34 *
35 * @param source expression giving the value to be converted
36 * @param target the type to which the value is to be converted
37 * @param allowEmpty true if the expression allows an empty sequence as input, producing
38 * an empty sequence as output. If false, an empty sequence is a type error.
39 */
40
41 public CastExpression(Expression source, AtomicType target, boolean allowEmpty) {
42 super(source, target, allowEmpty);
43 }
44
45 /**
46 * Type-check the expression
47 */
48
49 /*@NotNull*/
50 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
51 getOperand().typeCheck(visitor, contextInfo);
52 SequenceType atomicType = SequenceType.makeSequenceType(BuiltInAtomicType.ANY_ATOMIC, getCardinality());
53
54 Configuration config = visitor.getConfiguration();
55 final TypeHierarchy th = config.getTypeHierarchy();
56 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.TYPE_OP, "cast as", 0);
57 ItemType sourceItemType = null;
58
59 TypeChecker tc = config.getTypeChecker(false);
60 Expression operand = tc.staticTypeCheck(getBaseExpression(), atomicType, role, visitor);
61 setBaseExpression(operand);
62 sourceItemType = operand.getItemType();
63
64
65 if (sourceItemType instanceof ErrorType) {
66 if (allowsEmpty()) {
67 return Literal.makeEmptySequence();
68 } else {
69 XPathException err = new XPathException("Cast does not allow an empty sequence as input");
70 err.setErrorCode("XPTY0004");
71 err.setLocation(getLocation());
72 err.setIsTypeError(true);
73 throw err;
74 }
75 }
76
77 PlainType sourceType = (PlainType) sourceItemType;
78 int r = th.relationship(sourceType, getTargetType());
79 if (r == TypeHierarchy.SAME_TYPE) {
80 return operand;
81 } else if (r == TypeHierarchy.SUBSUMED_BY) {
82 // It's generally true that any expression defined to return an X is allowed to return a subtype of X.
83 // However, people seem to get upset if we treat the cast as a no-op.
84 converter = new Converter.UpCastingConverter(getTargetType());
85 } else {
86
87 ConversionRules rules = visitor.getConfiguration().getConversionRules();
88
89 if (sourceType.isAtomicType() && sourceType != BuiltInAtomicType.ANY_ATOMIC) {
90 converter = rules.getConverter((AtomicType)sourceType, getTargetType());
91 if (converter == null) {
92 XPathException err = new XPathException("Casting from " + sourceType + " to " + getTargetType() +
93 " can never succeed");
94 err.setErrorCode("XPTY0004");
95 err.setLocation(getLocation());
96 err.setIsTypeError(true);
97 throw err;
98 } else {
99 if (getTargetType().isNamespaceSensitive()) {
100 converter = converter.setNamespaceResolver(getRetainedStaticContext());
101 }
102 }
103
104 }
105 }
106
107 if (operand instanceof Literal) {
108 return preEvaluate();
109 }
110
111 return this;
112 }
113
114 /**
115 * Perform optimisation of an expression and its subexpressions.
116 * <p>This method is called after all references to functions and variables have been resolved
117 * to the declaration of the function or variable, and after all type checking has been done.</p>
118 *
119 * @param visitor an expression visitor
120 * @param contextInfo the static type of "." at the point where this expression is invoked.
121 * The parameter is set to null if it is known statically that the context item will be undefined.
122 * If the type of the context item is not known statically, the argument is set to
123 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
124 * @return the original expression, rewritten if appropriate to optimize execution
125 * @throws net.sf.saxon.trans.XPathException
126 * if an error is discovered during this phase
127 * (typically a type error)
128 */
129
130 /*@NotNull*/
131 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
132 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
133 Expression e2 = super.optimize(visitor, contextInfo);
134 if (e2 != this) {
135 return e2;
136 }
137 // Eliminate pointless casting between untypedAtomic and string
138 Expression operand = getBaseExpression();
139 if (getTargetType() == BuiltInAtomicType.UNTYPED_ATOMIC) {
140 if (operand.isCallOn(String_1.class)) {
141 Expression e = ((SystemFunctionCall) operand).getArg(0);
142 if (e.getItemType() instanceof AtomicType && e.getCardinality() == StaticProperty.EXACTLY_ONE) {
143 operand = e;
144 }
145 } else if (operand instanceof CastExpression) {
146 if (((CastExpression) operand).getTargetType() == BuiltInAtomicType.UNTYPED_ATOMIC) {
147 return operand;
148 } else if (((CastExpression) operand).getTargetType() == BuiltInAtomicType.STRING) {
149 ((CastExpression) operand).setTargetType(BuiltInAtomicType.UNTYPED_ATOMIC);
150 return operand;
151 }
152 } else if (operand instanceof AtomicSequenceConverter) {
153 if (operand.getItemType() == BuiltInAtomicType.UNTYPED_ATOMIC) {
154 return operand;
155 } else if (operand.getItemType() == BuiltInAtomicType.STRING) {
156 AtomicSequenceConverter old = (AtomicSequenceConverter) operand;
157 AtomicSequenceConverter asc = new AtomicSequenceConverter(
158 old.getBaseExpression(),
159 BuiltInAtomicType.UNTYPED_ATOMIC
160 );
161 return asc.typeCheck(visitor, contextInfo)
162 .optimize(visitor, contextInfo);
163 }
164 }
165 }
166 // avoid converting anything to a string and then back again
167 if (operand.isCallOn(String_1.class)) {
168 Expression e = ((SystemFunctionCall) operand).getArg(0);
169 ItemType et = e.getItemType();
170 if (et instanceof AtomicType &&
171 e.getCardinality() == StaticProperty.EXACTLY_ONE &&
172 th.isSubType(et, getTargetType())) {
173 return e;
174 }
175 }
176 // avoid converting anything to untypedAtomic and then back again
177 if (operand instanceof CastExpression) {
178 ItemType it = ((CastExpression) operand).getTargetType();
179 if (th.isSubType(it, BuiltInAtomicType.STRING) || th.isSubType(it, BuiltInAtomicType.UNTYPED_ATOMIC)) {
180 Expression e = ((CastExpression) operand).getBaseExpression();
181 ItemType et = e.getItemType();
182 if (et instanceof AtomicType &&
183 e.getCardinality() == StaticProperty.EXACTLY_ONE &&
184 th.isSubType(et, getTargetType())) {
185 return e;
186 }
187 }
188 }
189 if (operand instanceof AtomicSequenceConverter) {
190 ItemType it = operand.getItemType();
191 if (th.isSubType(it, BuiltInAtomicType.STRING) || th.isSubType(it, BuiltInAtomicType.UNTYPED_ATOMIC)) {
192 Expression e = ((AtomicSequenceConverter) operand).getBaseExpression();
193 ItemType et = e.getItemType();
194 if (et instanceof AtomicType &&
195 e.getCardinality() == StaticProperty.EXACTLY_ONE &&
196 th.isSubType(et, getTargetType())) {
197 return e;
198 }
199 }
200 }
201 // if the operand can't be empty, then set allowEmpty to false to provide more information for analysis
202 if (!Cardinality.allowsZero(operand.getCardinality())) {
203 setAllowEmpty(false);
204 resetLocalStaticProperties();
205 }
206
207 if (operand instanceof Literal) {
208 return preEvaluate();
209 }
210 return this;
211 }
212
213 /**
214 * Perform early (compile-time) evaluation
215 */
216
217 protected Expression preEvaluate() throws XPathException {
218 GroundedValue literalOperand = ((Literal) getBaseExpression()).getValue();
219 if (literalOperand instanceof AtomicValue && converter != null) {
220 ConversionResult result = converter.convert((AtomicValue) literalOperand);
221 if (result instanceof ValidationFailure) {
222 ValidationFailure err = (ValidationFailure) result;
223 String code = err.getErrorCode();
224 if (code == null) {
225 code = "FORG0001";
226 }
227 throw new XPathException(err.getMessage(), code, this.getLocation());
228 } else {
229 return Literal.makeLiteral((AtomicValue) result, this);
230 }
231 }
232 if (literalOperand.getLength() == 0) {
233 if (allowsEmpty()) {
234 return getBaseExpression();
235 } else {
236 XPathException err = new XPathException("Cast can never succeed: the operand must not be an empty sequence", "XPTY0004", this.getLocation());
237 err.setIsTypeError(true);
238 throw err;
239 }
240 }
241 return this;
242 }
243
244 /**
245 * Get the static cardinality of the expression
246 */
247
248 public int computeCardinality() {
249 return allowsEmpty() && Cardinality.allowsZero(getBaseExpression().getCardinality())
250 ? StaticProperty.ALLOWS_ZERO_OR_ONE : StaticProperty.EXACTLY_ONE;
251 }
252
253 /**
254 * Get the static type of the expression
255 */
256
257 /*@NotNull*/
258 public ItemType getItemType() {
259 return getTargetType();
260 }
261
262
263 /**
264 * Get the static type of the expression as a UType, following precisely the type
265 * inference rules defined in the XSLT 3.0 specification.
266 *
267 * @return the static item type of the expression according to the XSLT 3.0 defined rules
268 * @param contextItemType
269 */
270 @Override
271 public UType getStaticUType(UType contextItemType) {
272 return getTargetType().getUType();
273 }
274
275 /**
276 * Determine the special properties of this expression
277 * @return the expression properties
278 */
279 @Override
280 public int computeSpecialProperties() {
281 int p = super.computeSpecialProperties();
282 if (getTargetType() == BuiltInAtomicType.UNTYPED_ATOMIC) {
283 p = p &~ StaticProperty.NOT_UNTYPED_ATOMIC;
284 }
285 return p;
286 }
287
288 /**
289 * For an expression that returns an integer or a sequence of integers, get
290 * a lower and upper bound on the values of the integers that may be returned, from
291 * static analysis. The default implementation returns null, meaning "unknown" or
292 * "not applicable". Other implementations return an array of two IntegerValue objects,
293 * representing the lower and upper bounds respectively. The values
294 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
295 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
296 * are used to indicate values limited by the size of a string or the size of a sequence.
297 *
298 * @return the lower and upper bounds of integer values in the result, or null to indicate
299 * unknown or not applicable.
300 */
301 /*@Nullable*/
302 @Override
303 public IntegerValue[] getIntegerBounds() {
304 if (converter == Converter.BooleanToInteger.INSTANCE) {
305 return new IntegerValue[]{Int64Value.ZERO, Int64Value.PLUS_ONE};
306 } else {
307 return null;
308 }
309 }
310
311 /**
312 * Copy an expression. This makes a deep copy.
313 *
314 * @return the copy of the original expression
315 * @param rebindings
316 */
317
318 /*@NotNull*/
319 public Expression copy(RebindingMap rebindings) {
320 CastExpression c2 = new CastExpression(getBaseExpression().copy(rebindings), getTargetType(), allowsEmpty());
321 ExpressionTool.copyLocationInfo(this, c2);
322 c2.converter = converter;
323 c2.setRetainedStaticContext(getRetainedStaticContext());
324 c2.setOperandIsStringLiteral(isOperandIsStringLiteral());
325 return c2;
326 }
327
328 /**
329 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
330 * This method indicates which of these methods is provided directly. The other methods will always be available
331 * indirectly, using an implementation that relies on one of the other methods.
332 *
333 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
334 * {@link #PROCESS_METHOD}
335 */
336 @Override
337 public int getImplementationMethod() {
338 return EVALUATE_METHOD;
339 }
340
341 public Sequence<?> call(XPathContext context, Sequence[] arguments) throws XPathException {
342 AtomicValue result = doCast((AtomicValue)arguments[0].head(), context);
343 return result == null ? EmptySequence.getInstance() : result;
344 }
345
346 private AtomicValue doCast(AtomicValue value, XPathContext context) throws XPathException {
347 if (value == null) {
348 if (allowsEmpty()) {
349 return null;
350 } else {
351 XPathException e = new XPathException("Cast does not allow an empty sequence");
352 e.setXPathContext(context);
353 e.setLocation(getLocation());
354 e.setErrorCode("XPTY0004");
355 throw e;
356 }
357 }
358
359 Converter converter = this.converter;
360 if (converter == null) {
361 ConversionRules rules = context.getConfiguration().getConversionRules();
362 converter = rules.getConverter(value.getPrimitiveType(), getTargetType());
363 if (converter == null) {
364 XPathException e = new XPathException("Casting from " + value.getPrimitiveType() + " to " + getTargetType() + " is not permitted");
365 e.setXPathContext(context);
366 e.setLocation(getLocation());
367 e.setErrorCode("XPTY0004");
368 throw e;
369 }
370 if (getTargetType().isNamespaceSensitive()) {
371 converter = converter.setNamespaceResolver(getRetainedStaticContext());
372 }
373 }
374 ConversionResult result = converter.convert(value);
375 if (result instanceof ValidationFailure) {
376 ValidationFailure err = (ValidationFailure) result;
377 XPathException xe = err.makeException();
378 xe.maybeSetErrorCode("FORG0001");
379 xe.maybeSetLocation(getLocation());
380 throw xe;
381 }
382 return (AtomicValue) result;
383 }
384
385 /**
386 * Evaluate the expression
387 */
388
389 /*@Nullable*/
390 public AtomicValue evaluateItem(XPathContext context) throws XPathException {
391 try {
392 AtomicValue value = (AtomicValue) getBaseExpression().evaluateItem(context);
393 return doCast(value, context);
394 } catch (ClassCastException e) {
395 e.printStackTrace();
396 throw e;
397 }
398 }
399
400 /**
401 * Is this expression the same as another expression?
402 */
403
404 public boolean equals(Object other) {
405 return other instanceof CastExpression &&
406 getBaseExpression().isEqual(((CastExpression) other).getBaseExpression()) &&
407 getTargetType() == ((CastExpression) other).getTargetType() &&
408 allowsEmpty() == ((CastExpression) other).allowsEmpty();
409 }
410
411 /**
412 * get HashCode for comparing two expressions. Note that this hashcode gives the same
413 * result for (A op B) and for (B op A), whether or not the operator is commutative.
414 */
415
416 @Override
417 public int computeHashCode() {
418 return super.computeHashCode() ^ getTargetType().hashCode();
419 }
420
421 /**
422 * Represent the expression as a string. The resulting string will be a valid XPath 3.0 expression
423 * with no dependencies on namespace bindings.
424 *
425 * @return the expression as a string in XPath 3.0 syntax
426 */
427
428 public String toString() {
429 return getTargetType().getEQName() + "(" + getBaseExpression().toString() + ")";
430 }
431
432 @Override
433 public String toShortString() {
434 return getTargetType().getDisplayName() + "(" + getBaseExpression().toShortString() + ")";
435 }
436
437 /**
438 * Diagnostic print of expression structure. The abstract expression tree
439 * is written to the supplied output destination.
440 */
441
442 public void export(ExpressionPresenter out) throws XPathException {
443 out.startElement("cast", this);
444 out.emitAttribute("as", getTargetType().toExportString());
445 out.emitAttribute("emptiable", allowsEmpty() ? "1" : "0");
446 getBaseExpression().export(out);
447 out.endElement();
448 }
449
450 /**
451 * Get a name identifying the kind of expression, in terms meaningful to a user.
452 *
453 * @return a name identifying the kind of expression, in terms meaningful to a user.
454 * The name will always be in the form of a lexical XML QName, and should match the name used
455 * in export() output displaying the expression.
456 */
457 @Override
458 public String getExpressionName() {
459 return "cast";
460 }
461
462
463
464 }
465