Debian Codegraph @

net/sf/saxon/expr/ItemChecker.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.event.Receiver;
11 import net.sf.saxon.event.TypeCheckingFilter;
12 import net.sf.saxon.expr.instruct.Block;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.om.SequenceIterator;
16 import net.sf.saxon.pattern.CombinedNodeTest;
17 import net.sf.saxon.pattern.DocumentNodeTest;
18 import net.sf.saxon.pattern.NodeTest;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.type.*;
22 import net.sf.saxon.value.Cardinality;
23 import net.sf.saxon.value.IntegerValue;
24 import net.sf.saxon.value.SequenceType;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29
30 /**
31 * A ItemChecker implements the item type checking of "treat as": that is,
32 * it returns the supplied sequence, checking that all its items are of the correct type
33 */
34
35 public final class ItemChecker extends UnaryExpression {
36
37 private ItemType requiredItemType;
38 private RoleDiagnostic role;
39
40 /**
41 * Constructor
42 *
43 * @param sequence the expression whose value we are checking
44 * @param itemType the required type of the items in the sequence
45 * @param role information used in constructing an error message
46 */
47
48 public ItemChecker(Expression sequence, ItemType itemType, RoleDiagnostic role) {
49 super(sequence);
50 requiredItemType = itemType;
51 this.role = role;
52 //adoptChildExpression(sequence);
53 }
54
55 /**
56 * Get the required type
57 *
58 * @return the required type of the items in the sequence
59 */
60
61 public ItemType getRequiredType() {
62 return requiredItemType;
63 }
64
65 protected OperandRole getOperandRole() {
66 return OperandRole.SAME_FOCUS_ACTION;
67 }
68
69 /**
70 * Get the RoleLocator (used to construct error messages)
71 *
72 * @return the RoleLocator
73 */
74
75 public RoleDiagnostic getRoleLocator() {
76 return role;
77 }
78
79 /**
80 * Simplify an expression
81 *
82 */
83
84 /*@NotNull*/
85 public Expression simplify() throws XPathException {
86 Expression operand = getBaseExpression().simplify();
87 if (requiredItemType instanceof AnyItemType) {
88 return operand;
89 }
90 setBaseExpression(operand);
91 return this;
92 }
93
94 /**
95 * Type-check the expression
96 */
97
98 /*@NotNull*/
99 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
100 getOperand().typeCheck(visitor, contextInfo);
101 Expression operand = getBaseExpression();
102
103 if (operand instanceof Block) {
104 // Do the item-checking on each operand of the block separately (it might not be needed on all items)
105 // This is particularly needed for streamability analysis of xsl:map
106 Block block = (Block)operand;
107 List<Expression> checkedOperands = new ArrayList<>();
108 for (Operand o : block.operands()) {
109 ItemChecker checkedOp = new ItemChecker(o.getChildExpression(), requiredItemType, role);
110 checkedOperands.add(checkedOp);
111 }
112 Block newBlock = new Block(checkedOperands.toArray(new Expression[0]));
113 ExpressionTool.copyLocationInfo(this, newBlock);
114 return newBlock.typeCheck(visitor, contextInfo);
115 }
116 // When typeCheck is called a second time, we might have more information...
117
118 final TypeHierarchy th = getConfiguration().getTypeHierarchy();
119 int card = operand.getCardinality();
120 if (card == StaticProperty.EMPTY) {
121 //value is always empty, so no item checking needed
122 return operand;
123 }
124 ItemType supplied = operand.getItemType();
125 int relation = th.relationship(requiredItemType, supplied);
126 if (relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMES) {
127 return operand;
128 } else if (relation == TypeHierarchy.DISJOINT) {
129 if (requiredItemType.equals(BuiltInAtomicType.STRING) && th.isSubType(supplied, BuiltInAtomicType.ANY_URI)) {
130 // URI promotion will take care of this at run-time
131 return operand;
132 } else if (Cardinality.allowsZero(card)) {
133 if (!(operand instanceof Literal)) {
134 String message = role.composeErrorMessage(
135 requiredItemType, operand, th);
136 visitor.getStaticContext().issueWarning(
137 "The only value that can pass type-checking is an empty sequence. " +
138 message, getLocation());
139 }
140 } else {
141 String message = role.composeErrorMessage(requiredItemType, operand, th);
142 XPathException err = new XPathException(message);
143 err.setErrorCode(role.getErrorCode());
144 err.setLocation(this.getLocation());
145 err.setIsTypeError(role.isTypeError());
146 throw err;
147 }
148 }
149 return this;
150 }
151
152 /**
153 * Perform optimisation of an expression and its subexpressions.
154 * <p>This method is called after all references to functions and variables have been resolved
155 * to the declaration of the function or variable, and after all type checking has been done.</p>
156 *
157 * @param visitor an expression visitor
158 * @param contextInfo the static type of "." at the point where this expression is invoked.
159 * The parameter is set to null if it is known statically that the context item will be undefined.
160 * If the type of the context item is not known statically, the argument is set to
161 * {@link Type#ITEM_TYPE}
162 * @return the original expression, rewritten if appropriate to optimize execution
163 * @throws XPathException if an error is discovered during this phase
164 * (typically a type error)
165 */
166 @Override
167 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
168 getOperand().optimize(visitor, contextInfo);
169 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
170 int rel = th.relationship(requiredItemType, getBaseExpression().getItemType());
171 if (rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMES) {
172 return getBaseExpression();
173 }
174 return this;
175 }
176
177 /**
178 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
179 * This method indicates which of these methods is provided. This implementation provides both iterate() and
180 * process() methods natively.
181 */
182
183 public int getImplementationMethod() {
184 int m = ITERATE_METHOD | PROCESS_METHOD | ITEM_FEED_METHOD;
185 if (!Cardinality.allowsMany(getCardinality())) {
186 m |= EVALUATE_METHOD;
187 }
188 return m;
189 }
190
191 /**
192 * Get the (partial) name of a class that supports streaming of this kind of expression
193 *
194 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
195 * or null if there is no such class
196 */
197 @Override
198 public String getStreamerName() {
199 return "ItemChecker";
200 }
201
202 /**
203 * For an expression that returns an integer or a sequence of integers, get
204 * a lower and upper bound on the values of the integers that may be returned, from
205 * static analysis. The default implementation returns null, meaning "unknown" or
206 * "not applicable". Other implementations return an array of two IntegerValue objects,
207 * representing the lower and upper bounds respectively. The values
208 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
209 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
210 * are used to indicate values limited by the size of a string or the size of a sequence.
211 *
212 * @return the lower and upper bounds of integer values in the result, or null to indicate
213 * unknown or not applicable.
214 */
215 /*@Nullable*/
216 @Override
217 public IntegerValue[] getIntegerBounds() {
218 return getBaseExpression().getIntegerBounds();
219 }
220
221 /**
222 * Iterate over the sequence of values
223 */
224
225 /*@NotNull*/
226 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
227 SequenceIterator<?> base = getBaseExpression().iterate(context);
228 return new ItemMappingIterator<>(base, getMappingFunction(context), true);
229 }
230
231 /**
232 * Get the mapping function used to implement this item check. This mapping function is applied
233 * to each item in the input sequence.
234 *
235 * @param context The dynamic context used to evaluate the mapping function
236 * @return the mapping function. This will be an identity mapping: the output sequence is the same
237 * as the input sequence, unless the dynamic type checking reveals an error.
238 */
239
240 public ItemMappingFunction<Item<?>, Item<?>> getMappingFunction(XPathContext context) {
241 return new ItemTypeCheckingFunction(requiredItemType, role, getBaseExpression(), context.getConfiguration());
242 }
243
244 /**
245 * Evaluate as an Item.
246 */
247
248 public Item evaluateItem(XPathContext context) throws XPathException {
249 final TypeHierarchy th = context.getConfiguration().getTypeHierarchy();
250 Item item = getBaseExpression().evaluateItem(context);
251 if (item == null) {
252 return null;
253 }
254 if (requiredItemType.matches(item, th)) {
255 return item;
256 } else if (requiredItemType.getUType().subsumes(UType.STRING) && BuiltInAtomicType.ANY_URI.matches(item, th)) {
257 return item;
258 } else {
259 String message = role.composeErrorMessage(requiredItemType, item, th);
260 String errorCode = role.getErrorCode();
261 if ("XPDY0050".equals(errorCode)) {
262 // error in "treat as" assertion
263 dynamicError(message, errorCode, context);
264 } else {
265 typeError(message, errorCode, context);
266 }
267 return null;
268 }
269 }
270
271 /**
272 * Process the instruction, without returning any tail calls
273 *
274 * @param context The dynamic context, giving access to the current node,
275 * the current variables, etc.
276 */
277
278 public void process(XPathContext context) throws XPathException {
279 Expression next = getBaseExpression();
280 int card = StaticProperty.ALLOWS_ZERO_OR_MORE;
281 if (next instanceof CardinalityChecker) {
282 card = ((CardinalityChecker) next).getRequiredCardinality();
283 next = ((CardinalityChecker) next).getBaseExpression();
284 }
285 if ((next.getImplementationMethod() & PROCESS_METHOD) != 0 && !(requiredItemType instanceof DocumentNodeTest)) {
286 Receiver out = context.getReceiver();
287 TypeCheckingFilter filter = new TypeCheckingFilter(out);
288 filter.setRequiredType(requiredItemType, card, role, getLocation());
289 context.setReceiver(filter);
290 next.process(context);
291 filter.close();
292 context.setReceiver(out);
293 } else {
294 // Force pull-mode evaluation
295 super.process(context);
296 }
297 }
298
299 /**
300 * Copy an expression. This makes a deep copy.
301 *
302 * @return the copy of the original expression
303 * @param rebindings variable bindings that need to be changed
304 */
305
306 /*@NotNull*/
307 public Expression copy(RebindingMap rebindings) {
308 ItemChecker exp = new ItemChecker(getBaseExpression().copy(rebindings), requiredItemType, role);
309 ExpressionTool.copyLocationInfo(this, exp);
310 return exp;
311 }
312
313
314 /**
315 * Determine the data type of the items returned by the expression
316 */
317
318 /*@NotNull*/
319 public ItemType getItemType() {
320 ItemType operandType = getBaseExpression().getItemType();
321 TypeHierarchy th = getConfiguration().getTypeHierarchy();
322 int relationship = th.relationship(requiredItemType, operandType);
323 switch (relationship) {
324 case TypeHierarchy.OVERLAPS:
325 if (requiredItemType instanceof NodeTest && operandType instanceof NodeTest) {
326 return new CombinedNodeTest((NodeTest) requiredItemType, Token.INTERSECT, (NodeTest) operandType);
327 } else {
328 // we don't know how to intersect atomic types, it doesn't actually happen
329 return requiredItemType;
330 }
331
332 case TypeHierarchy.SUBSUMES:
333 case TypeHierarchy.SAME_TYPE:
334 // shouldn't happen, but it doesn't matter
335 return operandType;
336 case TypeHierarchy.SUBSUMED_BY:
337 default:
338 return requiredItemType;
339 }
340 }
341
342 /**
343 * Get the static type of the expression as a UType, following precisely the type
344 * inference rules defined in the XSLT 3.0 specification.
345 *
346 * @return the static item type of the expression according to the XSLT 3.0 defined rules
347 * @param contextItemType the type of the context item
348 */
349 @Override
350 public UType getStaticUType(UType contextItemType) {
351 return UType.fromTypeCode(requiredItemType.getPrimitiveType());
352 }
353
354 /**
355 * Is this expression the same as another expression?
356 */
357
358 public boolean equals(Object other) {
359 return super.equals(other) &&
360 requiredItemType == ((ItemChecker) other).requiredItemType;
361 }
362
363 /**
364 * get HashCode for comparing two expressions. Note that this hashcode gives the same
365 * result for (A op B) and for (B op A), whether or not the operator is commutative.
366 */
367
368 @Override
369 public int computeHashCode() {
370 return super.computeHashCode() ^ requiredItemType.hashCode();
371 }
372
373
374 /**
375 * Diagnostic print of expression structure. The abstract expression tree
376 * is written to the supplied output destination.
377 */
378
379 public void export(ExpressionPresenter out) throws XPathException {
380 out.startElement("treat", this);
381 out.emitAttribute("as", requiredItemType.toExportString());
382 ExpressionPresenter.ExportOptions options = (ExpressionPresenter.ExportOptions) out.getOptions();
383 if ("JS".equals(options.target)) {
384 int targetVersion = options.targetVersion;
385 out.emitAttribute("jsTest", requiredItemType.generateJavaScriptItemTypeTest(getBaseExpression().getItemType(), targetVersion));
386 if (targetVersion == 2) {
387 SequenceType st = SequenceType.makeSequenceType(requiredItemType, StaticProperty.EXACTLY_ONE);
388 out.emitAttribute("asJ", st.toExportString2());
389 }
390 }
391 out.emitAttribute("diag", role.save());
392 getBaseExpression().export(out);
393 out.endElement();
394 }
395
396 /**
397 * Get a name identifying the kind of expression, in terms meaningful to a user.
398 *
399 * @return a name identifying the kind of expression, in terms meaningful to a user.
400 * The name will always be in the form of a lexical XML QName, and should match the name used
401 * in explain() output displaying the expression.
402 */
403
404 public String getExpressionName() {
405 return "treatAs";
406 }
407
408 /**
409 * The toString() method for an expression attempts to give a representation of the expression
410 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
411 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
412 */
413
414 public String toString() {
415 String typeDesc = requiredItemType.toString();
416 return "(" + getBaseExpression() + ") treat as " + typeDesc;
417 }
418
419 @Override
420 public String toShortString() {
421 return getBaseExpression().toShortString();
422 }
423
424 }
425
426