Debian Codegraph @

net/sf/saxon/expr/ForExpression.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.flwor.OuterForExpression;
12 import net.sf.saxon.expr.instruct.Choose;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.lib.Feature;
15 import net.sf.saxon.om.Item;
16 import net.sf.saxon.om.SequenceIterator;
17 import net.sf.saxon.om.StructuredQName;
18 import net.sf.saxon.trace.ExpressionPresenter;
19 import net.sf.saxon.trace.LocationKind;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.type.ItemType;
22 import net.sf.saxon.type.SchemaType;
23 import net.sf.saxon.type.TypeHierarchy;
24 import net.sf.saxon.type.UType;
25 import net.sf.saxon.value.Cardinality;
26 import net.sf.saxon.value.IntegerValue;
27 import net.sf.saxon.value.SequenceType;
28
29 import java.util.ArrayList;
30 import java.util.List;
31
32 /**
33 * A ForExpression maps an expression over a sequence.
34 * We use a ForExpression in preference to a FLWORExpression to handle simple cases
35 * (roughly, the XPath subset). In 9.6, we no longer convert a FLWORExpression to a ForExpression
36 * if there is a position variable, which simplifies the cases this class has to handle.
37 */
38
39 public class ForExpression extends Assignation {
40
41 int actionCardinality = StaticProperty.ALLOWS_MANY;
42
43 /**
44 * Create a "for" expression (for $x at $p in SEQUENCE return ACTION)
45 */
46
47 public ForExpression() {
48 }
49
50 /**
51 * Get a name identifying the kind of expression, in terms meaningful to a user.
52 *
53 * @return a name identifying the kind of expression, in terms meaningful to a user.
54 * The name will always be in the form of a lexical XML QName, and should match the name used
55 * in explain() output displaying the expression.
56 */
57
58 public String getExpressionName() {
59 return "for";
60 }
61
62
63 /**
64 * Type-check the expression
65 */
66
67 /*@NotNull*/
68 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
69
70 // The order of events is critical here. First we ensure that the type of the
71 // sequence expression is established. This is used to establish the type of the variable,
72 // which in turn is required when type-checking the action part.
73
74 getSequenceOp().typeCheck(visitor, contextInfo);
75 if (Literal.isEmptySequence(getSequence()) && !(this instanceof OuterForExpression)) {
76 return getSequence();
77 }
78
79 if (requiredType != null) {
80 // if declaration is null, we've already done the type checking in a previous pass
81 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
82 SequenceType decl = requiredType;
83 SequenceType sequenceType = SequenceType.makeSequenceType(
84 decl.getPrimaryType(), StaticProperty.ALLOWS_ZERO_OR_MORE);
85 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, variableName.getDisplayName(), 0);
86 setSequence(TypeChecker.strictTypeCheck(
87 getSequence(), sequenceType, role, visitor.getStaticContext()));
88 ItemType actualItemType = getSequence().getItemType();
89 refineTypeInformation(actualItemType,
90 getRangeVariableCardinality(),
91 null,
92 getSequence().getSpecialProperties(), this);
93 }
94
95 if (Literal.isEmptySequence(getAction())) {
96 return getAction();
97 }
98 getActionOp().typeCheck(visitor, contextInfo);
99 actionCardinality = getAction().getCardinality();
100 return this;
101 }
102
103 /**
104 * Get the cardinality of the range variable
105 *
106 * @return the cardinality of the range variable (StaticProperty.EXACTLY_ONE). Can be overridden
107 * in a subclass
108 */
109
110 protected int getRangeVariableCardinality() {
111 return StaticProperty.EXACTLY_ONE;
112 }
113
114 /**
115 * Optimize the expression
116 */
117
118 /*@NotNull*/
119 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
120 Configuration config = visitor.getConfiguration();
121 Optimizer opt = visitor.obtainOptimizer();
122 boolean debug = config.getBooleanProperty(Feature.TRACE_OPTIMIZER_DECISIONS);
123
124 // Try to promote any WHERE clause appearing immediately within the FOR expression
125
126 if (Choose.isSingleBranchChoice(getAction())) {
127 getActionOp().optimize(visitor, contextItemType);
128 }
129
130 Expression p = promoteWhereClause();
131 if (p != null) {
132 if (debug) {
133 opt.trace("Promoted where clause in for $" + getVariableName(), p);
134 }
135 return p.optimize(visitor, contextItemType);
136 }
137
138 Expression seq0 = getSequence();
139 getSequenceOp().optimize(visitor, contextItemType);
140 if (seq0 != getSequence()) {
141 // if it changed, re-optimize
142 return optimize(visitor, contextItemType);
143 }
144
145 if (Literal.isEmptySequence(getSequence()) && !(this instanceof OuterForExpression)) {
146 return getSequence();
147 }
148
149 Expression act0 = getAction();
150 getActionOp().optimize(visitor, contextItemType);
151 if (act0 != getAction()) {
152 // it's now worth re-attempting the "where" clause optimizations
153 return optimize(visitor, contextItemType);
154 }
155
156 if (Literal.isEmptySequence(getAction())) {
157 return getAction();
158 }
159
160 // Simplify an expression of the form "for $b in a/b/c return $b/d".
161 // (XQuery users seem to write these a lot!)
162
163 if (getSequence() instanceof SlashExpression && getAction() instanceof SlashExpression) {
164 SlashExpression path2 = (SlashExpression) getAction();
165 Expression start2 = path2.getSelectExpression();
166 Expression step2 = path2.getActionExpression();
167 if (start2 instanceof VariableReference && ((VariableReference) start2).getBinding() == this &&
168 ExpressionTool.getReferenceCount(getAction(), this, false) == 1 &&
169 ((step2.getDependencies() & (StaticProperty.DEPENDS_ON_POSITION | StaticProperty.DEPENDS_ON_LAST)) == 0)) {
170 Expression newPath = new SlashExpression(getSequence(), path2.getActionExpression());
171 ExpressionTool.copyLocationInfo(this, newPath);
172 newPath = newPath.simplify().typeCheck(visitor, contextItemType);
173 if (newPath instanceof SlashExpression) {
174 // if not, it has been wrapped in a DocumentSorter or Reverser, which makes it ineligible.
175 // see test qxmp299, where this condition isn't satisfied
176 if (debug) {
177 opt.trace("Collapsed return clause of for $" + getVariableName() +
178 " into path expression", newPath);
179 }
180 return newPath.optimize(visitor, contextItemType);
181 }
182 }
183 }
184
185 // Simplify an expression of the form "for $x in EXPR return $x". These sometimes
186 // arise as a result of previous optimization steps.
187
188 if (getAction() instanceof VariableReference && ((VariableReference) getAction()).getBinding() == this) {
189 if (debug) {
190 opt.trace("Collapsed redundant for expression $" + getVariableName(), getSequence());
191 }
192 return getSequence();
193 }
194
195 // If the cardinality of the sequence is exactly one, rewrite as a LET expression
196
197 if (getSequence().getCardinality() == StaticProperty.EXACTLY_ONE) {
198 LetExpression let = new LetExpression();
199 let.setVariableQName(variableName);
200 let.setRequiredType(SequenceType.makeSequenceType(
201 getSequence().getItemType(),
202 StaticProperty.EXACTLY_ONE));
203 let.setSequence(getSequence());
204 let.setAction(getAction());
205 let.setSlotNumber(slotNumber);
206 let.setRetainedStaticContextLocally(getRetainedStaticContext());
207 ExpressionTool.rebindVariableReferences(getAction(), this, let);
208 return let.typeCheck(visitor, contextItemType).optimize(visitor, contextItemType);
209 }
210
211 return this;
212 }
213
214 /**
215 * Replace this expression by a simpler expression that delivers the results without regard
216 * to order.
217 *
218 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
219 * original; set to false if the result can eliminate (or introduce) duplicates.
220 * @param forStreaming set to true if optimizing for streaming
221 */
222 @Override
223 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
224 setSequence(getSequence().unordered(retainAllNodes, forStreaming));
225 setAction(getAction().unordered(retainAllNodes, forStreaming));
226 return this;
227 }
228
229 /**
230 * For an expression that returns an integer or a sequence of integers, get
231 * a lower and upper bound on the values of the integers that may be returned, from
232 * static analysis. The default implementation returns null, meaning "unknown" or
233 * "not applicable". Other implementations return an array of two IntegerValue objects,
234 * representing the lower and upper bounds respectively. The values
235 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
236 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
237 * are used to indicate values limited by the size of a string or the size of a sequence.
238 *
239 * @return the lower and upper bounds of integer values in the result, or null to indicate
240 * unknown or not applicable.
241 */
242 /*@Nullable*/
243 @Override
244 public IntegerValue[] getIntegerBounds() {
245 return getAction().getIntegerBounds();
246 }
247
248 /**
249 * Promote a WHERE clause whose condition doesn't depend on the variable being bound.
250 * This rewrites an expression of the form
251 * <p>let $i := SEQ return if (C) then R else ()</p>
252 * <p>to the form:</p>
253 * <p>if (C) then (let $i := SEQ return R) else ()</p>
254 *
255 * @return an expression in which terms from the WHERE clause that can be extracted have been extracted
256 */
257
258 /*@Nullable*/
259 protected Expression promoteWhereClause() {
260 if (Choose.isSingleBranchChoice(getAction())) {
261 Expression condition = ((Choose) getAction()).getCondition(0);
262 Binding[] bindingList = new Binding[]{this};
263 List<Expression> list = new ArrayList<>(5);
264 Expression promotedCondition = null;
265 BooleanExpression.listAndComponents(condition, list);
266 for (int i = list.size() - 1; i >= 0; i--) {
267 Expression term = list.get(i);
268 if (!ExpressionTool.dependsOnVariable(term, bindingList)) {
269 if (promotedCondition == null) {
270 promotedCondition = term;
271 } else {
272 promotedCondition = new AndExpression(term, promotedCondition);
273 }
274 list.remove(i);
275 }
276 }
277 if (promotedCondition != null) {
278 if (list.isEmpty()) {
279 // the whole if() condition has been promoted
280 Expression oldThen = ((Choose) getAction()).getAction(0);
281 setAction(oldThen);
282 return Choose.makeConditional(condition, this);
283 } else {
284 // one or more terms of the if() condition have been promoted
285 Expression retainedCondition = list.get(0);
286 for (int i = 1; i < list.size(); i++) {
287 retainedCondition = new AndExpression(retainedCondition, list.get(i));
288 }
289 ((Choose) getAction()).setCondition(0, retainedCondition);
290 Expression newIf = Choose.makeConditional(
291 promotedCondition, this, Literal.makeEmptySequence());
292 ExpressionTool.copyLocationInfo(this, newIf);
293 return newIf;
294 }
295 }
296 }
297 return null;
298 }
299
300
301 /**
302 * Copy an expression. This makes a deep copy.
303 *
304 * @param rebindings variables that need to be re-bound
305 * @return the copy of the original expression
306 */
307
308 /*@NotNull*/
309 public Expression copy(RebindingMap rebindings) {
310 ForExpression forExp = new ForExpression();
311 ExpressionTool.copyLocationInfo(this, forExp);
312 forExp.setRequiredType(requiredType);
313 forExp.setVariableQName(variableName);
314 forExp.setSequence(getSequence().copy(rebindings));
315 //rebindings.put(this, forExp);
316 Expression newAction = getAction().copy(rebindings);
317 forExp.setAction(newAction);
318 forExp.variableName = variableName;
319 forExp.slotNumber = slotNumber;
320 // TODO: should be able to do this by adding a mapping to rebindings as above. But -s:app-Walmsley -t:d1e41271 crashes.
321 ExpressionTool.rebindVariableReferences(newAction, this, forExp);
322 return forExp;
323 }
324
325 /**
326 * Mark tail function calls: only possible if the for expression iterates zero or one times.
327 * (This arises in XSLT/XPath, which does not have a LET expression, so FOR gets used instead)
328 */
329
330 public int markTailFunctionCalls(StructuredQName qName, int arity) {
331 if (!Cardinality.allowsMany(getSequence().getCardinality())) {
332 return ExpressionTool.markTailFunctionCalls(getAction(), qName, arity);
333 } else {
334 return UserFunctionCall.NOT_TAIL_CALL;
335 }
336 }
337
338 /**
339 * Determine whether this is a vacuous expression as defined in the XQuery update specification
340 *
341 * @return true if this expression is vacuous
342 */
343
344 public boolean isVacuousExpression() {
345 return getAction().isVacuousExpression();
346 }
347
348 /**
349 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
350 * This method indicates which of these methods is provided. This implementation provides both iterate() and
351 * process() methods natively.
352 */
353
354 public int getImplementationMethod() {
355 return ITERATE_METHOD | PROCESS_METHOD;
356 }
357
358 /**
359 * Check that any elements and attributes constructed or returned by this expression are acceptable
360 * in the content model of a given complex type. It's always OK to say yes, since the check will be
361 * repeated at run-time. The process of checking element and attribute constructors against the content
362 * model of a complex type also registers the type of content expected of those constructors, so the
363 * static validation can continue recursively.
364 */
365
366 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
367 getAction().checkPermittedContents(parentType, false);
368 }
369
370 /**
371 * Iterate over the sequence of values
372 */
373
374 /*@NotNull*/
375 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
376
377 // First create an iteration of the base sequence.
378
379 // Then create a MappingIterator which applies a mapping function to each
380 // item in the base sequence. The mapping function is essentially the "return"
381 // expression, wrapped in a MappingAction object that is responsible also for
382 // setting the range variable at each step.
383
384 SequenceIterator<?> base = getSequence().iterate(context);
385 MappingAction map = new MappingAction(context, getLocalSlotNumber(), getAction());
386 switch (actionCardinality) {
387 case StaticProperty.EXACTLY_ONE:
388 return new ItemMappingIterator<>(base, map, true);
389 case StaticProperty.ALLOWS_ZERO_OR_ONE:
390 return new ItemMappingIterator<>(base, map, false);
391 default:
392 return new MappingIterator<>(base, map);
393 }
394 }
395
396 /**
397 * Process this expression as an instruction, writing results to the current
398 * outputter
399 */
400
401 public void process(XPathContext context) throws XPathException {
402 int slot = getLocalSlotNumber();
403 getSequence().iterate(context).forEachOrFail(item -> {
404 context.setLocalVariable(slot, item);
405 getAction().process(context);
406 });
407 }
408
409
410 /**
411 * Evaluate an updating expression, adding the results to a Pending Update List.
412 * The default implementation of this method, which is used for non-updating expressions,
413 * throws an UnsupportedOperationException
414 *
415 * @param context the XPath dynamic evaluation context
416 * @param pul the pending update list to which the results should be written
417 */
418
419 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
420 int slot = getLocalSlotNumber();
421 getSequence().iterate(context).forEachOrFail(item -> {
422 context.setLocalVariable(slot, item);
423 getAction().evaluatePendingUpdates(context, pul);
424 });
425 }
426
427 /**
428 * Determine the data type of the items returned by the expression, if possible
429 *
430 * @return one of the values Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE,
431 * or Type.ITEM (meaning not known in advance)
432 */
433
434 /*@NotNull*/
435 public ItemType getItemType() {
436 return getAction().getItemType();
437 }
438
439 /**
440 * Get the static type of the expression as a UType, following precisely the type
441 * inference rules defined in the XSLT 3.0 specification.
442 *
443 * @param contextItemType the static type of the context item
444 * @return the static item type of the expression according to the XSLT 3.0 defined rules
445 */
446 @Override
447 public UType getStaticUType(UType contextItemType) {
448 return getAction().getStaticUType(contextItemType);
449 }
450
451 /**
452 * Determine the static cardinality of the expression
453 */
454
455 public int computeCardinality() {
456 int c1 = getSequence().getCardinality();
457 int c2 = getAction().getCardinality();
458 return Cardinality.multiply(c1, c2);
459 }
460
461 /**
462 * The toString() method for an expression attempts to give a representation of the expression
463 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
464 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
465 *
466 * @return a representation of the expression as a string
467 */
468
469 public String toString() {
470 return "for $" + getVariableEQName() +
471 " in " + (getSequence() == null ? "(...)" : getSequence().toString()) +
472 " return " + (getAction() == null ? "(...)" : ExpressionTool.parenthesize(getAction()));
473 }
474
475 @Override
476 public String toShortString() {
477 return "for $" + getVariableQName().getDisplayName() +
478 " in " + (getSequence() == null ? "(...)" : getSequence().toShortString()) +
479 " return " + (getAction() == null ? "(...)" : getAction().toShortString());
480 }
481
482 /**
483 * Diagnostic print of expression structure. The abstract expression tree
484 * is written to the supplied output destination.
485 */
486
487 public void export(ExpressionPresenter out) throws XPathException {
488 out.startElement("for", this);
489 explainSpecializedAttributes(out);
490 out.emitAttribute("var", getVariableQName());
491 out.emitAttribute("as", getSequence().getItemType().toExportString());
492 out.emitAttribute("slot", "" + getLocalSlotNumber());
493 out.setChildRole("in");
494 getSequence().export(out);
495 out.setChildRole("return");
496 getAction().export(out);
497 out.endElement();
498 }
499
500 protected void explainSpecializedAttributes(ExpressionPresenter out) {
501 // no action
502 }
503
504 /**
505 * The MappingAction represents the action to be taken for each item in the
506 * source sequence. It acts as the MappingFunction for the mapping iterator.
507 */
508
509 public static class MappingAction
510 implements MappingFunction<Item<?>, Item<?>>, ItemMappingFunction<Item<?>, Item<?>> {
511
512 protected XPathContext context;
513 private int slotNumber;
514 private Expression action;
515
516 public MappingAction(XPathContext context,
517 int slotNumber,
518 Expression action) {
519 this.context = context;
520 this.slotNumber = slotNumber;
521 this.action = action;
522 }
523
524 /*@Nullable*/
525 public SequenceIterator<?> map(Item<?> item) throws XPathException {
526 context.setLocalVariable(slotNumber, item);
527 return action.iterate(context);
528 }
529
530 /*@Nullable*/
531 public Item<?> mapItem(Item<?> item) throws XPathException {
532 context.setLocalVariable(slotNumber, item);
533 return action.evaluateItem(context);
534 }
535
536 }
537
538 /**
539 * Get the type of this expression for use in tracing and diagnostics
540 *
541 * @return the type of expression, as enumerated in class {@link LocationKind}
542 */
543
544 public int getConstructType() {
545 return LocationKind.FOR_EXPRESSION;
546 }
547
548 @Override
549 public String getStreamerName() {
550 return "ForExpression";
551 }
552
553
554 }
555