Debian Codegraph @

net/sf/saxon/expr/LookupExpression.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.ma.arrays.ArrayItem;
13 import net.sf.saxon.ma.arrays.ArrayItemType;
14 import net.sf.saxon.ma.map.MapItem;
15 import net.sf.saxon.ma.map.MapType;
16 import net.sf.saxon.ma.map.TupleItemType;
17 import net.sf.saxon.ma.map.TupleType;
18 import net.sf.saxon.om.GroundedValue;
19 import net.sf.saxon.om.Item;
20 import net.sf.saxon.om.NameChecker;
21 import net.sf.saxon.om.SequenceIterator;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.SaxonErrorCode;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.tree.iter.EmptyIterator;
26 import net.sf.saxon.type.*;
27 import net.sf.saxon.value.*;
28
29
30 /**
31 * A lookup expression is an expression of the form A?B. Here A must be a sequence of maps or arrays.
32 * In the general case B is an expression that computes a key/index into the map or array; the case where
33 * B is constant needs to be handled efficiently. The class also implements the unary lookup expression
34 * ?B, which is interpreted as .?B. It does not handle the case A?* - that is handled as a LookupAllExpression.
35 */
36
37 public class LookupExpression extends BinaryExpression {
38
39 private boolean isClassified = false;
40 protected boolean isArrayLookup = false;
41 protected boolean isMapLookup = false;
42 protected boolean isSingleContainer = false;
43 protected boolean isSingleEntry = false;
44
45
46 /**
47 * Constructor
48 *
49 * @param start The left hand operand (which must always select a sequence of maps or arrays).
50 * @param step The step to be followed from each map/array in the start expression to yield a new
51 * sequence
52 */
53
54 public LookupExpression(Expression start, Expression step) {
55 super(start, Token.QMARK, step);
56 }
57
58 @Override
59 protected OperandRole getOperandRole(int arg) {
60 return arg == 0 ? OperandRole.INSPECT : OperandRole.ABSORB;
61 }
62
63 @Override
64 public String getExpressionName() {
65 return "lookupExp";
66 }
67
68
69 /**
70 * Determine the data type of the items returned by this expression
71 *
72 * @return the type of the expression, as far as this is known. Prior to type-checking,
73 * the method returns {@link AnyItemType}
74 */
75
76 /*@NotNull*/
77 public ItemType getItemType() {
78 if (isClassified) {
79 if (isArrayLookup) {
80 ItemType arrayType = getLhsExpression().getItemType();
81 if (arrayType instanceof ArrayItemType) {
82 return ((ArrayItemType) arrayType).getMemberType().getPrimaryType();
83 }
84 } else if (isMapLookup) {
85 ItemType mapType = getLhsExpression().getItemType();
86 if (mapType instanceof TupleItemType && getRhsExpression() instanceof StringLiteral) {
87 String fieldName = ((StringLiteral) getRhsExpression()).getStringValue();
88 SequenceType fieldType = ((TupleItemType) mapType).getFieldType(fieldName);
89 return fieldType == null ? ErrorType.getInstance() : fieldType.getPrimaryType();
90 } else if (mapType instanceof MapType) {
91 return ((MapType) mapType).getValueType().getPrimaryType();
92 }
93 }
94 }
95 return AnyItemType.getInstance();
96 }
97
98
99 /**
100 * Get the static type of the expression as a UType, following precisely the type
101 * inference rules defined in the XSLT 3.0 specification.
102 *
103 * @param contextItemType not used
104 * @return the static item type of the expression according to the XSLT 3.0 defined rules
105 */
106 @Override
107 public UType getStaticUType(UType contextItemType) {
108 return getItemType().getUType();
109 }
110
111 /**
112 * Type-check the expression
113 */
114
115 /*@NotNull*/
116 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
117
118 Configuration config = visitor.getConfiguration();
119 TypeHierarchy th = config.getTypeHierarchy();
120
121 // Check the first operand
122 getLhs().typeCheck(visitor, contextInfo);
123
124 ItemType containerType = getLhsExpression().getItemType();
125 isArrayLookup = containerType instanceof ArrayItemType;
126 boolean isTupleLookup = containerType instanceof TupleType;
127 isMapLookup = containerType instanceof MapType || isTupleLookup;
128 if (containerType instanceof AnyExternalObjectType) {
129 config.checkLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION, "use of lookup expressions on external objects", -1);
130 return config.makeObjectLookupExpression(getLhsExpression(), getRhsExpression())
131 .typeCheck(visitor, contextInfo);
132 }
133 isSingleContainer = getLhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE;
134
135 if (!isArrayLookup && !isMapLookup) {
136 if (th.relationship(containerType, MapType.ANY_MAP_TYPE) == TypeHierarchy.DISJOINT &&
137 th.relationship(containerType, ArrayItemType.getInstance()) == TypeHierarchy.DISJOINT &&
138 th.relationship(containerType, AnyExternalObjectType.THE_INSTANCE) == TypeHierarchy.DISJOINT) {
139 XPathException err = new XPathException("The left-hand operand of '?' must be a map or an array; the supplied expression is of type " + containerType, "XPTY0004");
140 err.setLocation(getLocation());
141 err.setIsTypeError(true);
142 err.setFailingExpression(this);
143 throw err;
144 }
145 }
146
147 // Now check the second operand
148
149 getRhs().typeCheck(visitor, contextInfo);
150 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.BINARY_EXPR, "?", 1);
151 TypeChecker tc = config.getTypeChecker(false);
152 SequenceType req = BuiltInAtomicType.ANY_ATOMIC.zeroOrMore();
153 if (isArrayLookup) {
154 req = BuiltInAtomicType.INTEGER.zeroOrMore();
155 }
156 setRhsExpression(tc.staticTypeCheck(getRhsExpression(), req, role, visitor));
157 isSingleEntry = getRhsExpression().getCardinality() == StaticProperty.EXACTLY_ONE;
158
159 if (isTupleLookup && getRhsExpression() instanceof StringLiteral) {
160 String fieldName = ((StringLiteral)getRhsExpression()).getStringValue();
161 if (((TupleType)containerType).getFieldType(fieldName) == null) {
162 XPathException err = new XPathException("Field " + fieldName + " is not defined in the tuple type", SaxonErrorCode.SXTT0001);
163 err.setIsTypeError(true);
164 err.setLocation(getLocation());
165 throw err;
166 }
167 }
168
169 isClassified = true;
170 return this;
171 }
172
173 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
174 getLhs().optimize(visitor, contextInfo);
175 getRhs().optimize(visitor, contextInfo);
176 return this;
177 }
178
179
180 /**
181 * Return the estimated cost of evaluating an expression. This is a very crude measure based
182 * on the syntactic form of the expression (we have no knowledge of data values). We take
183 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
184 * and we assume that a sequence has length 5. The resulting estimates may be used, for
185 * example, to reorder the predicates in a filter expression so cheaper predicates are
186 * evaluated first.
187 */
188 @Override
189 public int getCost() {
190 return getLhsExpression().getCost() * getRhsExpression().getCost();
191 }
192
193 /**
194 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
195 * This method indicates which of these methods is provided directly. The other methods will always be available
196 * indirectly, using an implementation that relies on one of the other methods.
197 *
198 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
199 * {@link #PROCESS_METHOD}
200 */
201 @Override
202 public int getImplementationMethod() {
203 return ITERATE_METHOD;
204 }
205
206
207 /**
208 * Copy an expression. This makes a deep copy.
209 *
210 * @param rebindings a mutable list of (old binding, new binding) pairs
211 * that is used to update the bindings held in any
212 * local variable references that are copied.
213 * @return the copy of the original expression
214 */
215
216 /*@NotNull*/
217 public LookupExpression copy(RebindingMap rebindings) {
218 LookupExpression exp = new LookupExpression(getLhsExpression().copy(rebindings), getRhsExpression().copy(rebindings));
219 ExpressionTool.copyLocationInfo(this, exp);
220 exp.isArrayLookup = isArrayLookup;
221 exp.isMapLookup = isMapLookup;
222 exp.isSingleEntry = isSingleEntry;
223 exp.isSingleContainer = isSingleContainer;
224 return exp;
225 }
226
227
228 /**
229 * Determine the static cardinality of the expression
230 */
231
232 public int computeCardinality() {
233 if (isSingleContainer && isSingleEntry) {
234 if (isArrayLookup) {
235 ItemType arrayType = getLhsExpression().getItemType();
236 if (arrayType instanceof ArrayItemType) {
237 return ((ArrayItemType) arrayType).getMemberType().getCardinality();
238 }
239 } else if (isMapLookup) {
240 ItemType mapType = getLhsExpression().getItemType();
241 if (mapType instanceof TupleItemType && getRhsExpression() instanceof StringLiteral) {
242 String fieldName = ((StringLiteral) getRhsExpression()).getStringValue();
243 SequenceType fieldType = ((TupleItemType) mapType).getFieldType(fieldName);
244 boolean isOptional = ((TupleItemType) mapType).isOptional(fieldName);
245 int card = fieldType.getCardinality();
246 if (isOptional) {
247 card = Cardinality.union(card, StaticProperty.ALLOWS_ZERO);
248 }
249 return fieldType == null ? StaticProperty.ALLOWS_ZERO : card;
250 } else if (mapType instanceof MapType) {
251 return ((MapType) mapType).getValueType().getCardinality();
252 }
253 }
254 }
255 return StaticProperty.ALLOWS_ZERO_OR_MORE;
256 }
257
258 /**
259 * Is this expression the same as another expression?
260 */
261
262 public boolean equals(Object other) {
263 if (!(other instanceof LookupExpression)) {
264 return false;
265 }
266 LookupExpression p = (LookupExpression) other;
267 return getLhsExpression().isEqual(p.getLhsExpression()) && getRhsExpression().isEqual(p.getRhsExpression());
268 }
269
270 /**
271 * get HashCode for comparing two expressions
272 */
273
274 public int computeHashCode() {
275 return "LookupExpression".hashCode() ^ getLhsExpression().hashCode() ^ getRhsExpression().hashCode();
276 }
277
278 /**
279 * Iterate the lookup-expression in a given context
280 *
281 * @param context the evaluation context
282 */
283
284 /*@NotNull*/
285 public SequenceIterator<?> iterate(final XPathContext context) throws XPathException {
286 Configuration config = context.getConfiguration();
287 if (isArrayLookup) {
288 if (isSingleContainer && isSingleEntry) {
289 ArrayItem array = (ArrayItem) getLhsExpression().evaluateItem(context);
290 IntegerValue subscript = (IntegerValue) getRhsExpression().evaluateItem(context);
291 return array.get((int) subscript.longValue() - 1).iterate();
292 } else if (isSingleEntry) {
293 SequenceIterator<?> baseIterator = getLhsExpression().iterate(context);
294 int subscript = (int) ((IntegerValue) getRhsExpression().evaluateItem(context)).longValue() - 1;
295 return new MappingIterator<>(baseIterator,
296 baseItem -> ((ArrayItem) baseItem).get(subscript).iterate());
297 } else {
298 SequenceIterator<?> baseIterator = getLhsExpression().iterate(context);
299 GroundedValue<?> rhs = getRhsExpression().iterate(context).materialize();
300 return new MappingIterator<>(baseIterator, baseItem -> new MappingIterator<>(
301 (SequenceIterator<?>) rhs.iterate(),
302 index -> ((ArrayItem) baseItem).get((int) ((IntegerValue) index).longValue() - 1).iterate()));
303 }
304 } else if (isMapLookup) {
305 if (isSingleContainer && isSingleEntry) {
306 MapItem map = (MapItem) getLhsExpression().evaluateItem(context);
307 AtomicValue key = (AtomicValue) getRhsExpression().evaluateItem(context);
308 GroundedValue value = map.get(key);
309 return value == null ? EmptyIterator.emptyIterator() : value.iterate();
310 } else if (isSingleEntry) {
311 SequenceIterator<?> baseIterator = getLhsExpression().iterate(context);
312 AtomicValue key = (AtomicValue) getRhsExpression().evaluateItem(context);
313 return new MappingIterator<>(baseIterator, baseItem -> {
314 GroundedValue<?> value = ((MapItem) baseItem).get(key);
315 return value == null ? EmptyIterator.emptyIterator() : value.iterate();
316 });
317 } else {
318 SequenceIterator<?> baseIterator = getLhsExpression().iterate(context);
319 GroundedValue<?> rhs = getRhsExpression().iterate(context).materialize();
320 return new MappingIterator<>(
321 baseIterator,
322 baseItem -> new MappingIterator<>(rhs.iterate(), index -> {
323 GroundedValue<?> value = ((MapItem) baseItem).get((AtomicValue) index);
324 return value == null ? EmptyIterator.emptyIterator() : value.iterate();
325 }));
326 }
327
328 } else {
329 SequenceIterator<?> baseIterator = getLhsExpression().iterate(context);
330 GroundedValue<?> rhs = getRhsExpression().iterate(context).materialize();
331 MappingFunction<? extends Item<?>, ? extends Item<?>> mappingFunction = baseItem -> {
332 if (baseItem instanceof ArrayItem) {
333 MappingFunction<Item<?>, Item<?>> arrayAccess = index -> {
334 if (index instanceof IntegerValue) {
335 GroundedValue<?> member = ((ArrayItem) baseItem).get((int) ((IntegerValue) index).longValue() - 1);
336 return member.iterate();
337 } else {
338 XPathException exception = new XPathException(
339 "An item on the LHS of the '?' operator is an array, but a value on the RHS of the operator (" +
340 baseItem.toShortString() + ") is not an integer", "XPTY0004");
341 exception.setIsTypeError(true);
342 exception.setLocation(getLocation());
343 exception.setFailingExpression(LookupExpression.this);
344 throw exception;
345 }
346 };
347 SequenceIterator<?> rhsIter = rhs.iterate();
348 return new MappingIterator<>(rhsIter, arrayAccess);
349 } else if (baseItem instanceof MapItem) {
350 SequenceIterator<?> rhsIter = rhs.iterate();
351 return new MappingIterator<>(rhsIter, key -> {
352 GroundedValue<?> value = ((MapItem) baseItem).get((AtomicValue) key);
353 return value == null ? EmptyIterator.emptyIterator() : value.iterate();
354 });
355 } else if (baseItem instanceof ObjectValue) {
356 if (!(rhs instanceof StringValue)) {
357 XPathException exception = new XPathException(
358 "An item on the LHS of the '?' operator is an external object, but a value on the RHS of the operator (" +
359 baseItem.toShortString() + ") is not a singleton string", "XPTY0004");
360 exception.setIsTypeError(true);
361 exception.setLocation(getLocation());
362 exception.setFailingExpression(LookupExpression.this);
363 throw exception;
364 }
365 String key = rhs.getStringValue();
366 return config.externalObjectAsMap((ObjectValue) baseItem, key).get((StringValue) rhs).iterate();
367 } else {
368 mustBeArrayOrMap(this, baseItem);
369 return null;
370 }
371 };
372 return new MappingIterator(baseIterator, mappingFunction);
373
374 }
375
376 }
377
378 protected static void mustBeArrayOrMap(Expression exp, Item baseItem) throws XPathException {
379 XPathException exception = new XPathException("The items on the LHS of the '?' operator must be maps or arrays; but value (" +
380 baseItem.toShortString() + ") was supplied", "XPTY0004");
381 exception.setIsTypeError(true);
382 exception.setLocation(exp.getLocation());
383 exception.setFailingExpression(exp);
384 throw exception;
385 }
386
387 /**
388 * Diagnostic print of expression structure. The abstract expression tree
389 * is written to the supplied output destination.
390 */
391
392 public void export(ExpressionPresenter destination) throws XPathException {
393 destination.startElement("lookup", this);
394 getLhsExpression().export(destination);
395 getRhsExpression().export(destination);
396 destination.endElement();
397 }
398
399 /**
400 * The toString() method for an expression attempts to give a representation of the expression
401 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
402 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
403 *
404 * @return a representation of the expression as a string
405 */
406
407 public String toString() {
408 String rhs;
409 if (getRhsExpression() instanceof Literal) {
410 Literal lit = (Literal)getRhsExpression();
411 if (lit instanceof StringLiteral && NameChecker.isValidNCName(((StringLiteral) lit).getStringValue())) {
412 rhs = ((StringLiteral) lit).getStringValue();
413 } else if (lit.getValue() instanceof Int64Value) {
414 rhs = lit.getValue().toString();
415 } else {
416 rhs = ExpressionTool.parenthesize(lit);
417 }
418 } else {
419 rhs = ExpressionTool.parenthesize(getRhsExpression());
420 }
421 return ExpressionTool.parenthesize(getLhsExpression()) + "?" + rhs;
422 }
423
424
425 }
426