Debian Codegraph @

net/sf/saxon/expr/flwor/FLWORExpression.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.flwor;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.om.Item;
13 import net.sf.saxon.om.SequenceIterator;
14 import net.sf.saxon.query.QueryModule;
15 import net.sf.saxon.trace.ExpressionPresenter;
16 import net.sf.saxon.trace.LocationKind;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.tree.util.FastStringBuffer;
19 import net.sf.saxon.type.ItemType;
20 import net.sf.saxon.value.SequenceType;
21
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.List;
25
26 /**
27 * This class represents a FLWOR expression, evaluated using tuple streams
28 */
29 public class FLWORExpression extends Expression {
30
31 public List<Clause> clauses;
32 public Operand returnClauseOp;
33
34 public FLWORExpression() {}
35
36 public void init(List<Clause> clauses, Expression returnClause) {
37 this.clauses = clauses;
38 boolean looping = false;
39 for (Clause c : clauses) {
40 if (isLoopingClause(c)) {
41 looping = true;
42 break;
43 }
44 }
45 this.returnClauseOp = new Operand(this, returnClause, looping ? REPEATED_RETURN : SINGLE_RETURN);
46 }
47
48 /**
49 * Get the list of clauses of the FLWOR expression, in the order they are written.
50 * This excludes the return clause
51 *
52 * @return the list of clauses
53 */
54 /*@NotNull*/
55 public List<Clause> getClauseList() {
56 return clauses;
57 }
58
59 public static boolean isLoopingClause(Clause c) {
60 return c.getClauseKey() == Clause.FOR || c.getClauseKey() == Clause.GROUPBYCLAUSE || c.getClauseKey() == Clause.WINDOW;
61 }
62
63 /**
64 * Get the return clause of the FLWOR expression
65 *
66 * @return the expression contained in the return clause
67 */
68
69 /*@NotNull*/
70 public Expression getReturnClause() {
71 return returnClauseOp.getChildExpression();
72 }
73
74 /**
75 * Determine whether a given variable binding belongs to this FLWOR expression
76 *
77 * @param binding the binding being sought
78 * @return true if this binding belongs to one of the clauses of this FLWOR expression
79 */
80
81 public boolean hasVariableBinding(Binding binding) {
82 for (Clause c : clauses) {
83 if (clauseHasBinding(c, binding)) {
84 return true;
85 }
86 }
87 return false;
88 }
89
90 private boolean clauseHasBinding(Clause c, Binding binding) {
91 for (Binding b : c.getRangeVariables()) {
92 if (b == binding) {
93 return true;
94 }
95 }
96 return false;
97 }
98
99 /**
100 * Ask whether common subexpressions found in the operands of this expression can
101 * be extracted and evaluated outside the expression itself. The result is irrelevant
102 * in the case of operands evaluated with a different focus, which will never be
103 * extracted in this way, even if they have no focus dependency.
104 *
105 * @return false for this kind of expression
106 */
107 @Override
108 public boolean allowExtractingCommonSubexpressions() {
109 return false;
110 }
111
112 /**
113 * Simplify an expression. This performs any static optimization (by rewriting the expression
114 * as a different expression). The default implementation does nothing.
115 *
116 *
117 *
118 * @throws net.sf.saxon.trans.XPathException
119 * if an error is discovered during expression
120 * rewriting
121 */
122 /*@NotNull*/
123 @Override
124 public Expression simplify() throws XPathException {
125 OperandProcessor simplifier =
126 op -> op.setChildExpression(op.getChildExpression().simplify());
127 for (Clause c : clauses) {
128 c.processOperands(simplifier);
129 }
130 returnClauseOp.setChildExpression(getReturnClause().simplify());
131 return this;
132 }
133
134 /**
135 * Perform type checking of an expression and its subexpressions. This is the second phase of
136 * static optimization.
137 * <p>This checks statically that the operands of the expression have
138 * the correct type; if necessary it generates code to do run-time type checking or type
139 * conversion. A static type error is reported only if execution cannot possibly succeed, that
140 * is, if a run-time type error is inevitable. The call may return a modified form of the expression.</p>
141 * <p>This method is called after all references to functions and variables have been resolved
142 * to the declaration of the function or variable. However, the types of such functions and
143 * variables may not be accurately known if they have not been explicitly declared.</p>
144 * <p>If the implementation returns a value other than "this", then it is required to ensure that
145 * the location information in the returned expression have been set up correctly.
146 * It should not rely on the caller to do this, although for historical reasons many callers do so.</p>
147 *
148 *
149 param visitor an expression visitor
150 * @param contextInfo static information about the dynamic context
151 * @return the original expression, rewritten to perform necessary run-time type checks,
152 * and to perform other type-related optimizations
153 * @throws net.sf.saxon.trans.XPathException
154 * if an error is discovered during this phase
155 * (typically a type error)
156 */
157 /*@NotNull*/
158 @Override
159 public Expression typeCheck(final ExpressionVisitor visitor, final ContextItemStaticInfo contextInfo)
160 throws XPathException {
161
162 OperandProcessor typeChecker = op -> op.typeCheck(visitor, contextInfo);
163 for (int i = 0; i < clauses.size(); i++) {
164 clauses.get(i).processOperands(typeChecker);
165 clauses.get(i).typeCheck(visitor, contextInfo);
166 LocalVariableBinding[] bindings = clauses.get(i).getRangeVariables();
167
168 for (Binding b : bindings) {
169 List<VariableReference> references = new ArrayList<>();
170 for (int j = i; j < clauses.size(); j++) {
171 clauses.get(j).gatherVariableReferences(visitor, b, references);
172 }
173 ExpressionTool.gatherVariableReferences(getReturnClause(), b, references);
174 clauses.get(i).refineVariableType(visitor, references, getReturnClause());
175 }
176 }
177 returnClauseOp.typeCheck(visitor, contextInfo);
178 return this;
179 }
180
181 /**
182 * Determine whether this expression implements its own method for static type checking
183 *
184 * @return true - this expression has a non-trivial implementation of the staticTypeCheck()
185 * method
186 */
187
188 public boolean implementsStaticTypeCheck() {
189 for (Clause c : clauses) {
190 switch (c.getClauseKey()) {
191 case Clause.LET:
192 case Clause.WHERE:
193 continue;
194 default:
195 return false;
196 }
197 }
198 return true;
199 }
200
201 /**
202 * Static type checking for let expressions is delegated to the expression itself,
203 * and is performed on the "return" expression, to allow further delegation to the branches
204 * of a conditional
205 *
206 *
207 * @param req the required type
208 * @param backwardsCompatible true if backwards compatibility mode applies
209 * @param role the role of the expression in relation to the required type
210 * @param visitor an expression visitor
211 * @return the expression after type checking (perhaps augmented with dynamic type checking code)
212 * @throws XPathException if failures occur, for example if the static type of one branch of the conditional
213 * is incompatible with the required type
214 */
215
216 public Expression staticTypeCheck(SequenceType req,
217 boolean backwardsCompatible,
218 RoleDiagnostic role, ExpressionVisitor visitor)
219 throws XPathException {
220 // only called if implementsStaticTypeCheck() returns true
221 TypeChecker tc = visitor.getConfiguration().getTypeChecker(backwardsCompatible);
222 returnClauseOp.setChildExpression(
223 tc.staticTypeCheck(getReturnClause(), req, role, visitor));
224 return this;
225 }
226
227 /**
228 * Determine the data type of the items returned by the expression.
229 *
230 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER,
231 * Type.NODE, or Type.ITEM (meaning not known at compile time)
232 */
233 /*@NotNull*/
234 @Override
235 public ItemType getItemType() {
236 return getReturnClause().getItemType();
237 }
238
239 /**
240 * Compute the static cardinality of this expression
241 *
242 * @return the computed cardinality, as one of the values {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ZERO_OR_ONE},
243 * {@link net.sf.saxon.expr.StaticProperty#EXACTLY_ONE}, {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ONE_OR_MORE},
244 * {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ZERO_OR_MORE}
245 */
246 @Override
247 protected int computeCardinality() {
248 // Assume that simple cases, like a FLWOR whose clauses are all "let" clauses, will have been converted into something else.
249 return StaticProperty.ALLOWS_ZERO_OR_MORE;
250 }
251
252 /**
253 * Get the immediate sub-expressions of this expression, with information about the relationship
254 * of each expression to its parent expression. Default implementation
255 * returns a zero-length array, appropriate for an expression that has no
256 * sub-expressions.
257 *
258 * @return an iterator containing the sub-expressions of this expression
259 */
260 @Override
261 public Iterable<Operand> operands() {
262 final List<Operand> list = new ArrayList<>(5);
263 boolean repeatable = false;
264 try {
265 for (Clause c : clauses) {
266 c.processOperands(list::add);
267 if (c instanceof ForClause) {
268 repeatable = true;
269 }
270 }
271 } catch (XPathException e) {
272 throw new IllegalStateException(e);
273 }
274 list.add(returnClauseOp);
275 return list;
276
277 }
278
279 private static final OperandRole SINGLE_RETURN =
280 new OperandRole(0, OperandUsage.TRANSMISSION, SequenceType.ANY_SEQUENCE);
281
282 private static final OperandRole REPEATED_RETURN =
283 new OperandRole(OperandRole.HIGHER_ORDER, OperandUsage.TRANSMISSION, SequenceType.ANY_SEQUENCE);
284
285 /**
286 * Check to ensure that this expression does not contain any inappropriate updating subexpressions.
287 * This check is overridden for those expressions that permit updating subexpressions.
288 *
289 * @throws net.sf.saxon.trans.XPathException
290 * if the expression has a non-permitted updateing subexpression
291 */
292
293 public void checkForUpdatingSubexpressions() throws XPathException {
294 OperandProcessor processor = op -> {
295 op.getChildExpression().checkForUpdatingSubexpressions();
296 if (op.getChildExpression().isUpdatingExpression()) {
297 throw new XPathException(
298 "An updating expression cannot be used in a clause of a FLWOR expression", "XUST0001");
299 }
300 };
301 for (Clause c : clauses) {
302 c.processOperands(processor);
303 }
304 getReturnClause().checkForUpdatingSubexpressions();
305 }
306
307 /**
308 * Determine whether this is an updating expression as defined in the XQuery update specification
309 *
310 * @return true if this is an updating expression
311 */
312
313 @Override
314 public boolean isUpdatingExpression() {
315 return getReturnClause().isUpdatingExpression();
316 }
317
318 /**
319 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
320 * This method indicates which of these methods is provided directly. The other methods will always be available
321 * indirectly, using an implementation that relies on one of the other methods.
322 *
323 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
324 * {@link #PROCESS_METHOD}
325 */
326 @Override
327 public int getImplementationMethod() {
328 return ITERATE_METHOD | PROCESS_METHOD;
329 }
330
331 /**
332 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
333 * by an expression in a source tree.
334 * <p>The default implementation of this method assumes that an expression does no navigation other than
335 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
336 * same context as the containing expression. The method must be overridden for any expression
337 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
338 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
339 * functions because they create a new navigation root. Implementations also exist for PathExpression and
340 * FilterExpression because they have subexpressions that are evaluated in a different context from the
341 * calling expression.</p>
342 *
343 * @param pathMap the PathMap to which the expression should be added
344 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
345 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
346 * expression, and that represent possible results of this expression. For an expression that does
347 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
348 * expressions, it is the same as the input pathMapNode.
349 */
350
351 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, /*@Nullable*/ PathMap.PathMapNodeSet pathMapNodeSet) {
352 for (Clause c : clauses) {
353 c.addToPathMap(pathMap, pathMapNodeSet);
354 }
355 return getReturnClause().addToPathMap(pathMap, pathMapNodeSet);
356 }
357
358
359 /**
360 * Diagnostic print of expression structure. The abstract expression tree
361 * is written to the supplied output destination.
362 *
363 * @param out the expression presenter used to display the structure
364 */
365 @Override
366 public void export(ExpressionPresenter out) throws XPathException {
367 out.startElement("FLWOR", this);
368 for (Clause c : clauses) {
369 c.explain(out);
370 }
371 out.startSubsidiaryElement("return");
372 getReturnClause().export(out);
373 out.endSubsidiaryElement();
374 out.endElement();
375 }
376
377 /**
378 * Copy an expression. This makes a deep copy.
379 *
380 * @return the copy of the original expression
381 * @param rebindings variable bindings to be replaced
382 */
383 /*@NotNull*/
384 @Override
385 public Expression copy(RebindingMap rebindings) {
386 //verifyParentPointers();
387 List<Clause> newClauses = new ArrayList<>();
388 List<LocalVariableBinding> oldBindings = new ArrayList<>();
389 List<LocalVariableBinding> newBindings = new ArrayList<>();
390 FLWORExpression f2 = new FLWORExpression();
391 for (Clause c : clauses) {
392 Clause c2 = c.copy(f2, rebindings);
393 c2.setLocation(c.getLocation());
394 c2.setRepeated(c.isRepeated());
395 oldBindings.addAll(Arrays.asList(c.getRangeVariables()));
396 newBindings.addAll(Arrays.asList(c2.getRangeVariables()));
397 newClauses.add(c2);
398 }
399 f2.init(newClauses, getReturnClause().copy(rebindings));
400 ExpressionTool.copyLocationInfo(this, f2);
401 for (int i = 0; i < oldBindings.size(); i++) {
402 ExpressionTool.rebindVariableReferences(f2, oldBindings.get(i), newBindings.get(i));
403 }
404 //f2.verifyParentPointers();
405 return f2;
406 }
407
408 /**
409 * Replace this expression by a simpler expression that delivers the results without regard
410 * to order.
411 *
412 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
413 * original; set to false if the result can eliminate (or introduce) duplicates.
414 * @param forStreaming set to true if optimizing for streaming
415 */
416 @Override
417 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
418 for (Clause c : clauses) {
419 if (c instanceof ForClause && ((ForClause)c).getPositionVariable() == null) {
420 ((ForClause)c).setSequence(((ForClause)c).getSequence().unordered(retainAllNodes, forStreaming));
421 }
422 }
423 returnClauseOp.setChildExpression(
424 getReturnClause().unordered(retainAllNodes, forStreaming));
425 return this;
426 }
427
428 /*@Nullable*/
429 private Binding[] extendBindingList(/*@Nullable*/ Binding[] bindings, /*@Nullable*/ LocalVariableBinding[] moreBindings) {
430 if (bindings == null) {
431 bindings = new Binding[0];
432 }
433 if (moreBindings == null || moreBindings.length == 0) {
434 return bindings;
435 } else {
436 Binding[] b2 = new Binding[bindings.length + moreBindings.length];
437 System.arraycopy(bindings, 0, b2, 0, bindings.length);
438 System.arraycopy(moreBindings, 0, b2, bindings.length, moreBindings.length);
439 return b2;
440 }
441 }
442
443 @Override
444 public int getEvaluationMethod() {
445 return Expression.PROCESS_METHOD;
446 }
447
448
449 /*@NotNull*/
450 public Expression optimize(
451 final ExpressionVisitor visitor,
452 final ContextItemStaticInfo contextItemType) throws XPathException {
453
454 //verifyParentPointers();
455 // Optimize all the subexpressions
456 for (Clause c : clauses) {
457 c.processOperands(op -> op.optimize(visitor, contextItemType));
458 c.optimize(visitor, contextItemType);
459 }
460
461 // Optimize the return expression
462 returnClauseOp.setChildExpression(
463 getReturnClause().optimize(visitor, contextItemType));
464
465 // For a very simple "for" or "let" expression, convert it to a ForExpression or LetExpression now
466 if (clauses.size() == 1) {
467 Clause c = clauses.get(0);
468 if (c instanceof LetClause ||
469 (c instanceof ForClause && ((ForClause)c).getPositionVariable() == null)) {
470 return rewriteForOrLet(visitor, contextItemType);
471 }
472 }
473
474 // If any 'let' clause declares a variable that is used only once, then inline it. If the variable
475 // is not used at all, then eliminate it
476
477 boolean tryAgain;
478 boolean changed = false;
479 do {
480 tryAgain = false;
481 for (Clause c : clauses) {
482 if (c.getClauseKey() == Clause.LET) {
483 LetClause lc = (LetClause) c;
484 if (!ExpressionTool.dependsOnVariable(this, new Binding[]{lc.getRangeVariable()})) {
485 clauses.remove(c);
486 tryAgain = true;
487 break;
488 }
489 boolean suppressInlining = false;
490 for (Clause c2 : clauses) {
491 if (c2.containsNonInlineableVariableReference(lc.getRangeVariable())) {
492 suppressInlining = true;
493 break;
494 }
495 }
496 if (!suppressInlining) {
497 boolean oneRef = lc.getRangeVariable().getNominalReferenceCount() == 1;
498 boolean simpleSeq = lc.getSequence() instanceof VariableReference ||
499 lc.getSequence() instanceof Literal;
500 if (oneRef || simpleSeq) {
501 ExpressionTool.replaceVariableReferences(this, lc.getRangeVariable(), lc.getSequence(), !oneRef);
502 clauses.remove(c);
503 if (clauses.isEmpty()) {
504 return getReturnClause();
505 }
506 tryAgain = true;
507 break;
508 }
509 }
510 }
511 }
512 changed |= tryAgain;
513 } while (tryAgain);
514
515 // If changed, remove any redundant trace clauses
516 if (changed) {
517 for (int i = clauses.size() - 1; i >= 1; i--) {
518 if (clauses.get(i).getClauseKey() == Clause.TRACE && clauses.get(i - 1).getClauseKey() == Clause.TRACE) {
519 clauses.remove(i);
520 }
521 }
522 }
523
524 // If any 'where' clause depends on the context item, remove this dependency, because it makes
525 // it easier to rearrange where clauses as predicates
526 boolean depends = false;
527 for (Clause w : clauses) {
528 if (w instanceof WhereClause && ExpressionTool.dependsOnFocus(((WhereClause) w).getPredicate())) {
529 depends = true;
530 break;
531 }
532 }
533 if (depends && contextItemType != null) {
534 Expression expr1 = ExpressionTool.tryToFactorOutDot(this, contextItemType.getItemType());
535 if (expr1 == null || expr1 == this) {
536 //no optimisation possible
537 return this;
538 }
539 resetLocalStaticProperties();
540 return expr1.optimize(visitor, contextItemType);
541 }
542
543 // Now convert any terms within WHERE clauses where possible into predicates on the appropriate
544 // expression bound to a variable on a for clause. This enables the resulting filter expression
545 // to be handled using indexing (in Saxon-EE), and it also reduces the number of items that need
546 // to be tested against the predicate
547
548 Expression expr2 = rewriteWhereClause(visitor, contextItemType);
549 if (expr2 != null && expr2 != this) {
550 return expr2.optimize(visitor, contextItemType);
551 }
552
553 // If the FLWOR expression consists entirely of FOR and LET clauses, convert it to a ForExpression
554 // or LetExpression. This is largely to take advantage of existing optimizations implemented for those
555 // expressions.
556
557 boolean allForOrLetExpr = true;
558 for (Clause c : clauses) {
559 if (c instanceof ForClause) {
560 if (((ForClause)c).getPositionVariable() != null) {
561 allForOrLetExpr = false;
562 break;
563 }
564 } else if (!(c instanceof LetClause)) {
565 allForOrLetExpr = false;
566 break;
567 }
568
569 }
570
571 if (allForOrLetExpr) {
572 return rewriteForOrLet(visitor, contextItemType);
573 }
574
575 return this;
576 }
577
578 /**
579 * @param visitor the expression visitor
580 * @param contextItemType the type of the context item
581 * @return We return this expression, with WhereClauses moved up as far as possible in the list of clauses.
582 * A Where clause cannot move above a Count clause because it changes the number of tuples in the tuple stream.
583 * Alternatively, return null if no rewriting is possible.
584 * @throws XPathException if the rewrite fails for any reason
585 */
586
587 /*@Nullable*/
588 private Expression rewriteWhereClause(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType)
589 throws XPathException {
590 WhereClause whereClause;
591 int whereIndex = 0;
592 class WhereClauseStruct {
593 int whereIndex = 0;
594 WhereClause whereClause;
595 }
596 List<WhereClauseStruct> whereList = new ArrayList<>();
597
598 for (Clause c : clauses) {
599 if (c instanceof WhereClause) {
600 WhereClauseStruct wStruct = new WhereClauseStruct();
601 wStruct.whereClause = (WhereClause) c;
602
603 //keep track of whereclause from the end of the list of clauses.
604 //We are always attempting to rewrite whereclauses from left to right,
605 // therefore index will always be in snyc
606 wStruct.whereIndex = clauses.size() - whereIndex;
607 whereList.add(wStruct);
608 }
609 whereIndex++;
610 }
611
612 if (whereList.size() == 0) {
613 return null;
614 }
615
616 while (!whereList.isEmpty()) {
617 whereClause = whereList.get(0).whereClause;
618 whereIndex = whereList.get(0).whereIndex;
619 Expression condition = whereClause.getPredicate();
620 List<Expression> list = new ArrayList<>(5);
621 BooleanExpression.listAndComponents(condition, list);
622 for (int i = list.size() - 1; i >= 0; i--) {
623 Expression term = list.get(i);
624 for (int c = clauses.size() - whereIndex - 1; c >= 0; c--) {
625 Clause clause = clauses.get(c);
626 Binding[] bindingList = clause.getRangeVariables();
627
628 // Find the first clause prior to the where clause that declares variables on which the
629 // term of the where clause depends
630
631 if (ExpressionTool.dependsOnVariable(term, bindingList) || clause.getClauseKey() == Clause.COUNT) {
632 // remove this term from the where clause
633 Expression removedExpr = list.remove(i);
634 if (list.isEmpty()) {
635 // the where clause has no terms left, so remove the clause
636 clauses.remove(clauses.size() - whereIndex);
637 } else {
638 // change the predicate of the where clause to use only those terms that remain
639 whereClause.setPredicate(makeAndCondition(list));
640 }
641 if ((clause instanceof ForClause) && !((ForClause) clause).isAllowingEmpty()) {
642 // if the clause is a "for" clause, try to add the term as a predicate
643 boolean added = ((ForClause) clause).addPredicate(this, visitor, contextItemType, term);
644 //If we cannot add the WhereClause term as a predicate then put it back into the list of clauses
645 if (!added) {
646 clauses.add(c + 1, new WhereClause(this, removedExpr));
647 }
648 } else {
649 // the clause is not a "for" clause, so just move the "where" to this place in the list of clauses
650 WhereClause newWhere = new WhereClause(this, term);
651 clauses.add(c + 1, newWhere);
652 }
653 // we found a variable on which the term depends so we can't move it any further
654 break;
655 }
656 }
657 if (list.size() - 1 == i) {
658 list.remove(i);
659 if (list.isEmpty()) {
660 clauses.remove(clauses.size() - whereIndex);
661 } else {
662 whereClause.setPredicate(makeAndCondition(list));
663 }
664 WhereClause newWhere = new WhereClause(this, term);
665 clauses.add(0, newWhere);
666 }
667 }
668
669 whereList.remove(0);
670 }
671 return this;
672 }
673
674 /**
675 * Recursive method to make a list of expressions into a AndExpression
676 *
677 * @param list of Expression
678 * @return And Expression of list of expressions
679 */
680 private Expression makeAndCondition(List<Expression> list) {
681 if (list.size() == 1) {
682 return list.get(0);
683 } else {
684 return new AndExpression(list.get(0), makeAndCondition(list.subList(1, list.size())));
685 }
686 }
687
688 /**
689 * Rewrite a FLWOR expression that consists entirely of "for" and "let" clauses as
690 * a LetExpression or ForExpression
691 *
692 * @param visitor - ExpressionVisitor
693 * @param contextItemType - ExpressionVisitor.ContextItemTyp
694 * @return the rewritten expression
695 * @throws net.sf.saxon.trans.XPathException
696 * if an error occurs
697 */
698 /*@NotNull*/
699 private Expression rewriteForOrLet(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
700
701 Expression action = getReturnClause();
702 CodeInjector injector = null;
703 if (visitor.getStaticContext() instanceof QueryModule) {
704 injector = ((QueryModule) visitor.getStaticContext()).getCodeInjector();
705 }
706
707 for (int i = clauses.size() - 1; i >= 0; i--) {
708
709 if (clauses.get(i) instanceof ForClause) {
710 ForClause forClause = (ForClause) clauses.get(i);
711 ForExpression forExpr;
712 if (forClause.isAllowingEmpty()) {
713 forExpr = new OuterForExpression();
714 } else {
715 forExpr = new ForExpression();
716 }
717
718 forExpr.setLocation(forClause.getLocation());
719 forExpr.setRetainedStaticContext(getRetainedStaticContext());
720 //forExpr.setParentExpression(getParentExpression());
721 forExpr.setAction(action);
722
723 forExpr.setSequence(forClause.getSequence());
724 forExpr.setVariableQName(forClause.getRangeVariable().getVariableQName());
725 forExpr.setRequiredType(forClause.getRangeVariable().getRequiredType());
726 ExpressionTool.rebindVariableReferences(action, forClause.getRangeVariable(), forExpr);
727 action = forExpr;
728
729 if (injector != null) {
730 action = injector.inject(action, visitor.getStaticContext(), LocationKind.FOR_EXPRESSION, forExpr.getVariableQName());
731 }
732
733 } else {
734 LetClause letClause = (LetClause) clauses.get(i);
735 LetExpression letExpr = new LetExpression();
736 letExpr.setLocation(letClause.getLocation());
737 letExpr.setRetainedStaticContext(getRetainedStaticContext());
738 //letExpr.setParentExpression(getParentExpression());
739 letExpr.setAction(action);
740 letExpr.setSequence(letClause.getSequence());
741 letExpr.setVariableQName(letClause.getRangeVariable().getVariableQName());
742 letExpr.setRequiredType(letClause.getRangeVariable().getRequiredType());
743 if (letClause.getRangeVariable().isIndexedVariable()) {
744 letExpr.setIndexedVariable();
745 }
746 //letExpr.setRefCount(letClause.getRangeVariable().getNominalReferenceCount());
747 ExpressionTool.rebindVariableReferences(action, letClause.getRangeVariable(), letExpr);
748 action = letExpr;
749
750 if (injector != null) {
751 action = injector.inject(action, visitor.getStaticContext(), LocationKind.LET_EXPRESSION, letExpr.getVariableQName());
752 }
753 }
754
755 }
756 action = action.typeCheck(visitor, contextItemType);
757 action = action.optimize(visitor, contextItemType);
758 return action;
759 }
760
761 /**
762 * Return an Iterator to iterate over the values of a sequence. The value of every
763 * expression can be regarded as a sequence, so this method is supported for all
764 * expressions. This default implementation handles iteration for expressions that
765 * return singleton values: for non-singleton expressions, the subclass must
766 * provide its own implementation.
767 *
768 * @param context supplies the context for evaluation
769 * @return a SequenceIterator that can be used to iterate over the result
770 * of the expression
771 * @throws net.sf.saxon.trans.XPathException
772 * if any dynamic error occurs evaluating the
773 * expression
774 */
775 /*@NotNull*/
776 @Override
777 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
778 TuplePull stream = new SingularityPull();
779 for (Clause c : clauses) {
780 stream = c.getPullStream(stream, context);
781 }
782 return new ReturnClauseIterator(stream, this, context);
783 }
784
785
786 /**
787 * Process the instruction, without returning any tail calls
788 *
789 * @param context The dynamic context, giving access to the current node,
790 * the current variables, etc.
791 * @throws XPathException if a dynamic error occurs
792 */
793 @Override
794 public void process(XPathContext context) throws XPathException {
795 TuplePush destination = new ReturnClausePush(getReturnClause());
796 for (int i = clauses.size() - 1; i >= 0; i--) {
797 Clause c = clauses.get(i);
798 destination = c.getPushStream(destination, context);
799 }
800 destination.processTuple(context);
801 destination.close();
802 }
803
804 /**
805 * Evaluate an updating expression, adding the results to a Pending Update List.
806 * The default implementation of this method, which is used for non-updating expressions,
807 * throws an UnsupportedOperationException
808 *
809 * @param context the XPath dynamic evaluation context
810 * @param pul the pending update list to which the results should be written
811 * @throws net.sf.saxon.trans.XPathException
812 * if evaluation fails
813 * @throws UnsupportedOperationException if the expression is not an updating expression
814 */
815
816
817 @Override
818 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
819 TuplePull stream = new SingularityPull();
820 for (Clause c : clauses) {
821 stream = c.getPullStream(stream, context);
822 }
823 while (stream.nextTuple(context)) {
824 getReturnClause().evaluatePendingUpdates(context, pul);
825 }
826 }
827
828 /**
829 * Get a name identifying the kind of expression, in terms meaningful to a user.
830 *
831 * @return a name identifying the kind of expression, in terms meaningful to a user.
832 * The name will always be in the form of a lexical XML QName, and should match the name used
833 * in export() output displaying the expression.
834 */
835 @Override
836 public String getExpressionName() {
837 return "FLWOR";
838 }
839
840 /**
841 * Produce a short string identifying the expression for use in error messages
842 *
843 * @return a short string, sufficient to identify the expression
844 */
845 @Override
846 public String toShortString() {
847 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
848 sb.append(clauses.get(0).toShortString());
849 sb.append(" ... return ");
850 sb.append(getReturnClause().toShortString());
851 return sb.toString();
852 }
853
854 /**
855 * Display the expression as a string
856 */
857
858 public String toString() {
859 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
860 for (Clause c : clauses) {
861 sb.append(c.toString());
862 sb.append(' ');
863 }
864 sb.append(" return ");
865 sb.append(getReturnClause().toString());
866 return sb.toString();
867 }
868
869 /**
870 * Determine whether a variable reference found within a clause of a FLWOR expression is a looping
871 * reference, that is, whether the variable is used more than once
872 *
873 * @param binding the variable binding, which may be bound in a clause of the same FLWOR expression,
874 * or in some containing expression
875 * @return true if a reference to the variable occurs within a loop relative to the binding, that is, if the
876 * variable's value is used more than once. Note that this method only detects a loop that is due to the clauses
877 * of this FLWOR expression itself. A loop in an inner expression or outer expression of the FLWOR expression must
878 * be detected by the caller.
879 */
880
881 public boolean hasLoopingVariableReference(final Binding binding) {
882
883 // Determine the clause that binds the variable (if any)
884
885 int bindingClause = -1;
886 for (int i = 0; i < clauses.size(); i++) {
887 if (clauseHasBinding(clauses.get(i), binding)) {
888 bindingClause = i;
889 break;
890 }
891 }
892
893 boolean boundOutside = bindingClause < 0;
894 if (boundOutside) {
895 bindingClause = 0;
896 }
897
898 // Determine the last clause that contains a reference to the variable.
899 // (If any reference to the variable is a looping reference, then the last one will be)
900
901 int lastReferencingClause = clauses.size(); // indicates the return clause
902 if (!ExpressionTool.dependsOnVariable(getReturnClause(), new Binding[]{binding})) {
903 // artifice to get a response value from the generic processExpression() method
904 final List<Boolean> response = new ArrayList<>();
905 OperandProcessor checker = op -> {
906 if (response.isEmpty() &&
907 ExpressionTool.dependsOnVariable(op.getChildExpression(), new Binding[]{binding})) {
908 response.add(true);
909 }
910 };
911 for (int i = clauses.size() - 1; i >= 0; i--) {
912 try {
913 clauses.get(i).processOperands(checker);
914 if (!response.isEmpty()) {
915 lastReferencingClause = i;
916 break;
917 }
918 } catch (XPathException e) {
919 assert false;
920 }
921 }
922 }
923
924 // If any clause between the binding clause and the last referencing clause is a looping clause,
925 // then the variable is used within a loop
926
927 for (int i = lastReferencingClause - 1; i >= bindingClause; i--) {
928 if (isLoopingClause(clauses.get(i))) {
929 return true;
930 }
931 }
932
933 // otherwise there is no loop caused by the clauses of the FLWOR expression itself.
934
935 return false;
936 }
937
938 }
939