Debian Codegraph @

net/sf/saxon/expr/CardinalityChecker.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.parser.*;
13 import net.sf.saxon.om.Item;
14 import net.sf.saxon.om.SequenceIterator;
15 import net.sf.saxon.om.SequenceTool;
16 import net.sf.saxon.pattern.DocumentNodeTest;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.Err;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.iter.ArrayIterator;
21 import net.sf.saxon.tree.util.FastStringBuffer;
22 import net.sf.saxon.type.ItemType;
23 import net.sf.saxon.type.Type;
24 import net.sf.saxon.value.Cardinality;
25 import net.sf.saxon.value.IntegerValue;
26
27
28 /**
29 * A CardinalityChecker implements the cardinality checking of "treat as": that is,
30 * it returns the supplied sequence, checking that its cardinality is correct
31 */
32
33 public final class CardinalityChecker extends UnaryExpression {
34
35 private int requiredCardinality = -1;
36 private RoleDiagnostic role;
37
38 /**
39 * Private Constructor: use factory method
40 *
41 * @param sequence the base sequence whose cardinality is to be checked
42 * @param cardinality the required cardinality
43 * @param role information to be used in error reporting
44 */
45
46 private CardinalityChecker(Expression sequence, int cardinality, RoleDiagnostic role) {
47 super(sequence);
48 requiredCardinality = cardinality;
49 this.role = role;
50 //computeStaticProperties();
51 //adoptChildExpression(sequence);
52 }
53
54 /**
55 * Factory method to construct a CardinalityChecker. The method may create an expression that combines
56 * the cardinality checking with the functionality of the underlying expression class
57 *
58 * @param sequence the base sequence whose cardinality is to be checked
59 * @param cardinality the required cardinality
60 * @param role information to be used in error reporting
61 * @return a new Expression that does the CardinalityChecking (not necessarily a CardinalityChecker)
62 */
63
64 public static Expression makeCardinalityChecker(Expression sequence, int cardinality, RoleDiagnostic role) {
65 Expression result;
66 if (sequence instanceof Literal && Cardinality.subsumes(cardinality, SequenceTool.getCardinality(((Literal) sequence).getValue()))) {
67 return sequence;
68 }
69 if (sequence instanceof Atomizer && !Cardinality.allowsMany(cardinality)) {
70 Expression base = ((Atomizer) sequence).getBaseExpression();
71 result = new SingletonAtomizer(base, role, Cardinality.allowsZero(cardinality));
72 } else {
73 result = new CardinalityChecker(sequence, cardinality, role);
74 }
75 ExpressionTool.copyLocationInfo(sequence, result);
76 return result;
77 }
78
79 protected OperandRole getOperandRole() {
80 return OperandRole.SAME_FOCUS_ACTION;
81 }
82
83 /**
84 * Get the required cardinality
85 *
86 * @return the cardinality required by this checker
87 */
88
89 public int getRequiredCardinality() {
90 return requiredCardinality;
91 }
92
93 /**
94 * Type-check the expression
95 */
96
97 /*@NotNull*/
98 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
99 getOperand().typeCheck(visitor, contextInfo);
100 Expression base = getBaseExpression();
101 if (requiredCardinality == StaticProperty.ALLOWS_ZERO_OR_MORE ||
102 Cardinality.subsumes(requiredCardinality, base.getCardinality())) {
103 return base;
104 }
105 return this;
106 }
107
108 /**
109 * Perform optimisation of an expression and its subexpressions.
110 * <p>This method is called after all references to functions and variables have been resolved
111 * to the declaration of the function or variable, and after all type checking has been done.</p>
112 *
113 * @param visitor an expression visitor
114 * @param contextInfo the static type of "." at the point where this expression is invoked.
115 * The parameter is set to null if it is known statically that the context item will be undefined.
116 * If the type of the context item is not known statically, the argument is set to
117 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
118 * @return the original expression, rewritten if appropriate to optimize execution
119 * @throws XPathException if an error is discovered during this phase
120 * (typically a type error)
121 */
122
123 /*@NotNull*/
124 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
125 getOperand().optimize(visitor, contextInfo);
126 Expression base = getBaseExpression();
127 if (requiredCardinality == StaticProperty.ALLOWS_ZERO_OR_MORE ||
128 Cardinality.subsumes(requiredCardinality, base.getCardinality())) {
129 return base;
130 }
131 if ((base.getCardinality() & requiredCardinality) == 0) {
132 XPathException err = new XPathException("The " + role.getMessage() +
133 " does not satisfy the cardinality constraints", role.getErrorCode());
134 err.setLocation(getLocation());
135 err.setIsTypeError(role.isTypeError());
136 throw err;
137 }
138 // do cardinality checking before item checking (may avoid the need for a mapping iterator)
139 if (base instanceof ItemChecker) {
140 ItemChecker checker = (ItemChecker) base;
141 Expression other = checker.getBaseExpression();
142 // change this -> checker -> other to checker -> this -> other
143 setBaseExpression(other);
144 checker.setBaseExpression(this);
145 checker.setParentExpression(null);
146 return checker;
147 }
148 return this;
149 }
150
151
152 /**
153 * Set the error code to be returned (this is used when evaluating the functions such
154 * as exactly-one() which have their own error codes)
155 *
156 * @param code the error code to be used
157 */
158
159 public void setErrorCode(String code) {
160 role.setErrorCode(code);
161 }
162
163 /**
164 * Get the RoleLocator, which contains diagnostic information for use if the cardinality check fails
165 *
166 * @return the diagnostic information
167 */
168
169 public RoleDiagnostic getRoleLocator() {
170 return role;
171 }
172
173 /**
174 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
175 * This method indicates which of these methods is provided. This implementation provides both iterate() and
176 * process() methods natively.
177 */
178
179 public int getImplementationMethod() {
180 int m = ITERATE_METHOD | PROCESS_METHOD | ITEM_FEED_METHOD;
181 if (!Cardinality.allowsMany(requiredCardinality)) {
182 m |= EVALUATE_METHOD;
183 }
184 return m;
185 }
186
187 /**
188 * For an expression that returns an integer or a sequence of integers, get
189 * a lower and upper bound on the values of the integers that may be returned, from
190 * static analysis. The default implementation returns null, meaning "unknown" or
191 * "not applicable". Other implementations return an array of two IntegerValue objects,
192 * representing the lower and upper bounds respectively. The values
193 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
194 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
195 * are used to indicate values limited by the size of a string or the size of a sequence.
196 *
197 * @return the lower and upper bounds of integer values in the result, or null to indicate
198 * unknown or not applicable.
199 */
200 @Override
201 public IntegerValue[] getIntegerBounds() {
202 return getBaseExpression().getIntegerBounds();
203 }
204
205 /**
206 * Iterate over the sequence of values
207 */
208
209 /*@NotNull*/
210 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
211 SequenceIterator<?> base = getBaseExpression().iterate(context);
212
213 // If the base iterator knows how many items there are, then check it now rather than wasting time
214
215 if ((base.getProperties() & SequenceIterator.LAST_POSITION_FINDER) != 0) {
216 int count = ((LastPositionFinder) base).getLength();
217 if (count == 0 && !Cardinality.allowsZero(requiredCardinality)) {
218 typeError("An empty sequence is not allowed as the " +
219 role.getMessage(), role.getErrorCode(), context);
220 } else if (count == 1 && requiredCardinality == StaticProperty.EMPTY) {
221 typeError("The only value allowed for the " +
222 role.getMessage() + " is an empty sequence", role.getErrorCode(), context);
223 } else if (count > 1 && !Cardinality.allowsMany(requiredCardinality)) {
224 typeError("A sequence of more than one item is not allowed as the " +
225 role.getMessage() + depictSequenceStart(base, 2),
226 role.getErrorCode(), context);
227 }
228 return base;
229 }
230
231 // Otherwise return an iterator that does the checking on the fly
232
233 return new CardinalityCheckingIterator<>(base, requiredCardinality, role, getLocation());
234
235 }
236
237 /**
238 * Show the first couple of items in a sequence in an error message
239 *
240 * @param seq iterator over the sequence
241 * @param max maximum number of items to be shown
242 * @return a message display of the contents of the sequence
243 */
244
245 public static String depictSequenceStart(SequenceIterator seq, int max) {
246 try {
247 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
248 int count = 0;
249 sb.append(" (");
250 Item next;
251 while ((next = seq.next()) != null) {
252 if (count++ > 0) {
253 sb.append(", ");
254 }
255 if (count > max) {
256 sb.append("...) ");
257 return sb.toString();
258 }
259
260 sb.append(Err.depict(next));
261 }
262 sb.append(") ");
263 return sb.toString();
264 } catch (XPathException e) {
265 return "";
266 }
267 }
268
269 /**
270 * Evaluate as an Item. For this class, this implies checking that the underlying
271 * expression delivers a singleton.
272 */
273
274 /*@Nullable*/
275 public Item evaluateItem(XPathContext context) throws XPathException {
276 SequenceIterator iter = getBaseExpression().iterate(context);
277 Item first = iter.next();
278 if (first == null) {
279 if (!Cardinality.allowsZero(requiredCardinality)) {
280 typeError("An empty sequence is not allowed as the " +
281 role.getMessage(), role.getErrorCode(), context);
282 }
283 return null;
284 } else {
285 if (requiredCardinality == StaticProperty.EMPTY) {
286 typeError("An empty sequence is required as the " +
287 role.getMessage(), role.getErrorCode(), context);
288 return null;
289 }
290 Item second = iter.next();
291 if (second != null) {
292 Item[] leaders = new Item[]{first, second};
293 typeError("A sequence of more than one item is not allowed as the " +
294 role.getMessage() + depictSequenceStart(new ArrayIterator<Item<?>>(leaders), 2), role.getErrorCode(), context);
295 return null;
296 }
297 }
298 return first;
299 }
300
301 /**
302 * Process the instruction, without returning any tail calls
303 *
304 * @param context The dynamic context, giving access to the current node,
305 * the current variables, etc.
306 */
307
308 public void process(XPathContext context) throws XPathException {
309 Expression next = getBaseExpression();
310 ItemType type = Type.ITEM_TYPE;
311 if (next instanceof ItemChecker) {
312 type = ((ItemChecker) next).getRequiredType();
313 next = ((ItemChecker) next).getBaseExpression();
314 }
315 if ((next.getImplementationMethod() & PROCESS_METHOD) != 0 && !(type instanceof DocumentNodeTest)) {
316 Receiver out = context.getReceiver();
317 TypeCheckingFilter filter = new TypeCheckingFilter(out);
318 filter.setRequiredType(type, requiredCardinality, role, getLocation());
319 context.setReceiver(filter);
320 next.process(context);
321 try {
322 filter.close();
323 } catch (XPathException e) {
324 e.maybeSetLocation(getLocation());
325 throw e;
326 }
327 context.setReceiver(out);
328 } else {
329 // Force pull-mode evaluation
330 super.process(context);
331 }
332 }
333
334 /**
335 * Determine the data type of the items returned by the expression, if possible
336 *
337 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE,
338 * or Type.ITEM (meaning not known in advance)
339 */
340
341 /*@NotNull*/
342 public ItemType getItemType() {
343 return getBaseExpression().getItemType();
344 }
345
346 /**
347 * Determine the static cardinality of the expression
348 */
349
350 public int computeCardinality() {
351 return requiredCardinality;
352 }
353
354 /**
355 * Get the static properties of this expression (other than its type). The result is
356 * bit-signficant. These properties are used for optimizations. In general, if
357 * property bit is set, it is true, but if it is unset, the value is unknown.
358 */
359
360 public int computeSpecialProperties() {
361 return getBaseExpression().getSpecialProperties();
362 }
363
364 /**
365 * Copy an expression. This makes a deep copy.
366 *
367 * @return the copy of the original expression
368 * @param rebindings variable bindings that need to be changed
369 */
370
371 /*@NotNull*/
372 public Expression copy(RebindingMap rebindings) {
373 CardinalityChecker c2 = new CardinalityChecker(getBaseExpression().copy(rebindings), requiredCardinality, role);
374 ExpressionTool.copyLocationInfo(this, c2);
375 return c2;
376 }
377
378 /**
379 * Is this expression the same as another expression?
380 */
381
382 public boolean equals(Object other) {
383 return super.equals(other) &&
384 requiredCardinality == ((CardinalityChecker) other).requiredCardinality;
385 }
386
387 /**
388 * get HashCode for comparing two expressions. Note that this hashcode gives the same
389 * result for (A op B) and for (B op A), whether or not the operator is commutative.
390 */
391
392 @Override
393 public int computeHashCode() {
394 return super.computeHashCode() ^ requiredCardinality;
395 }
396
397 /**
398 * Diagnostic print of expression structure. The abstract expression tree
399 * is written to the supplied output destination.
400 */
401
402 public void export(ExpressionPresenter out) throws XPathException {
403 out.startElement("check", this);
404 String occ = Cardinality.getOccurrenceIndicator(requiredCardinality);
405 if (occ.equals("")) {
406 occ = "1";
407 }
408 out.emitAttribute("card", occ);
409 out.emitAttribute("diag", role.save());
410 getBaseExpression().export(out);
411 out.endElement();
412 }
413
414 /**
415 * The toString() method for an expression attempts to give a representation of the expression
416 * in an XPath-like form. For subclasses of Expression that represent XPath expressions, the result should always
417 * be a string that parses as an XPath 3.0 expression.
418 */
419 @Override
420 public String toString() {
421 Expression operand = getBaseExpression();
422 switch (requiredCardinality) {
423 case StaticProperty.ALLOWS_ONE:
424 return "exactly-one(" + operand + ")";
425 case StaticProperty.ALLOWS_ZERO_OR_ONE:
426 return "zero-or-one(" + operand + ")";
427 case StaticProperty.ALLOWS_ONE_OR_MORE:
428 return "one-or-more(" + operand + ")";
429 case StaticProperty.EMPTY:
430 return "must-be-empty(" + operand + ")";
431 default:
432 return "check(" + operand + ")";
433 }
434 }
435
436 /**
437 * Get a name identifying the kind of expression, in terms meaningful to a user.
438 *
439 * @return a name identifying the kind of expression, in terms meaningful to a user.
440 * The name will always be in the form of a lexical XML QName, and should match the name used
441 * in explain() output displaying the expression.
442 */
443
444 public String getExpressionName() {
445 return "CheckCardinality";
446 }
447
448 @Override
449 public String toShortString() {
450 return getBaseExpression().toShortString();
451 }
452
453
454 @Override
455 public String getStreamerName() {
456 return "CardinalityChecker";
457 }
458
459 @Override
460 public void setLocation(Location id) {
461 super.setLocation(id);
462 }
463 }
464