Debian Codegraph @

net/sf/saxon/expr/instruct/ApplyTemplates.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.event.PipelineConfiguration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.om.*;
14 import net.sf.saxon.trace.ExpressionPresenter;
15 import net.sf.saxon.trans.*;
16 import net.sf.saxon.trans.rules.RuleManager;
17 import net.sf.saxon.tree.iter.EmptyIterator;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22
23 /**
24 * An instruction representing an xsl:apply-templates element in the stylesheet
25 */
26
27 public class ApplyTemplates extends Instruction implements ITemplateCall, ComponentInvocation {
28
29 private Operand selectOp;
30 private WithParam[] actualParams;
31 private WithParam[] tunnelParams;
32
33 protected boolean useCurrentMode = false;
34 protected boolean useTailRecursion = false;
35 protected Mode mode;
36 protected boolean implicitSelect;
37 protected boolean inStreamableConstruct = false;
38 protected RuleManager ruleManager;
39 private int bindingSlot = -1; // for binding the mode
40
41 protected ApplyTemplates() {
42 }
43
44 /**
45 * Construct an apply-templates instruction
46 *
47 * @param select the select expression
48 * @param useCurrentMode true if mode="#current" was specified
49 * @param useTailRecursion true if this instruction is the last in its template
50 * @param implicitSelect true if the select expression is implicit, that is, if there was no explicit
51 * select expression in the call. This information is used only to make error messages more meaningful.
52 * @param mode the mode specified on apply-templates
53 */
54
55 public ApplyTemplates( Expression select,
56 boolean useCurrentMode,
57 boolean useTailRecursion,
58 boolean implicitSelect,
59 boolean inStreamableConstruct,
60 Mode mode,
61 RuleManager ruleManager) {
62
63 selectOp = new Operand(this, select, OperandRole.SINGLE_ATOMIC);
64 init(select, useCurrentMode, useTailRecursion, mode);
65 this.implicitSelect = implicitSelect;
66 this.inStreamableConstruct = inStreamableConstruct;
67 this.ruleManager = ruleManager;
68 }
69
70 protected void init(Expression select,
71 boolean useCurrentMode,
72 boolean useTailRecursion,
73 Mode mode) {
74 this.setSelect(select);
75 this.useCurrentMode = useCurrentMode;
76 this.useTailRecursion = useTailRecursion;
77 this.mode = mode;
78 adoptChildExpression(select);
79 }
80
81 /**
82 * Set the mode to be used.
83 *
84 * @param target the attribute set to be used
85 */
86
87 public void setMode(SimpleMode target) {
88 this.mode = target;
89 }
90
91 /**
92 * Get the actual parameters passed to the called template
93 *
94 * @return the non-tunnel parameters
95 */
96
97
98 public WithParam[] getActualParams() {
99 return actualParams;
100 }
101
102 /**
103 * Get the tunnel parameters passed to the called template
104 *
105 * @return the tunnel parameters
106 */
107
108
109 public WithParam[] getTunnelParams() {
110 return tunnelParams;
111 }
112
113 public void setActualParams(WithParam[] params) {
114 actualParams = params;
115 }
116
117 public void setTunnelParams(WithParam[] params) {
118 tunnelParams = params;
119 }
120
121 @Override
122 public Iterable<Operand> operands() {
123 List<Operand> operanda = new ArrayList<>();
124 operanda.add(selectOp);
125 WithParam.gatherOperands(this, getActualParams(), operanda);
126 WithParam.gatherOperands(this, getTunnelParams(), operanda);
127 return operanda;
128 }
129
130 /**
131 * Get the name of this instruction for diagnostic and tracing purposes
132 */
133
134 public int getInstructionNameCode() {
135 return StandardNames.XSL_APPLY_TEMPLATES;
136 }
137
138 /**
139 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
140 * This method indicates which of these methods is prefered. For instructions this is the process() method.
141 */
142
143 public int getImplementationMethod() {
144 return super.getImplementationMethod() | Expression.WATCH_METHOD;
145 }
146
147
148 /**
149 * Simplify an expression. This performs any static optimization (by rewriting the expression
150 * as a different expression).
151 *
152 *
153 *
154 * @throws XPathException if an error is discovered during expression
155 * rewriting
156 */
157
158 /*@NotNull*/
159 public Expression simplify() throws XPathException {
160 WithParam.simplify(getActualParams());
161 WithParam.simplify(getTunnelParams());
162 setSelect(getSelect().simplify());
163 return this;
164 }
165
166 /*@NotNull*/
167 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
168 WithParam.typeCheck(actualParams, visitor, contextInfo);
169 WithParam.typeCheck(tunnelParams, visitor, contextInfo);
170 try {
171 selectOp.typeCheck(visitor, contextInfo);
172 } catch (XPathException e) {
173 if (implicitSelect) {
174 String code = e.getErrorCodeLocalPart();
175 if ("XPTY0020".equals(code) || "XPTY0019".equals(code)) {
176 XPathException err = new XPathException("Cannot apply-templates to child nodes when the context item is an atomic value");
177 err.setErrorCode("XTTE0510");
178 err.setIsTypeError(true);
179 throw err;
180 } else if ("XPDY0002".equals(code)) {
181 XPathException err = new XPathException("Cannot apply-templates to child nodes when the context item is absent");
182 err.setErrorCode("XTTE0510");
183 err.setIsTypeError(true);
184 throw err;
185 }
186 }
187 throw e;
188 }
189 adoptChildExpression(getSelect());
190 if (Literal.isEmptySequence(getSelect())) {
191 return getSelect();
192 }
193 return this;
194 }
195
196 /*@NotNull*/
197 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
198 WithParam.optimize(visitor, actualParams, contextInfo);
199 WithParam.optimize(visitor, tunnelParams, contextInfo);
200 selectOp.typeCheck(visitor, contextInfo); // More info available second time around
201 selectOp.optimize(visitor, contextInfo);
202 if (Literal.isEmptySequence(getSelect())) {
203 return getSelect();
204 }
205
206 return this;
207 }
208
209 public int getIntrinsicDependencies() {
210 // If the instruction uses mode="#current", this represents a dependency on the context
211 // which means the instruction cannot be loop-lifted or moved to a global variable.
212 // We overload the dependency DEPENDS_ON_CURRENT_ITEM to achieve this effect.
213 return super.getIntrinsicDependencies() | (useCurrentMode ? StaticProperty.DEPENDS_ON_CURRENT_ITEM : 0);
214 }
215
216 public RuleManager getRuleManager() {
217 return ruleManager;
218 }
219
220 /**
221 * Copy an expression. This makes a deep copy.
222 *
223 * @return the copy of the original expression
224 * @param rebindings a mutable list of (old binding, new binding) pairs
225 * that is used to update the bindings held in any
226 * local variable references that are copied.
227 */
228
229 /*@NotNull*/
230 public Expression copy(RebindingMap rebindings) {
231 ApplyTemplates a2 = new ApplyTemplates(
232 getSelect().copy(rebindings), useCurrentMode, useTailRecursion, implicitSelect, inStreamableConstruct, mode, ruleManager);
233 a2.setActualParams(WithParam.copy(a2, getActualParams(), rebindings));
234 a2.setTunnelParams(WithParam.copy(a2, getTunnelParams(), rebindings));
235 ExpressionTool.copyLocationInfo(this, a2);
236 a2.ruleManager = ruleManager;
237 return a2;
238 }
239
240 /**
241 * Determine whether this instruction creates new nodes.
242 * This implementation returns true (which is almost invariably the case, so it's not worth
243 * doing any further analysis to find out more precisely).
244 */
245
246 public final boolean mayCreateNewNodes() {
247 return true;
248 }
249
250 public void process(XPathContext context) throws XPathException {
251 apply(context, false);
252 }
253
254 public TailCall processLeavingTail(XPathContext context) throws XPathException {
255 return apply(context, useTailRecursion);
256 }
257
258 protected TailCall apply(XPathContext context, boolean returnTailCall) throws XPathException {
259
260 Component.M targetMode = getTargetMode(context);
261 Mode thisMode = targetMode.getActor();
262
263 // handle parameters if any
264
265 ParameterSet params = assembleParams(context, getActualParams());
266 ParameterSet tunnels = assembleTunnelParams(context, getTunnelParams());
267
268 if (returnTailCall) {
269 XPathContextMajor c2 = context.newContext();
270 c2.setOrigin(this);
271 return new ApplyTemplatesPackage(
272 ExpressionTool.lazyEvaluate(getSelect(), context, false),
273 targetMode, params, tunnels, c2, getLocation());
274 }
275
276 // Get an iterator to iterate through the selected nodes in original order
277
278 SequenceIterator iter = getSelect().iterate(context);
279
280 // Quick exit if the iterator is empty
281
282 if (iter instanceof EmptyIterator) {
283 return null;
284 }
285
286 // process the selected nodes now
287
288 XPathContextMajor c2 = context.newContext();
289 c2.trackFocus(iter);
290 c2.setCurrentMode(targetMode);
291 c2.setOrigin(this);
292 c2.setCurrentComponent(targetMode);
293 if (inStreamableConstruct) {
294 c2.setCurrentGroupIterator(null);
295 }
296 PipelineConfiguration pipe = c2.getReceiver().getPipelineConfiguration();
297 pipe.setXPathContext(c2);
298
299 try {
300 TailCall tc = thisMode.applyTemplates(params, tunnels, c2, getLocation());
301 while (tc != null) {
302 tc = tc.processLeavingTail();
303 }
304 } catch (StackOverflowError e) {
305 XPathException err = new XPathException("Too many nested apply-templates calls. The stylesheet may be looping.");
306 err.setErrorCode(SaxonErrorCode.SXLM0001);
307 err.setLocation(getLocation());
308 err.setXPathContext(context);
309 throw err;
310 }
311 pipe.setXPathContext(context);
312 return null;
313
314 }
315
316 /**
317 * Establish the target mode, at run-time. This (a) resolves overrides across packages,
318 * and (b) handles mode="#current".
319 * @param context the dynamic context
320 * @return the mode to be used, as a Component
321 */
322
323 public Component.M getTargetMode(XPathContext context) {
324 Component.M targetMode;
325 if (useCurrentMode) {
326 targetMode = context.getCurrentMode();
327 } else {
328 if (bindingSlot >= 0) {
329 targetMode = (Component.M)context.getTargetComponent(bindingSlot);
330 if (targetMode.getVisibility() == Visibility.ABSTRACT) {
331 throw new AssertionError("Modes cannot be abstract");
332 }
333 } else {
334 // fallback
335 targetMode = mode.getDeclaringComponent();
336 }
337 }
338 return targetMode;
339 }
340
341
342 /**
343 * Get the select expression
344 *
345 * @return the select expression
346 */
347
348 public Expression getSelectExpression() {
349 return getSelect();
350 }
351
352 /**
353 * Ask if the select expression was implicit
354 *
355 * @return true if no select attribute was explicitly specified
356 */
357
358 public boolean isImplicitSelect() {
359 return implicitSelect;
360 }
361
362 /**
363 * Ask if tail recursion is to be used
364 *
365 * @return true if tail recursion is used
366 */
367
368 public boolean useTailRecursion() {
369 return useTailRecursion;
370 }
371
372 /**
373 * Ask if mode="#current" was specified
374 *
375 * @return true if mode="#current" was specified
376 */
377
378 public boolean usesCurrentMode() {
379 return useCurrentMode;
380 }
381
382 /**
383 * Get the Mode
384 *
385 * @return the mode, or null if mode="#current" was specified
386 */
387
388 public Mode getMode() {
389 return mode;
390 }
391
392 /**
393 * Get the target component if this is known in advance, that is, if the target component
394 * is private or final, or in some other cases such as xsl:original. Otherwise, return null.
395 *
396 * @return the bound component if the binding has been fixed
397 */
398 public Component getFixedTarget() {
399 return mode.getDeclaringComponent();
400 }
401
402 /**
403 * Get the symbolic name of the mode that this invocation references
404 *
405 * @return the symbolic name of the mode used by this instructon, or null if the instruction uses mode="#current"
406 */
407 public SymbolicName getSymbolicName() {
408 return mode==null ? null : mode.getSymbolicName();
409 }
410
411 /**
412 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
413 * by an expression in a source tree.
414 * <p>The default implementation of this method assumes that an expression does no navigation other than
415 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
416 * same context as the containing expression. The method must be overridden for any expression
417 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
418 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
419 * functions because they create a new navigation root. Implementations also exist for PathExpression and
420 * FilterExpression because they have subexpressions that are evaluated in a different context from the
421 * calling expression.</p>
422 *
423 * @param pathMap the PathMap to which the expression should be added
424 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
425 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
426 * expression, and that represent possible results of this expression. For an expression that does
427 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
428 * expressions, it is the same as the input pathMapNode.
429 */
430
431 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
432 // This logic is assuming the mode is streamable (so that called templates can't return streamed nodes)
433 PathMap.PathMapNodeSet result = super.addToPathMap(pathMap, pathMapNodeSet);
434 result.setReturnable(false);
435 return new PathMap.PathMapNodeSet(pathMap.makeNewRoot(this));
436 }
437
438
439 /**
440 * Diagnostic print of expression structure. The abstract expression tree
441 * is written to the supplied output destination.
442 *
443 * @param out output destination
444 */
445
446 public void export(ExpressionPresenter out) throws XPathException {
447
448 out.startElement("applyT", this);
449 if (mode != null && !mode.isUnnamedMode()) {
450 out.emitAttribute("mode", mode.getModeName());
451 }
452 String flags = "";
453 if (useCurrentMode) {
454 flags = "c";
455 }
456 if (useTailRecursion) {
457 flags += "t";
458 }
459 if (implicitSelect) {
460 flags += "i";
461 }
462 if (!flags.isEmpty()) {
463 out.emitAttribute("flags", flags);
464 }
465 out.emitAttribute("bSlot", "" + getBindingSlot());
466 out.setChildRole("select");
467 getSelect().export(out);
468 if (getActualParams().length != 0) {
469 WithParam.exportParameters(getActualParams(), out, false);
470 }
471 if (getTunnelParams().length != 0) {
472 WithParam.exportParameters(getTunnelParams(), out, true);
473 }
474 out.endElement();
475 }
476
477 /**
478 * Get the select expression
479 * @return the select expression
480 */
481
482 public Expression getSelect() {
483 return selectOp.getChildExpression();
484 }
485
486 /**
487 * Set the select expression
488 * @param select the select expression
489 */
490
491 public void setSelect(Expression select) {
492 selectOp.setChildExpression(select);
493 }
494
495 /**
496 * Set the binding slot to be used (for the explicit or implicit reference to the mode).
497 * This is the offset within the binding vector of the containing
498 * component where the actual target template is to be found. The target template is not held directly
499 * in the CallTemplate instruction itself because it can be overridden in a using package.
500 *
501 * @param slot the offset in the binding vector of the containing package where the target template
502 * can be found.
503 */
504
505 public void setBindingSlot(int slot) {
506 bindingSlot = slot;
507 }
508
509 /**
510 * Get the binding slot to be used (for the explicit or implicit reference to the mode).
511 * This is the offset within the binding vector of the containing
512 * component where the actual target template is to be found.
513 *
514 * @return the offset in the binding vector of the containing package where the target template
515 * can be found.
516 */
517
518 public int getBindingSlot() {
519 return bindingSlot;
520 }
521
522
523 /**
524 * An ApplyTemplatesPackage is an object that encapsulates the sequence of nodes to be processed,
525 * the mode, the parameters to be supplied, and the execution context. This object can be returned as a tail
526 * call, so that the actual call is made from a lower point on the stack, allowing a tail-recursive
527 * template to execute in a finite stack size
528 */
529
530 protected static class ApplyTemplatesPackage implements TailCall {
531
532 private Sequence<?> selectedItems;
533 private Component.M targetMode;
534 private ParameterSet params;
535 private ParameterSet tunnelParams;
536 private XPathContextMajor evaluationContext;
537 private Location locationId;
538
539 ApplyTemplatesPackage(Sequence<?> selectedItems,
540 Component.M targetMode,
541 ParameterSet params,
542 ParameterSet tunnelParams,
543 XPathContextMajor context,
544 Location locationId) {
545 this.selectedItems = selectedItems;
546 this.targetMode = targetMode;
547 this.params = params;
548 this.tunnelParams = tunnelParams;
549 evaluationContext = context;
550 this.locationId = locationId;
551 }
552
553 public TailCall processLeavingTail() throws XPathException {
554 evaluationContext.trackFocus(selectedItems.iterate());
555 evaluationContext.setCurrentMode(targetMode);
556 evaluationContext.setCurrentComponent(targetMode);
557 return targetMode.getActor().applyTemplates(params, tunnelParams, evaluationContext, locationId);
558 }
559 }
560
561 @Override
562 public String getStreamerName() {
563 return "ApplyTemplates";
564 }
565
566 }
567