Debian Codegraph @

net/sf/saxon/expr/InstanceOfExpression.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.Item;
15 import net.sf.saxon.om.SequenceIterator;
16 import net.sf.saxon.pattern.DocumentNodeTest;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.type.BuiltInAtomicType;
20 import net.sf.saxon.type.ItemType;
21 import net.sf.saxon.type.TypeHierarchy;
22 import net.sf.saxon.type.UType;
23 import net.sf.saxon.value.BooleanValue;
24 import net.sf.saxon.value.Cardinality;
25 import net.sf.saxon.value.SequenceType;
26
27 /**
28 * InstanceOf Expression: implements "Expr instance of data-type"
29 */
30
31 public final class InstanceOfExpression extends UnaryExpression {
32
33 ItemType targetType;
34 int targetCardinality;
35
36 /**
37 * Construct an "instance of" expression in the form "source instance of target"
38 *
39 * @param source the expression whose type is to be tested
40 * @param target the type against which it is tested
41 */
42
43 public InstanceOfExpression(Expression source, SequenceType target) {
44 super(source);
45 targetType = target.getPrimaryType();
46 if (targetType == null) {
47 throw new IllegalArgumentException("Primary item type must not be null");
48 }
49 targetCardinality = target.getCardinality();
50 }
51
52 protected OperandRole getOperandRole() {
53 return targetType instanceof DocumentNodeTest ?
54 OperandRole.ABSORB : OperandRole.INSPECT;
55 }
56
57 /**
58 * Get the item type that we are testing for membership of
59 *
60 * @return the item type
61 */
62
63 public ItemType getRequiredItemType() {
64 return targetType;
65 }
66
67 /**
68 * Get the cardinality that we are testing for membership of
69 *
70 * @return the required cardinality
71 */
72
73 public int getRequiredCardinality() {
74 return targetCardinality;
75 }
76
77 /**
78 * Type-check the expression
79 *
80 * @return the checked expression
81 */
82
83 /*@NotNull*/
84 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
85 getOperand().typeCheck(visitor, contextInfo);
86 Expression operand = getBaseExpression();
87 if (operand instanceof Literal) {
88 Literal lit = Literal.makeLiteral(
89 evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()), this);
90 ExpressionTool.copyLocationInfo(this, lit);
91 return lit;
92 }
93
94 // See if we can get the answer by static analysis.
95
96 if (Cardinality.subsumes(targetCardinality, operand.getCardinality())) {
97 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
98 int relation = th.relationship(operand.getItemType(), targetType);
99 if (relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMED_BY) {
100 Literal lit = Literal.makeLiteral(BooleanValue.TRUE, this);
101 ExpressionTool.copyLocationInfo(this, lit);
102 return lit;
103 } else if (relation == TypeHierarchy.DISJOINT) {
104 // if the item types are disjoint, the result might still be true if both sequences are empty
105 if (!Cardinality.allowsZero(targetCardinality) || !Cardinality.allowsZero(operand.getCardinality())) {
106 Literal lit = Literal.makeLiteral(BooleanValue.FALSE, this);
107 ExpressionTool.copyLocationInfo(this, lit);
108 return lit;
109 }
110 }
111 } else if ((targetCardinality & operand.getCardinality()) == 0) {
112 Literal lit = Literal.makeLiteral(BooleanValue.FALSE, this);
113 ExpressionTool.copyLocationInfo(this, lit);
114 return lit;
115 }
116 return this;
117 }
118
119 /**
120 * Perform optimisation of an expression and its subexpressions.
121 * <p>This method is called after all references to functions and variables have been resolved
122 * to the declaration of the function or variable, and after all type checking has been done.</p>
123 *
124 * @param visitor an expression visitor
125 * @param contextInfo the static type of "." at the point where this expression is invoked.
126 * The parameter is set to null if it is known statically that the context item will be undefined.
127 * If the type of the context item is not known statically, the argument is set to
128 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
129 * @return the original expression, rewritten if appropriate to optimize execution
130 * @throws XPathException if an error is discovered during this phase
131 * (typically a type error)
132 */
133
134 /*@NotNull*/
135 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
136 Expression e = super.optimize(visitor, contextInfo);
137 if (e != this) {
138 return e;
139 }
140 if (Cardinality.subsumes(targetCardinality, getBaseExpression().getCardinality())) {
141 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
142 int relation = th.relationship(getBaseExpression().getItemType(), targetType);
143 if (relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMED_BY) {
144 return Literal.makeLiteral(BooleanValue.TRUE, this);
145 } else if (relation == TypeHierarchy.DISJOINT) {
146 // if the item types are disjoint, the result might still be true if both sequences are empty
147 if (!Cardinality.allowsZero(targetCardinality) || !Cardinality.allowsZero(getBaseExpression().getCardinality())) {
148 return Literal.makeLiteral(BooleanValue.FALSE, this);
149 }
150 }
151 }
152 return this;
153 }
154
155 /**
156 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
157 * This method indicates which of these methods is provided directly. The other methods will always be available
158 * indirectly, using an implementation that relies on one of the other methods.
159 *
160 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
161 * {@link #PROCESS_METHOD}
162 */
163 @Override
164 public int getImplementationMethod() {
165 return EVALUATE_METHOD;
166 }
167
168 /**
169 * Is this expression the same as another expression?
170 */
171
172 public boolean equals(Object other) {
173 return super.equals(other) &&
174 targetType == ((InstanceOfExpression) other).targetType &&
175 targetCardinality == ((InstanceOfExpression) other).targetCardinality;
176 }
177
178 /**
179 * get HashCode for comparing two expressions. Note that this hashcode gives the same
180 * result for (A op B) and for (B op A), whether or not the operator is commutative.
181 */
182
183 @Override
184 public int computeHashCode() {
185 return super.computeHashCode() ^ targetType.hashCode() ^ targetCardinality;
186 }
187
188 /**
189 * Determine the cardinality
190 */
191
192 public int computeCardinality() {
193 return StaticProperty.EXACTLY_ONE;
194 }
195
196 /**
197 * Copy an expression. This makes a deep copy.
198 *
199 * @return the copy of the original expression
200 * @param rebindings variable references that need to be rebound
201 */
202
203 /*@NotNull*/
204 public Expression copy(RebindingMap rebindings) {
205 InstanceOfExpression exp = new InstanceOfExpression(getBaseExpression().copy(rebindings),
206 SequenceType.makeSequenceType(targetType, targetCardinality));
207 ExpressionTool.copyLocationInfo(this, exp);
208 return exp;
209 }
210
211 /**
212 * Determine the data type of the result of the InstanceOf expression
213 */
214
215 /*@NotNull*/
216 public ItemType getItemType() {
217 return BuiltInAtomicType.BOOLEAN;
218 }
219
220 /**
221 * Get the static type of the expression as a UType, following precisely the type
222 * inference rules defined in the XSLT 3.0 specification.
223 *
224 * @return the static item type of the expression according to the XSLT 3.0 defined rules
225 * @param contextItemType the statically-inferred type of the context item
226 */
227 @Override
228 public UType getStaticUType(UType contextItemType) {
229 return UType.BOOLEAN;
230 }
231
232
233 /**
234 * Evaluate the expression
235 */
236
237 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
238 return BooleanValue.get(effectiveBooleanValue(context));
239 }
240
241 /**
242 * Evaluate the expression as a boolean
243 */
244
245 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
246 SequenceIterator iter = getBaseExpression().iterate(context);
247 return isInstance(iter, context);
248 }
249
250 /**
251 * Here is the method that does the work
252 * @param iter iterator over the operand sequence
253 * @param context dynamic evaluation context
254 * @return true if the operand is an instance of the required type
255 * @throws XPathException if a failure occurs evaluating the operand
256 */
257
258 private boolean isInstance(SequenceIterator iter, XPathContext context) throws XPathException {
259 int count = 0;
260 Item item;
261 while ((item = iter.next()) != null) {
262 count++;
263 if (!targetType.matches(item, context.getConfiguration().getTypeHierarchy())) {
264 iter.close();
265 return false;
266 }
267 if (count == 2 && !Cardinality.allowsMany(targetCardinality)) {
268 iter.close();
269 return false;
270 }
271 }
272 return !(count == 0 && ((targetCardinality & StaticProperty.ALLOWS_ZERO) == 0));
273 }
274
275 /**
276 * Get a name identifying the kind of expression, in terms meaningful to a user.
277 *
278 * @return a name identifying the kind of expression, in terms meaningful to a user.
279 * The name will always be in the form of a lexical XML QName, and should match the name used
280 * in export() output displaying the expression.
281 */
282 @Override
283 public String getExpressionName() {
284 return "instance";
285 }
286
287
288 /**
289 * Diagnostic print of expression structure. The abstract expression tree
290 * is written to the supplied output destination.
291 */
292
293 public void export(ExpressionPresenter out) throws XPathException {
294 out.startElement("instance", this);
295 if (targetCardinality == StaticProperty.ALLOWS_ZERO) {
296 out.emitAttribute("of", "empty-sequence()");
297 } else {
298 out.emitAttribute("of", targetType.toExportString() + Cardinality.getOccurrenceIndicator(targetCardinality));
299 }
300 if ("JS".equals(((ExpressionPresenter.ExportOptions) out.getOptions()).target)) {
301 int targetVersion = ((ExpressionPresenter.ExportOptions) out.getOptions()).targetVersion;
302 out.emitAttribute("jsTest", targetType.generateJavaScriptItemTypeTest(getBaseExpression().getItemType(), targetVersion));
303 }
304 getBaseExpression().export(out);
305 out.endElement();
306 }
307
308 /**
309 * The toString() method for an expression attempts to give a representation of the expression
310 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
311 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
312 */
313 @Override
314 public String toString() {
315 String occ = Cardinality.getOccurrenceIndicator(targetCardinality);
316 return "(" + getBaseExpression().toString() + " instance of " +
317 targetType.toString() + occ + ")";
318 }
319
320 /**
321 * Produce a short string identifying the expression for use in error messages
322 *
323 * @return a short string, sufficient to identify the expression
324 */
325 @Override
326 public String toShortString() {
327 String occ = Cardinality.getOccurrenceIndicator(targetCardinality);
328 return getBaseExpression().toShortString() + " instance of " +
329 targetType.toString() + occ;
330 }
331
332 /**
333 * Get the (partial) name of a class that supports streaming of this kind of expression
334 *
335 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
336 * or null if there is no such class
337 */
338 @Override
339 public String getStreamerName() {
340 return "InstanceOf";
341 }
342 }
343