Debian Codegraph @

net/sf/saxon/expr/AtomicSequenceConverter.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.Configuration;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.lib.ConversionRules;
13 import net.sf.saxon.om.GroundedValue;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.om.SequenceIterator;
16 import net.sf.saxon.trace.ExpressionPresenter;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.type.*;
19 import net.sf.saxon.value.AtomicValue;
20 import net.sf.saxon.value.StringValue;
21
22
23 /**
24 * An AtomicSequenceConverter is an expression that performs a cast on each member of
25 * a supplied sequence
26 */
27
28 public class AtomicSequenceConverter extends UnaryExpression {
29
30 public static ToStringMappingFunction TO_STRING_MAPPER = new ToStringMappingFunction();
31
32 private PlainType requiredItemType;
33 protected Converter converter;
34 private RoleDiagnostic roleDiagnostic; // may be null
35
36
37 /**
38 * Constructor
39 *
40 * @param sequence this must be a sequence of atomic values. This is not checked; a ClassCastException
41 * will occur if the precondition is not satisfied.
42 * @param requiredItemType the item type to which all items in the sequence should be converted,
43 */
44
45 public AtomicSequenceConverter(Expression sequence, PlainType requiredItemType) {
46 super(sequence);
47 this.requiredItemType = requiredItemType;
48 }
49
50 public void allocateConverterStatically(Configuration config, boolean allowNull) {
51 converter = allocateConverter(config, allowNull, getBaseExpression().getItemType());
52 }
53
54 public Converter allocateConverter(Configuration config, boolean allowNull) {
55 return allocateConverter(config, allowNull, getBaseExpression().getItemType());
56 }
57
58 protected Converter getConverterDynamically(XPathContext context) {
59 if (converter != null) {
60 return converter;
61 }
62 return allocateConverter(context.getConfiguration(), false);
63 }
64
65 public Converter allocateConverter(Configuration config, boolean allowNull, ItemType sourceType) {
66 final ConversionRules rules = config.getConversionRules();
67 Converter converter = null;
68 if (sourceType instanceof ErrorType) {
69 converter = StringConverter.IdentityConverter.INSTANCE;
70 } else if (!(sourceType instanceof AtomicType)) {
71 converter = null;
72 } else if (requiredItemType instanceof AtomicType) {
73 converter = rules.getConverter((AtomicType) sourceType, (AtomicType) requiredItemType);
74 } else if (((SimpleType) requiredItemType).isUnionType()) {
75 converter = new StringConverter.StringToUnionConverter(requiredItemType, rules);
76 }
77
78 if (converter == null && !allowNull) {
79 // source type not known statically; create a converter that decides at run-time
80 converter = new Converter(rules) {
81 /*@NotNull*/
82 public ConversionResult convert(/*@NotNull*/ AtomicValue input) {
83 Converter converter = rules.getConverter(input.getPrimitiveType(), (AtomicType) requiredItemType);
84 if (converter == null) {
85 return new ValidationFailure("Cannot convert value from " + input.getPrimitiveType() + " to " + requiredItemType);
86 } else {
87 return converter.convert(input);
88 }
89 }
90 };
91 }
92 return converter;
93 }
94
95 protected OperandRole getOperandRole() {
96 return OperandRole.ATOMIC_SEQUENCE;
97 }
98
99 /**
100 * Get the required item type (the target type of the conversion
101 *
102 * @return the required item type
103 */
104
105 public PlainType getRequiredItemType() {
106 return requiredItemType;
107 }
108
109 /**
110 * Get the converter used to convert the items in the sequence
111 *
112 * @return the converter. Note that a converter is always allocated during the typeCheck() phase,
113 * even if the source type is not known.
114 */
115
116 public Converter getConverter() {
117 return converter;
118 }
119
120 public void setConverter(Converter converter) {
121 this.converter = converter;
122 }
123
124
125 /**
126 * Set a RoleDiagnostic, used to give more precise error information if the conversion
127 * fails
128 *
129 * @param role the RoleDiagnostic, which gives more precise error information
130 */
131
132 public void setRoleDiagnostic(RoleDiagnostic role) {
133 // TODO: pragmatic kludge in the run-up to 9.9. If the role says error=XPTY0004, ignore it, because
134 // in XQuery the cast failure should be FORG0001. We only use the error code in XSLT paths where it
135 // might be something like XTTE0780
136 if (role != null && !"XPTY0004".equals(role.getErrorCode())) {
137 this.roleDiagnostic = role;
138 }
139 }
140
141 /**
142 * Get the RoleDiagnostic, used to give more precise error information if the conversion
143 * fails
144 *
145 * @return the RoleDiagnostic, or null if none has been set
146 */
147
148 public RoleDiagnostic getRoleDiagnostic() {
149 return this.roleDiagnostic;
150 }
151
152
153 /**
154 * Simplify an expression
155 *
156 */
157
158 /*@NotNull*/
159 public Expression simplify() throws XPathException {
160 Expression operand = getBaseExpression().simplify();
161 setBaseExpression(operand);
162 if (operand instanceof Literal && requiredItemType instanceof AtomicType) {
163 if (Literal.isEmptySequence(operand)) {
164 return operand;
165 }
166 Configuration config = getConfiguration();
167 allocateConverterStatically(config, true);
168 if (converter != null) {
169 GroundedValue<?> val = iterate(new EarlyEvaluationContext(config)).materialize();
170 return Literal.makeLiteral(val, operand);
171 }
172 }
173 return this;
174 }
175
176 /**
177 * Type-check the expression
178 */
179
180 /*@NotNull*/
181 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
182 typeCheckChildren(visitor, contextInfo);
183 Configuration config = visitor.getConfiguration();
184 final TypeHierarchy th = config.getTypeHierarchy();
185 Expression operand = getBaseExpression();
186 if (th.isSubType(operand.getItemType(), requiredItemType)) {
187 return operand;
188 } else {
189 if (converter == null) {
190 allocateConverterStatically(config, true);
191 }
192 return this;
193 }
194 }
195
196 /**
197 * Perform optimisation of an expression and its subexpressions.
198 */
199 /*@NotNull*/
200 @Override
201 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
202 Expression e = super.optimize(visitor, contextInfo);
203 if (e != this) {
204 return e;
205 }
206 if (getBaseExpression() instanceof UntypedSequenceConverter) {
207 UntypedSequenceConverter asc = (UntypedSequenceConverter) getBaseExpression();
208 ItemType ascType = asc.getItemType();
209 if (ascType == requiredItemType) {
210 return getBaseExpression();
211 } else if ((requiredItemType == BuiltInAtomicType.STRING || requiredItemType == BuiltInAtomicType.UNTYPED_ATOMIC) &&
212 (ascType == BuiltInAtomicType.STRING || ascType == BuiltInAtomicType.UNTYPED_ATOMIC)) {
213 UntypedSequenceConverter old = (UntypedSequenceConverter) getBaseExpression();
214 UntypedSequenceConverter asc2 = new UntypedSequenceConverter(
215 old.getBaseExpression(),
216 requiredItemType);
217 return asc2.typeCheck(visitor, contextInfo)
218 .optimize(visitor, contextInfo);
219 }
220 } else if (getBaseExpression() instanceof AtomicSequenceConverter) {
221 AtomicSequenceConverter asc = (AtomicSequenceConverter) getBaseExpression();
222 ItemType ascType = asc.getItemType();
223 if (ascType == requiredItemType) {
224 return getBaseExpression();
225 } else if ((requiredItemType == BuiltInAtomicType.STRING || requiredItemType == BuiltInAtomicType.UNTYPED_ATOMIC) &&
226 (ascType == BuiltInAtomicType.STRING || ascType == BuiltInAtomicType.UNTYPED_ATOMIC)) {
227 AtomicSequenceConverter old = (AtomicSequenceConverter) getBaseExpression();
228 AtomicSequenceConverter asc2 = new AtomicSequenceConverter(
229 old.getBaseExpression(),
230 requiredItemType
231 );
232 return asc2.typeCheck(visitor, contextInfo)
233 .optimize(visitor, contextInfo);
234 }
235 }
236 return this;
237
238 }
239
240 /**
241 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
242 * This method indicates which of these methods is provided directly. The other methods will always be available
243 * indirectly, using an implementation that relies on one of the other methods.
244 *
245 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
246 * {@link #PROCESS_METHOD}
247 */
248 @Override
249 public int getImplementationMethod() {
250 return ITERATE_METHOD;
251 }
252
253 /**
254 * Determine the special properties of this expression
255 *
256 * @return {@link StaticProperty#NO_NODES_NEWLY_CREATED}.
257 */
258
259 public int computeSpecialProperties() {
260 int p = super.computeSpecialProperties() | StaticProperty.NO_NODES_NEWLY_CREATED;
261 if (requiredItemType == BuiltInAtomicType.UNTYPED_ATOMIC) {
262 p &= ~StaticProperty.NOT_UNTYPED_ATOMIC;
263 } else {
264 p |= StaticProperty.NOT_UNTYPED_ATOMIC;
265 }
266 return p;
267 }
268
269
270 @Override
271 public String getStreamerName() {
272 return "AtomicSequenceConverter";
273 }
274
275 /**
276 * Copy an expression. This makes a deep copy.
277 *
278 * @return the copy of the original expression
279 * @param rebindings variables that need to be re-bound
280 */
281
282 /*@NotNull*/
283 public Expression copy(RebindingMap rebindings) {
284 AtomicSequenceConverter atomicConverter = new AtomicSequenceConverter(getBaseExpression().copy(rebindings), requiredItemType);
285 ExpressionTool.copyLocationInfo(this, atomicConverter);
286 atomicConverter.setConverter(converter);
287 atomicConverter.setRoleDiagnostic(getRoleDiagnostic());
288 return atomicConverter;
289 }
290
291 /**
292 * Iterate over the sequence of values
293 */
294
295 /*@NotNull*/
296 public SequenceIterator<? extends AtomicValue> iterate(final XPathContext context) throws XPathException {
297 SequenceIterator<?> base = getBaseExpression().iterate(context);
298 Converter conv = getConverterDynamically(context);
299 if (conv == Converter.ToStringConverter.INSTANCE) {
300 return new ItemMappingIterator<>(base, TO_STRING_MAPPER, true);
301 } else {
302 AtomicSequenceMappingFunction mapper = new AtomicSequenceMappingFunction();
303 mapper.setConverter(conv);
304 if (roleDiagnostic != null) {
305 mapper.setErrorCode(roleDiagnostic.getErrorCode());
306 }
307 return new ItemMappingIterator<>((SequenceIterator<? extends AtomicValue>)base, mapper, true);
308 }
309 }
310
311 /**
312 * Mapping function wrapped around a converter
313 */
314
315 public static class AtomicSequenceMappingFunction implements ItemMappingFunction<AtomicValue, AtomicValue> {
316 private Converter converter;
317 private String errorCode;
318
319 public void setConverter(Converter converter) {
320 this.converter = converter;
321 }
322
323 public void setErrorCode(String code) {
324 this.errorCode = code;
325 }
326
327 public AtomicValue mapItem(AtomicValue item) throws XPathException {
328 ConversionResult result = converter.convert(item);
329 if (errorCode != null && result instanceof ValidationFailure) {
330 ((ValidationFailure)result).setErrorCode(errorCode);
331 }
332 return result.asAtomic();
333 }
334 }
335
336 /**
337 * Mapping function that converts every item in a sequence to a string
338 */
339
340 public static class ToStringMappingFunction
341 implements ItemMappingFunction<Item<?>, StringValue> {
342 public StringValue mapItem(Item<?> item) {
343 return StringValue.makeStringValue(item.getStringValueCS());
344 }
345 }
346
347
348 /**
349 * Evaluate as an Item. This should only be called if the AtomicSequenceConverter has cardinality zero-or-one
350 */
351
352 public AtomicValue evaluateItem(XPathContext context) throws XPathException {
353 Converter conv = getConverterDynamically(context);
354 AtomicValue item = (AtomicValue) getBaseExpression().evaluateItem(context);
355 if (item == null) {
356 return null;
357 }
358 ConversionResult result = conv.convert(item);
359 if (roleDiagnostic != null && result instanceof ValidationFailure) {
360 // TODO: use more of the information in the roleDiagnostic to form the error message
361 ((ValidationFailure)result).setErrorCode(roleDiagnostic.getErrorCode());
362 }
363 return result.asAtomic();
364 }
365
366 /**
367 * Determine the data type of the items returned by the expression, if possible
368 *
369 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE,
370 * or Type.ITEM (meaning not known in advance)
371 */
372
373 /*@NotNull*/
374 public ItemType getItemType() {
375 return requiredItemType;
376 }
377
378 /**
379 * Determine the static cardinality of the expression
380 */
381
382 public int computeCardinality() {
383 return getBaseExpression().getCardinality();
384 }
385
386 /**
387 * Is this expression the same as another expression?
388 */
389
390 public boolean equals(Object other) {
391 return super.equals(other) &&
392 requiredItemType.equals(((AtomicSequenceConverter) other).requiredItemType);
393 }
394
395 /**
396 * get HashCode for comparing two expressions. Note that this hashcode gives the same
397 * result for (A op B) and for (B op A), whether or not the operator is commutative.
398 */
399
400 @Override
401 public int computeHashCode() {
402 return super.computeHashCode() ^ requiredItemType.hashCode();
403 }
404
405
406 /**
407 * Get a name identifying the kind of expression, in terms meaningful to a user.
408 *
409 * @return a name identifying the kind of expression, in terms meaningful to a user.
410 * The name will always be in the form of a lexical XML QName, and should match the name used
411 * in explain() output displaying the expression.
412 */
413 @Override
414 public String getExpressionName() {
415 return "convert";
416 }
417
418 @Override
419 protected String displayOperator(Configuration config) {
420 return "convert";
421 }
422
423 /**
424 * Diagnostic print of expression structure. The abstract expression tree
425 * is written to the supplied output destination.
426 */
427
428 public void export(ExpressionPresenter destination) throws XPathException {
429 destination.startElement("convert", this);
430 destination.emitAttribute("from", getBaseExpression().getItemType().toExportString());
431 destination.emitAttribute("to", requiredItemType.toExportString());
432 if (converter instanceof Converter.PromoterToDouble || converter instanceof Converter.PromoterToFloat) {
433 destination.emitAttribute("flags", "p");
434 }
435 if (getRoleDiagnostic() != null) {
436 destination.emitAttribute("diag", getRoleDiagnostic().save());
437 }
438 getBaseExpression().export(destination);
439 destination.endElement();
440 }
441
442 }
443