Debian Codegraph @

net/sf/saxon/expr/flwor/ForClause.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.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.functions.KeyFn;
14 import net.sf.saxon.functions.SystemFunction;
15 import net.sf.saxon.lib.Feature;
16 import net.sf.saxon.trace.ExpressionPresenter;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.tree.util.FastStringBuffer;
19 import net.sf.saxon.type.*;
20 import net.sf.saxon.value.Cardinality;
21 import net.sf.saxon.value.SequenceType;
22
23 import java.util.ArrayList;
24 import java.util.List;
25
26 /**
27 * A "for" clause in a FLWOR expression
28 */
29 public class ForClause extends Clause {
30
31 private LocalVariableBinding rangeVariable;
32 /*@Nullable*/
33 private LocalVariableBinding positionVariable;
34 private Operand sequenceOp;
35 private boolean allowsEmpty;
36
37 public ForClause() {
38 }
39
40 @Override
41 public int getClauseKey() {
42 return FOR;
43 }
44
45 public ForClause copy(FLWORExpression flwor, RebindingMap rebindings) {
46 ForClause f2 = new ForClause();
47 f2.setLocation(getLocation());
48 f2.setPackageData(getPackageData());
49 f2.rangeVariable = rangeVariable.copy();
50 if (positionVariable != null) {
51 f2.positionVariable = positionVariable.copy();
52 }
53 f2.initSequence(flwor, getSequence().copy(rebindings));
54 f2.allowsEmpty = allowsEmpty;
55 return f2;
56 }
57
58 public void initSequence(FLWORExpression flwor, Expression sequence) {
59 sequenceOp = new Operand(flwor, sequence, isRepeated() ? OperandRole.REPEAT_NAVIGATE : OperandRole.NAVIGATE);
60 }
61
62 public void setSequence(Expression sequence) {
63 sequenceOp.setChildExpression(sequence);
64 }
65
66 public Expression getSequence() {
67 return sequenceOp.getChildExpression();
68 }
69
70 /**
71 * Set the range variable (the primary variable bound by this clause)
72 *
73 * @param binding the range variable
74 */
75
76 public void setRangeVariable(LocalVariableBinding binding) {
77 rangeVariable = binding;
78 }
79
80 /**
81 * Get the range variable (the primary variable bound by this clause)
82 *
83 * @return the range variable
84 */
85
86 public LocalVariableBinding getRangeVariable() {
87 return rangeVariable;
88 }
89
90 /**
91 * Set the position variable (the variable bound by the "at" clause)
92 *
93 * @param binding the position variable, or null if there is no position variable
94 */
95
96 public void setPositionVariable(/*@Nullable*/ LocalVariableBinding binding) {
97 positionVariable = binding;
98 }
99
100 /**
101 * Get the position variable (the variable bound by the "at" clause)
102 *
103 * @return the position variable, or null if there is no position variable
104 */
105
106 /*@Nullable*/
107 public LocalVariableBinding getPositionVariable() {
108 return positionVariable;
109 }
110
111 /**
112 * Get the number of variables bound by this clause
113 *
114 * @return the number of variable bindings (1 or 2 depending on whether there is a position variable)
115 */
116 @Override
117 public LocalVariableBinding[] getRangeVariables() {
118 if (positionVariable == null) {
119 return new LocalVariableBinding[]{rangeVariable};
120 } else {
121 return new LocalVariableBinding[]{rangeVariable, positionVariable};
122 }
123 }
124
125 /**
126 * Say whether the "allowing empty" option is present
127 *
128 * @param option true if the "allowing empty" option is present
129 */
130
131 public void setAllowingEmpty(boolean option) {
132 allowsEmpty = option;
133 }
134
135 /**
136 * Ask whether the "allowing empty" option is present
137 *
138 * @return true if the "allowing empty" option is present
139 */
140
141 public boolean isAllowingEmpty() {
142 return allowsEmpty;
143 }
144
145 /**
146 * Type-check the expression
147 */
148 @Override
149 public void typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
150 SequenceType decl = rangeVariable.getRequiredType();
151 if (allowsEmpty && !Cardinality.allowsZero(decl.getCardinality())) {
152 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, rangeVariable.getVariableQName().getDisplayName(), 0);
153 Expression checker =
154 CardinalityChecker.makeCardinalityChecker(
155 getSequence(), StaticProperty.ALLOWS_ONE_OR_MORE, role);
156 setSequence(checker);
157 }
158 SequenceType sequenceType = SequenceType.makeSequenceType(
159 decl.getPrimaryType(), StaticProperty.ALLOWS_ZERO_OR_MORE);
160 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, rangeVariable.getVariableQName().getDisplayName(), 0);
161 setSequence(
162 TypeChecker.strictTypeCheck(
163 getSequence(), sequenceType, role, visitor.getStaticContext()));
164 }
165
166 /**
167 * Get a tuple stream that implements the functionality of this clause, taking its
168 * input from another tuple stream which this clause modifies
169 *
170 * @param base the input tuple stream
171 * @param context the XPath dynamic context
172 * @return the output tuple stream
173 */
174 @Override
175 public TuplePull getPullStream(TuplePull base, XPathContext context) {
176 if (allowsEmpty) {
177 return new ForClauseOuterPull(base, this);
178 } else {
179 return new ForClausePull(base, this);
180 }
181 }
182
183 /**
184 * Get a push-mode tuple stream that implements the functionality of this clause, supplying its
185 * output to another tuple stream
186 *
187 * @param destination the output tuple stream
188 * @param context the dynamic evaluation context
189 * @return the push tuple stream that implements the functionality of this clause of the FLWOR
190 * expression
191 */
192 @Override
193 public TuplePush getPushStream(TuplePush destination, XPathContext context) {
194 if (allowsEmpty) {
195 return new ForClauseOuterPush(destination, this);
196 } else {
197 return new ForClausePush(destination, this);
198 }
199 }
200
201 /**
202 * Convert where clause to a predicate.
203 *
204 * @param flwor the FLWOR expression (sans the relevant part of the where clause)
205 * @param visitor the expression visitor
206 * @param contextItemType the item type of the context item
207 * @param condition the predicate to be added. This will always be a single term (never a composite condition
208 * using "and"), as the where clause is split into separate terms before calling this method
209 * @return true if the expression has been changed, that is, if the where clause has been converted
210 * @throws XPathException if an error is encountered
211 */
212
213 public boolean addPredicate(FLWORExpression flwor, ExpressionVisitor visitor, ContextItemStaticInfo contextItemType, Expression condition) throws XPathException {
214 Configuration config = getConfiguration();
215 Optimizer opt = visitor.obtainOptimizer();
216 boolean debug = config.getBooleanProperty(Feature.TRACE_OPTIMIZER_DECISIONS);
217
218 // assert: condition has no dependency on context item. We removed any such dependency before we got here.
219
220 final TypeHierarchy th = config.getTypeHierarchy();
221 Expression head = null;
222 Expression selection = getSequence();
223 ItemType selectionContextItemType = contextItemType == null ? null : contextItemType.getItemType();
224 if (getSequence() instanceof SlashExpression) {
225 if (((SlashExpression) getSequence()).isAbsolute()) {
226 head = ((SlashExpression) getSequence()).getFirstStep();
227 selection = ((SlashExpression) getSequence()).getRemainingSteps();
228 selectionContextItemType = head.getItemType();
229 } else {
230 SlashExpression p = ((SlashExpression) getSequence()).tryToMakeAbsolute();
231 if (p != null) {
232 setSequence(p);
233 head = p.getFirstStep();
234 selection = p.getRemainingSteps();
235 selectionContextItemType = head.getItemType();
236 }
237 }
238 }
239
240 boolean changed = false;
241
242 // Process each term in the where clause independently
243
244 if (positionVariable != null &&
245 (condition instanceof ValueComparison || condition instanceof GeneralComparison || condition instanceof CompareToIntegerConstant) &&
246 ExpressionTool.dependsOnVariable(condition, new Binding[]{positionVariable})) {
247 ComparisonExpression comp = (ComparisonExpression) condition;
248 Expression[] operands = new Expression[]{comp.getLhsExpression(), comp.getRhsExpression()};
249
250 if (ExpressionTool.dependsOnVariable(flwor, new Binding[]{positionVariable})) {
251 // cannot convert a positional where clause into a positional predicate if there are
252 // other references to the position variable
253 return false;
254 }
255
256 for (int op = 0; op < 2; op++) {
257
258 // If the where clause is a simple test on the position variable, for example
259 // for $x at $p in EXPR where $p = 5 return A
260 // then absorb the where condition into a predicate, rewriting it as
261 // for $x in EXPR[position() = 5] return A
262 // This takes advantage of the optimizations applied to positional filter expressions
263 // Only do this if the sequence expression has not yet been changed, because
264 // the position in a predicate after the first is different. And only do it if this
265 // is the only reference to the position variable, because if there are other references,
266 // the existence of the predicate will change the values of the position variable.
267 Binding[] thisVar = {this.getRangeVariable()};
268 if (positionVariable != null && operands[op] instanceof VariableReference && !changed) {
269 List<VariableReference> varRefs = new ArrayList<>();
270 ExpressionTool.gatherVariableReferences(condition, positionVariable, varRefs);
271 if (varRefs.size() == 1 && varRefs.get(0) == operands[op] &&
272 !ExpressionTool.dependsOnFocus(operands[1 - op]) &&
273 !ExpressionTool.dependsOnVariable(operands[1 - op], thisVar)) {
274 RetainedStaticContext rsc = new RetainedStaticContext(visitor.getStaticContext());
275 Expression position =
276 SystemFunction.makeCall("position", rsc);
277 Expression predicate = condition.copy(new RebindingMap());
278 Operand child = op == 0
279 ? ((ComparisonExpression)predicate).getLhs()
280 : ((ComparisonExpression)predicate).getRhs();
281 child.setChildExpression(position);
282 if (debug) {
283 opt.trace("Replaced positional variable in predicate by position()", predicate);
284 }
285 selection = new FilterExpression(selection, predicate);
286 ExpressionTool.copyLocationInfo(predicate, selection);
287 ContextItemStaticInfo cit = config.makeContextItemStaticInfo(selectionContextItemType, true);
288 selection = selection.typeCheck(visitor, cit);
289 if (!ExpressionTool.dependsOnVariable(flwor, new Binding[]{positionVariable})) {
290 positionVariable = null;
291 }
292 changed = true;
293 break;
294 }
295 }
296 }
297 }
298
299 if (positionVariable == null) {
300 Binding[] thisVar = {this.getRangeVariable()};
301 if (opt.isVariableReplaceableByDot(condition, thisVar)) {
302
303 // When rewriting the where expression as a filter, we have to replace references to the
304 // range variable by references to the context item. If we can do this directly, we do. But
305 // if the reference to the range variable occurs inside a predicate, or on the rhs of slash,
306 // we have to bind a new variable to the context item. So for example "for $x in S where
307 // T[abc = $x]" gets rewritten as "for $x in S[let $dot := . return T[abc = $dot]]"
308 //if (useDotDirectly) {
309 Expression replacement = new ContextItemExpression();
310
311 boolean found = ExpressionTool.inlineVariableReferences(condition, this.getRangeVariable(), replacement);
312 if (found) {
313 ContextItemStaticInfo cit = config.makeContextItemStaticInfo(getSequence().getItemType(), true);
314 Expression predicate = condition.typeCheck(visitor, cit);
315 // If the result of the predicate might be a number, wrap it in a call of boolean()
316 int rel = th.relationship(predicate.getItemType(), BuiltInAtomicType.INTEGER);
317 if (rel != TypeHierarchy.DISJOINT) {
318 RetainedStaticContext rsc = new RetainedStaticContext(visitor.getStaticContext());
319 predicate = SystemFunction.makeCall("boolean", rsc, predicate);
320 assert predicate != null;
321 }
322 selection = new FilterExpression(selection, predicate);
323 ExpressionTool.copyLocationInfo(predicate, selection);
324 cit = config.makeContextItemStaticInfo(selectionContextItemType, true);
325 selection = selection.typeCheck(visitor, cit);
326 changed = true;
327 }
328 }
329
330 }
331 if (changed) {
332
333 if (head == null) {
334 setSequence(selection);
335 } else if (head instanceof RootExpression && selection.isCallOn(KeyFn.class)) {
336 setSequence(selection);
337 } else {
338 Expression path = ExpressionTool.makePathExpression(head, selection);
339 if (path instanceof SlashExpression) {
340 ExpressionTool.copyLocationInfo(condition, path);
341 Expression k = visitor.obtainOptimizer().convertPathExpressionToKey((SlashExpression) path, visitor);
342 if (k == null) {
343 setSequence(path);
344 } else {
345 setSequence(k);
346 }
347 sequenceOp.typeCheck(visitor, contextItemType);
348 sequenceOp.optimize(visitor, contextItemType);
349 }
350 }
351 }
352 return changed;
353 }
354
355 /**
356 * Process the subexpressions of this clause
357 *
358 * @param processor the expression processor used to process the subexpressions
359 */
360 @Override
361 public void processOperands(OperandProcessor processor) throws XPathException {
362 processor.processOperand(sequenceOp);
363 }
364
365 @Override
366 public void gatherVariableReferences(final ExpressionVisitor visitor, Binding binding, List<VariableReference> references) {
367 ExpressionTool.gatherVariableReferences(getSequence(), binding, references);
368 }
369
370 @Override
371 public void refineVariableType(ExpressionVisitor visitor, List<VariableReference> references, Expression returnExpr) {
372 ItemType actualItemType = getSequence().getItemType();
373 if (actualItemType instanceof ErrorType) {
374 actualItemType = AnyItemType.getInstance();
375 }
376 for (VariableReference ref : references) {
377 ref.refineVariableType(actualItemType,
378 allowsEmpty ? StaticProperty.ALLOWS_ZERO_OR_ONE : StaticProperty.EXACTLY_ONE,
379 null, getSequence().getSpecialProperties());
380 }
381 }
382
383 @Override
384 public void addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
385 PathMap.PathMapNodeSet varPath = getSequence().addToPathMap(pathMap, pathMapNodeSet);
386 pathMap.registerPathForVariable(rangeVariable, varPath);
387 }
388
389 /**
390 * Diagnostic print of expression structure. The abstract expression tree
391 * is written to the supplied output destination.
392 *
393 * @param out the expression presenter used to display the structure
394 */
395 @Override
396 public void explain(ExpressionPresenter out) throws XPathException {
397 out.startElement("for");
398 out.emitAttribute("var", getRangeVariable().getVariableQName());
399 out.emitAttribute("slot", getRangeVariable().getLocalSlotNumber() + "");
400 LocalVariableBinding posVar = getPositionVariable();
401 if (posVar != null) {
402 out.emitAttribute("at", posVar.getVariableQName());
403 out.emitAttribute("at-slot", posVar.getLocalSlotNumber() + "");
404 }
405 getSequence().export(out);
406 out.endElement();
407 }
408
409 public String toShortString() {
410 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
411 fsb.append("for $");
412 fsb.append(rangeVariable.getVariableQName().getDisplayName());
413 fsb.append(' ');
414 LocalVariableBinding posVar = getPositionVariable();
415 if (posVar != null) {
416 fsb.append("at $");
417 fsb.append(posVar.getVariableQName().getDisplayName());
418 fsb.append(' ');
419 }
420 fsb.append("in ");
421 fsb.append(getSequence().toShortString());
422 return fsb.toString();
423 }
424
425 public String toString() {
426 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
427 fsb.append("for $");
428 fsb.append(rangeVariable.getVariableQName().getDisplayName());
429 fsb.append(' ');
430 LocalVariableBinding posVar = getPositionVariable();
431 if (posVar != null) {
432 fsb.append("at $");
433 fsb.append(posVar.getVariableQName().getDisplayName());
434 fsb.append(' ');
435 }
436 fsb.append("in ");
437 fsb.append(getSequence().toString());
438 return fsb.toString();
439 }
440 }
441