Debian Codegraph @

net/sf/saxon/expr/CastableExpression.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.ContextItemStaticInfo;
11 import net.sf.saxon.expr.parser.ExpressionTool;
12 import net.sf.saxon.expr.parser.ExpressionVisitor;
13 import net.sf.saxon.expr.parser.RebindingMap;
14 import net.sf.saxon.om.*;
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.AtomicValue;
19 import net.sf.saxon.value.BooleanValue;
20 import net.sf.saxon.value.Cardinality;
21
22 /**
23 * Castable Expression: implements "Expr castable as atomic-type?".
24 * The implementation simply wraps a cast expression with a try/catch.
25 */
26
27 public final class CastableExpression extends CastingExpression {
28
29 /**
30 * Create a "castable" expression of the form "source castable as target"
31 *
32 * @param source The source expression
33 * @param target The type being tested against
34 * @param allowEmpty true if an empty sequence is acceptable, that is if the expression
35 * was written as "source castable as target?"
36 */
37
38 public CastableExpression(Expression source, AtomicType target, boolean allowEmpty) {
39 super(source, target, allowEmpty);
40 }
41
42 /**
43 * Type-check the expression
44 */
45
46 /*@NotNull*/
47 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
48 getOperand().typeCheck(visitor, contextInfo);
49
50 // We need to take care here. The usual strategy of wrapping the operand in an expression that
51 // does type-checking doesn't work here, because an error in the type checking should be caught,
52 // while an error in evaluating the expression as written should not.
53
54 Expression operand = getBaseExpression();
55 ItemType sourceItemType = operand.getItemType();
56
57 AtomicType atomizedType = (AtomicType) sourceItemType.getAtomizedItemType().getPrimitiveItemType();
58 if (!(atomizedType == BuiltInAtomicType.ANY_ATOMIC)) {
59 converter = visitor.getConfiguration().getConversionRules().getConverter(atomizedType, getTargetType());
60 if (converter == null) {
61 if (!allowsEmpty() || !Cardinality.allowsZero(operand.getCardinality())) {
62 // Conversion from source to target type will never succeed
63 return Literal.makeLiteral(BooleanValue.FALSE, this);
64 }
65 } else {
66 if (getTargetPrimitiveType().isNamespaceSensitive()) {
67 converter = converter.setNamespaceResolver(getRetainedStaticContext());
68 }
69 if (converter.isAlwaysSuccessful() && !allowsEmpty() && operand.getCardinality() == StaticProperty.ALLOWS_ONE) {
70 return Literal.makeLiteral(BooleanValue.TRUE, this);
71 }
72 }
73 }
74
75 setBaseExpression(operand);
76 if (operand instanceof Literal) {
77 return preEvaluate();
78 }
79
80 return this;
81 }
82
83
84 protected Expression preEvaluate() throws XPathException {
85 GroundedValue literalOperand = ((Literal) getBaseExpression()).getValue();
86 if (literalOperand instanceof AtomicValue && converter != null) {
87 ConversionResult result = converter.convert((AtomicValue) literalOperand);
88 return Literal.makeLiteral(BooleanValue.get(!(result instanceof ValidationFailure)), this);
89 }
90 final int length = literalOperand.getLength();
91 if (length == 0) {
92 return Literal.makeLiteral(BooleanValue.get(allowsEmpty()), this);
93 }
94 if (length > 1) {
95 return Literal.makeLiteral(BooleanValue.FALSE, this);
96 }
97 return this;
98 }
99
100 /**
101 * Optimize the expression
102 */
103
104 /*@NotNull*/
105 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
106 optimizeChildren(visitor, contextInfo);
107 if (getBaseExpression() instanceof Literal) {
108 return preEvaluate();
109 }
110 return this;
111 }
112
113 /**
114 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
115 * This method indicates which of these methods is provided directly. The other methods will always be available
116 * indirectly, using an implementation that relies on one of the other methods.
117 *
118 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
119 * {@link #PROCESS_METHOD}
120 */
121 @Override
122 public int getImplementationMethod() {
123 return EVALUATE_METHOD;
124 }
125
126 /**
127 * Is this expression the same as another expression?
128 */
129
130 public boolean equals(Object other) {
131 return other instanceof CastableExpression &&
132 getBaseExpression().isEqual(((CastableExpression) other).getBaseExpression()) &&
133 getTargetType() == ((CastableExpression) other).getTargetType() &&
134 allowsEmpty() == ((CastableExpression) other).allowsEmpty();
135 }
136
137 /**
138 * get HashCode for comparing two expressions. Note that this hashcode gives the same
139 * result for (A op B) and for (B op A), whether or not the operator is commutative.
140 */
141
142 @Override
143 public int computeHashCode() {
144 return super.computeHashCode() ^ 0x5555;
145 }
146
147 /**
148 * Determine the data type of the result of the Castable expression
149 */
150
151 /*@NotNull*/
152 public ItemType getItemType() {
153 return BuiltInAtomicType.BOOLEAN;
154 }
155
156 /**
157 * Get the static type of the expression as a UType, following precisely the type
158 * inference rules defined in the XSLT 3.0 specification.
159 *
160 * @return the static item type of the expression according to the XSLT 3.0 defined rules
161 * @param contextItemType
162 */
163 @Override
164 public UType getStaticUType(UType contextItemType) {
165 return UType.BOOLEAN;
166 }
167
168
169 public int computeCardinality() {
170 return StaticProperty.EXACTLY_ONE;
171 }
172
173 /*@NotNull*/
174 public Expression copy(RebindingMap rebindings) {
175 CastableExpression ce = new CastableExpression(getBaseExpression().copy(rebindings), getTargetType(), allowsEmpty());
176 ExpressionTool.copyLocationInfo(this, ce);
177 ce.setRetainedStaticContext(getRetainedStaticContext());
178 ce.converter = converter;
179 return ce;
180 }
181
182 /**
183 * Evaluate the expression
184 */
185
186 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
187 return BooleanValue.get(effectiveBooleanValue(context));
188 }
189
190 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
191 // This method does its own atomization so that it can distinguish between atomization
192 // failures and casting failures
193 int count = 0;
194 SequenceIterator iter = getBaseExpression().iterate(context);
195 Item item;
196 while ((item = iter.next()) != null) {
197 if (item instanceof NodeInfo) {
198 AtomicSequence atomizedValue = item.atomize();
199 int length = SequenceTool.getLength(atomizedValue);
200 count += length;
201 if (count > 1) {
202 return false;
203 }
204 if (length != 0) {
205 AtomicValue av = atomizedValue.head();
206 if (!isCastable(av, getTargetType(), context)) {
207 return false;
208 }
209 }
210 } else if (item instanceof AtomicValue) {
211 AtomicValue av = (AtomicValue) item;
212 count++;
213 if (count > 1) {
214 return false;
215 }
216 if (!isCastable(av, getTargetType(), context)) {
217 return false;
218 }
219 } else {
220 throw new XPathException("Input to cast cannot be atomized", "XPTY0004");
221 }
222 }
223 return count != 0 || allowsEmpty();
224 }
225
226 /**
227 * Determine whether a value is castable to a given type
228 *
229 * @param value the value to be tested
230 * @param targetType the type to be tested against
231 * @param context XPath dynamic context
232 * @return true if the value is castable to the required type
233 */
234
235 private boolean isCastable(AtomicValue value, AtomicType targetType, XPathContext context) {
236 Converter converter = this.converter;
237 if (converter == null) {
238 converter = context.getConfiguration().getConversionRules().getConverter(value.getPrimitiveType(), targetType);
239 if (converter == null) {
240 return false;
241 }
242 if (converter.isAlwaysSuccessful()) {
243 return true;
244 }
245 if (getTargetType().isNamespaceSensitive()) {
246 converter = converter.setNamespaceResolver(getRetainedStaticContext());
247 }
248 }
249 return !(converter.convert(value) instanceof ValidationFailure);
250 }
251
252 public String getExpressionName() {
253 return "castable";
254 }
255
256 /**
257 * The toString() method for an expression attempts to give a representation of the expression
258 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
259 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
260 */
261
262 public String toString() {
263 return getBaseExpression().toString() + " castable as " + getTargetType().getEQName();
264 }
265
266
267 /**
268 * Diagnostic print of expression structure. The abstract expression tree
269 * is written to the supplied output destination.
270 */
271
272 public void export(ExpressionPresenter out) throws XPathException {
273 out.startElement("castable", this);
274 out.emitAttribute("as", getTargetType().toExportString());
275 out.emitAttribute("emptiable", allowsEmpty() ? "1" : "0");
276 getBaseExpression().export(out);
277 out.endElement();
278 }
279
280 }
281