Debian Codegraph @

net/sf/saxon/expr/instruct/ForEach.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.instruct;
9
10 import net.sf.saxon.Controller;
11 import net.sf.saxon.event.PipelineConfiguration;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.lib.TraceListener;
15 import net.sf.saxon.om.FocusIterator;
16 import net.sf.saxon.om.Item;
17 import net.sf.saxon.om.SequenceIterator;
18 import net.sf.saxon.om.StandardNames;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.type.ErrorType;
22 import net.sf.saxon.type.ItemType;
23 import net.sf.saxon.type.SchemaType;
24 import net.sf.saxon.type.UType;
25 import net.sf.saxon.value.Cardinality;
26
27
28 /**
29 * Handler for xsl:for-each elements in a stylesheet. The same class handles the "!" operator in XPath 3.0,
30 * which has identical semantics to xsl:for-each, and it is used to support the "/" operator in cases where it
31 * is known that the rhs delivers atomic values.
32 */
33
34 public class ForEach extends Instruction implements ContextMappingFunction<Item<?>>, ContextSwitchingExpression {
35
36 protected boolean containsTailCall;
37 protected Operand selectOp;
38 protected Operand actionOp;
39 protected Operand threadsOp;
40 protected boolean isInstruction;
41
42 /**
43 * Create an xsl:for-each instruction
44 *
45 * @param select the select expression
46 * @param action the body of the xsl:for-each loop
47 */
48
49 public ForEach(Expression select, Expression action) {
50 this(select, action, false, null);
51 }
52
53 /**
54 * Create an xsl:for-each instruction
55 *
56 * @param select the select expression
57 * @param action the body of the xsl:for-each loop
58 * @param containsTailCall true if the body of the loop contains a tail call on the containing function
59 * @param threads if &gt;1 causes multithreaded execution (Saxon-EE only)
60 */
61
62 public ForEach(Expression select, Expression action, boolean containsTailCall, Expression threads) {
63 selectOp = new Operand(this, select, OperandRole.FOCUS_CONTROLLING_SELECT);
64 actionOp = new Operand(this, action, OperandRole.FOCUS_CONTROLLED_ACTION);
65 if (threads != null) {
66 threadsOp = new Operand(this, threads, OperandRole.SINGLE_ATOMIC);
67 }
68 this.containsTailCall = containsTailCall && action instanceof TailCallReturner;
69 }
70
71 /**
72 * Say whether this ForEach expression originates as an XSLT instruction
73 *
74 * @param inst true if this is an xsl:for-each instruction; false if it is the XPath "!" operator
75 */
76
77 public void setInstruction(boolean inst) {
78 isInstruction = inst;
79 }
80
81 /**
82 * Ask whether this expression is an instruction. In XSLT streamability analysis this
83 * is used to distinguish constructs corresponding to XSLT instructions from other constructs.
84 *
85 * @return true if this construct originates as an XSLT instruction
86 */
87
88 @Override
89 public boolean isInstruction() {
90 return isInstruction;
91 }
92
93
94 /**
95 * Get the select expression
96 *
97 * @return the select expression. Note this will have been wrapped in a sort expression
98 * if sorting was requested.
99 */
100
101 public Expression getSelect() {
102 return selectOp.getChildExpression();
103 }
104
105 /**
106 * Set the select expression
107 * @param select the select expression of the for-each
108 */
109
110 public void setSelect(Expression select) {
111 selectOp.setChildExpression(select);
112 }
113
114 /**
115 * Get the action expression (in XSLT, the body of the xsl:for-each instruction
116 * @return the action expression
117 */
118
119 public Expression getAction() {
120 return actionOp.getChildExpression();
121 }
122
123 /**
124 * Set the action expression (in XSLT, the body of the xsl:for-each instruction)
125 * @param action the action expression
126 */
127
128 public void setAction(Expression action) {
129 actionOp.setChildExpression(action);
130 }
131
132 /**
133 * Get the expression used to determine how many threads to use when multi-threading
134 * @return the saxon:threads expression if present, or null otherwise
135 */
136
137 public Expression getThreads() {
138 return threadsOp == null ? null : threadsOp.getChildExpression();
139 }
140
141 /**
142 * Set the expression used to determine how many threads to use when multi-threading
143 * @param threads the saxon:threads expression if present, or null otherwise
144 */
145
146 public void setThreads(Expression threads) {
147 if (threads != null) {
148 if (threadsOp == null) {
149 threadsOp = new Operand(this, threads, OperandRole.SINGLE_ATOMIC);
150 } else {
151 threadsOp.setChildExpression(threads);
152 }
153 }
154 }
155
156 /**
157 * Get the operands of this expression
158 * @return the operands
159 */
160
161 @Override
162 public Iterable<Operand> operands() {
163 if (threadsOp == null) {
164 return operandList(selectOp, actionOp);
165 } else {
166 return operandList(selectOp, actionOp, threadsOp);
167 }
168 }
169
170 /**
171 * Get the name of this instruction for diagnostic and tracing purposes
172 *
173 * @return the code for name xsl:for-each
174 */
175
176 public int getInstructionNameCode() {
177 return StandardNames.XSL_FOR_EACH;
178 }
179
180 /**
181 * Get the select expression
182 *
183 * @return the select expression. Note this will have been wrapped in a sort expression
184 * if sorting was requested.
185 */
186
187 public Expression getSelectExpression() {
188 return getSelect();
189 }
190
191 /**
192 * Set the select expression
193 *
194 * @param select the select expression
195 */
196
197 public void setSelectExpression(Expression select) {
198 this.setSelect(select);
199 }
200
201 /**
202 * Set the action expression
203 *
204 * @param action the select expression
205 */
206
207 public void setActionExpression(Expression action) {
208 this.setAction(action);
209 }
210
211 /**
212 * Get the subexpression that is evaluated in the new context
213 *
214 * @return the subexpression evaluated in the context set by the controlling expression
215 */
216 public Expression getActionExpression() {
217 return getAction();
218 }
219
220 /**
221 * Get the number of threads requested
222 *
223 * @return the value of the saxon:threads attribute
224 */
225
226 public Expression getNumberOfThreadsExpression() {
227 return getThreads();
228 }
229
230 /**
231 * Determine the data type of the items returned by this expression
232 *
233 * @return the data type
234 */
235
236 /*@NotNull*/
237 public final ItemType getItemType() {
238 return getAction().getItemType();
239 }
240
241
242 /**
243 * Get the static type of the expression as a UType, following precisely the type
244 * inference rules defined in the XSLT 3.0 specification.
245 *
246 * @return the static item type of the expression according to the XSLT 3.0 defined rules
247 * @param contextItemType static type of the context item
248 */
249 @Override
250 public UType getStaticUType(UType contextItemType) {
251 if (isInstruction()) {
252 return super.getStaticUType(contextItemType);
253 } else {
254 return getAction().getStaticUType(getSelect().getStaticUType(contextItemType));
255 }
256 }
257
258
259 /**
260 * Determine whether this instruction creates new nodes.
261 * This implementation returns true if the "action" creates new nodes.
262 * (Nodes created by the condition can't contribute to the result).
263 */
264
265 public final boolean mayCreateNewNodes() {
266 int props = getAction().getSpecialProperties();
267 return (props & StaticProperty.NO_NODES_NEWLY_CREATED) == 0;
268 }
269
270 /*@NotNull*/
271 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
272
273 selectOp.typeCheck(visitor, contextInfo);
274
275 ItemType selectType = getSelect().getItemType();
276 if (selectType == ErrorType.getInstance()) {
277 return Literal.makeEmptySequence();
278 }
279
280 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(getSelect().getItemType(), false);
281 cit.setContextSettingExpression(getSelect());
282 actionOp.typeCheck(visitor, cit);
283
284 if (!Cardinality.allowsMany(getSelect().getCardinality())) {
285 actionOp.setOperandRole(actionOp.getOperandRole().modifyProperty(OperandRole.SINGLETON, true));
286 }
287
288 return this;
289 }
290
291 /*@NotNull*/
292 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
293 selectOp.optimize(visitor, contextInfo);
294
295 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(getSelect().getItemType(), false);
296 cit.setContextSettingExpression(getSelect());
297 actionOp.optimize(visitor, cit);
298
299 if (!visitor.isOptimizeForStreaming()) {
300 // Don't eliminate a void for-each if streaming, because it can consume the stream: see test accumulator-015
301 if (Literal.isEmptySequence(getSelect())) {
302 return getSelect();
303 }
304 if (Literal.isEmptySequence(getAction())) {
305 return getAction();
306 }
307 }
308
309 if (threadsOp != null && !Literal.isEmptySequence(getThreads())) {
310 return visitor.obtainOptimizer().generateMultithreadedInstruction(this);
311 }
312 return this;
313 }
314
315 /**
316 * Replace this expression by a simpler expression that delivers the results without regard
317 * to order.
318 *
319 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
320 * original; set to false if the result can eliminate (or introduce) duplicates.
321 * @param forStreaming set to true if optimizing for streaming
322 */
323 @Override
324 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
325 setSelect(getSelect().unordered(retainAllNodes, forStreaming));
326 setAction(getAction().unordered(retainAllNodes, forStreaming));
327 return this;
328 }
329
330 /**
331 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
332 * by an expression in a source tree.
333 * <p>The default implementation of this method assumes that an expression does no navigation other than
334 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
335 * same context as the containing expression. The method must be overridden for any expression
336 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
337 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
338 * functions because they create a new navigation root. Implementations also exist for PathExpression and
339 * FilterExpression because they have subexpressions that are evaluated in a different context from the
340 * calling expression.</p>
341 *
342 * @param pathMap the PathMap to which the expression should be added
343 * @param pathMapNodeSet the set of nodes in the path map that are affected
344 * @return the pathMapNode representing the focus established by this expression, in the case where this
345 * expression is the first operand of a path expression or filter expression. For an expression that does
346 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
347 * expressions, it is the same as the input pathMapNode.
348 */
349
350 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
351 PathMap.PathMapNodeSet target = getSelect().addToPathMap(pathMap, pathMapNodeSet);
352 return getAction().addToPathMap(pathMap, target);
353 }
354
355 /**
356 * Copy an expression. This makes a deep copy.
357 *
358 * @return the copy of the original expression
359 * @param rebindings variables that need to be re-bound
360 */
361
362 /*@NotNull*/
363 public Expression copy(RebindingMap rebindings) {
364 ForEach f2 = new ForEach(getSelect().copy(rebindings), getAction().copy(rebindings), containsTailCall, getThreads());
365 ExpressionTool.copyLocationInfo(this, f2);
366 f2.setInstruction(isInstruction());
367 return f2;
368 }
369
370 /**
371 * Get the static properties of this expression (other than its type). The result is
372 * bit-signficant. These properties are used for optimizations. In general, if
373 * property bit is set, it is true, but if it is unset, the value is unknown.
374 *
375 * @return a set of flags indicating static properties of this expression
376 */
377 @Override
378 public int computeSpecialProperties() {
379 int p = super.computeSpecialProperties();
380 if (getSelect().getCardinality() == StaticProperty.EXACTLY_ONE) {
381 p |= getAction().getSpecialProperties();
382 } else {
383 p |= getAction().getSpecialProperties() & StaticProperty.ALL_NODES_UNTYPED;
384 }
385 return p;
386 }
387
388 @Override
389 public boolean alwaysCreatesNewNodes() {
390 return (getAction() instanceof Instruction) && ((Instruction)getAction()).alwaysCreatesNewNodes();
391 }
392
393 /**
394 * Determine whether this is an updating expression as defined in the XQuery update specification
395 *
396 * @return true if this is an updating expression
397 */
398
399 public boolean isUpdatingExpression() {
400 return getAction().isUpdatingExpression();
401 }
402
403 /**
404 * Check to ensure that this expression does not contain any inappropriate updating subexpressions.
405 * This check is overridden for those expressions that permit updating subexpressions.
406 *
407 * @throws XPathException if the expression has a non-permitted updating subexpression
408 */
409
410 public void checkForUpdatingSubexpressions() throws XPathException {
411 if (getSelect().isUpdatingExpression()) {
412 XPathException err = new XPathException(
413 "Updating expression appears in a context where it is not permitted", "XUST0001");
414 err.setLocation(getSelect().getLocation());
415 throw err;
416 }
417 }
418
419
420 /**
421 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
422 * This method indicates which of these methods is provided. This implementation provides both iterate() and
423 * process() methods natively.
424 */
425
426 public int getImplementationMethod() {
427 return ITERATE_METHOD | PROCESS_METHOD | Expression.WATCH_METHOD | Expression.ITEM_FEED_METHOD;
428 }
429
430 /**
431 * Check that any elements and attributes constructed or returned by this expression are acceptable
432 * in the content model of a given complex type. It's always OK to say yes, since the check will be
433 * repeated at run-time. The process of checking element and attribute constructors against the content
434 * model of a complex type also registers the type of content expected of those constructors, so the
435 * static validation can continue recursively.
436 */
437
438 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
439 getAction().checkPermittedContents(parentType, false);
440 }
441
442 public TailCall processLeavingTail(XPathContext context) throws XPathException {
443 Controller controller = context.getController();
444 assert controller != null;
445
446 XPathContextMajor c2 = context.newContext();
447 c2.setOrigin(this);
448 FocusIterator<?> iter = c2.trackFocus(getSelect().iterate(context));
449 c2.setCurrentTemplateRule(null);
450
451 Expression action = getAction();
452 if (containsTailCall) {
453 if (controller.isTracing()) {
454 TraceListener listener = controller.getTraceListener();
455 assert listener != null;
456 Item item = iter.next();
457 if (item == null) {
458 return null;
459 }
460 listener.startCurrentItem(item);
461 TailCall tc = ((TailCallReturner) action).processLeavingTail(c2);
462 listener.endCurrentItem(item);
463 return tc;
464 } else {
465 Item item = iter.next();
466 if (item == null) {
467 return null;
468 }
469 return ((TailCallReturner) action).processLeavingTail(c2);
470 }
471 } else {
472 PipelineConfiguration pipe = c2.getReceiver().getPipelineConfiguration();
473 pipe.setXPathContext(c2);
474 if (controller.isTracing()) {
475 TraceListener listener = controller.getTraceListener();
476 assert listener != null;
477 Item item;
478 while ((item = iter.next()) != null) {
479 listener.startCurrentItem(item);
480 action.process(c2);
481 listener.endCurrentItem(item);
482 }
483 } else {
484 iter.forEachOrFail(item -> action.process(c2));
485 }
486 pipe.setXPathContext(context);
487 }
488 return null;
489 }
490
491 /**
492 * Return an Iterator to iterate over the values of the sequence.
493 *
494 * @param context supplies the context for evaluation
495 * @return a SequenceIterator that can be used to iterate over the result
496 * of the expression
497 * @throws XPathException if any dynamic error occurs evaluating the
498 * expression
499 */
500
501 /*@NotNull*/
502 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
503 XPathContextMinor c2 = context.newMinorContext();
504 c2.trackFocus(getSelect().iterate(context));
505 return new ContextMappingIterator<>(this, c2);
506 }
507
508 /**
509 * Map one item to a sequence.
510 *
511 * @param context The processing context. The item to be mapped is the context item identified
512 * from this context: the values of position() and last() also relate to the set of items being mapped
513 * @return a SequenceIterator over the sequence of items that the supplied input
514 * item maps to
515 */
516
517 public SequenceIterator<?> map(XPathContext context) throws XPathException {
518 return getAction().iterate(context);
519 }
520
521 /**
522 * Evaluate an updating expression, adding the results to a Pending Update List.
523 * The default implementation of this method, which is used for non-updating expressions,
524 * throws an UnsupportedOperationException
525 *
526 * @param context the XPath dynamic evaluation context
527 * @param pul the pending update list to which the results should be written
528 * @throws net.sf.saxon.trans.XPathException if evaluation fails
529 * @throws UnsupportedOperationException if the expression is not an updating expression
530 */
531
532 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
533 XPathContextMinor c2 = context.newMinorContext();
534 c2.trackFocus(getSelect().iterate(context));
535 SequenceIterator iter = c2.getCurrentIterator();
536 Item item;
537 while ((item = iter.next()) != null) {
538 getAction().evaluatePendingUpdates(c2, pul);
539 }
540 }
541
542 /**
543 * Diagnostic print of expression structure. The abstract expression tree
544 * is written to the supplied output destination.
545 */
546
547 public void export(ExpressionPresenter out) throws XPathException {
548 out.startElement("forEach", this);
549 getSelect().export(out);
550 getAction().export(out);
551 explainThreads(out);
552 out.endElement();
553 }
554
555 protected void explainThreads(ExpressionPresenter out) throws XPathException {
556 // no action in this class: implemented in subclass
557 }
558
559 /**
560 * <p>The toString() method for an expression attempts to give a representation of the expression
561 * in an XPath-like form.</p>
562 * <p>For subclasses of Expression that represent XPath expressions, the result should always be a string that
563 * parses as an XPath 3.0 expression</p>
564 *
565 * @return a representation of the expression as a string
566 */
567 @Override
568 public String toString() {
569 return ExpressionTool.parenthesize(getSelect()) + " ! " + ExpressionTool.parenthesize(getAction());
570 }
571
572 @Override
573 public String toShortString() {
574 return getSelect().toShortString() + "!" + getAction().toShortString();
575 }
576
577 /**
578 * Get a name identifying the kind of expression, in terms meaningful to a user.
579 *
580 * @return a name identifying the kind of expression, in terms meaningful to a user.
581 * The name will always be in the form of a lexical XML QName, and should match the name used
582 * in explain() output displaying the expression.
583 */
584 @Override
585 public String getExpressionName() {
586 return "forEach";
587 }
588
589 /**
590 * Get the (partial) name of a class that supports streaming of this kind of expression
591 *
592 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
593 * or null if there is no such class
594 */
595 @Override
596 public String getStreamerName() {
597 return "ForEach";
598 }
599 }
600