Debian Codegraph @

net/sf/saxon/expr/instruct/CallTemplate.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.expr.*;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.om.StandardNames;
13 import net.sf.saxon.om.StructuredQName;
14 import net.sf.saxon.trace.ExpressionPresenter;
15 import net.sf.saxon.trans.SaxonErrorCode;
16 import net.sf.saxon.trans.SymbolicName;
17 import net.sf.saxon.trans.Visibility;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20 import net.sf.saxon.type.AnyItemType;
21 import net.sf.saxon.type.ItemType;
22 import net.sf.saxon.value.SequenceType;
23
24 import java.util.ArrayList;
25 import java.util.Arrays;
26
27 /**
28 * Instruction representing an xsl:call-template element in the stylesheet.
29 */
30
31 public class CallTemplate extends Instruction implements ITemplateCall, ComponentInvocation {
32
33 private NamedTemplate template = null; // Null only for saxon:call-template
34 private StructuredQName calledTemplateName; // the name of the called template
35 private WithParam[] actualParams = WithParam.EMPTY_ARRAY;
36 private WithParam[] tunnelParams = WithParam.EMPTY_ARRAY;
37 private boolean useTailRecursion = false;
38 private int bindingSlot = -1;
39 private boolean isWithinDeclaredStreamableConstruct;
40
41 /**
42 * Construct a CallTemplate instruction.
43 * @param template the template to be called. This is provisional, and applies only if the template
44 * is not overridden in another package; the template supplied will be the one with
45 * matching name in the same package. Null in the case of saxon:call-template, and also
46 * in the case where the supplied name is xsl:original
47 * @param calledTemplateName the name of the template to be called; null in the case of saxon:call-template
48 * where this is established dynamically
49 * @param useTailRecursion true if the call is potentially tail recursive
50 * where the name of the called template is to be calculated dynamically
51 */
52
53 public CallTemplate(NamedTemplate template, StructuredQName calledTemplateName, boolean useTailRecursion, boolean inStreamable) {
54 this.template = template;
55 this.calledTemplateName = calledTemplateName;
56 this.useTailRecursion = useTailRecursion;
57 this.isWithinDeclaredStreamableConstruct = inStreamable;
58 }
59
60 /**
61 * Set the actual parameters on the call
62 *
63 * @param actualParams the parameters that are not tunnel parameters
64 * @param tunnelParams the tunnel parameters
65 */
66
67 public void setActualParameters(
68 /*@NotNull*/ WithParam[] actualParams,
69 /*@NotNull*/ WithParam[] tunnelParams) {
70 this.actualParams = actualParams;
71 this.tunnelParams = tunnelParams;
72 for (WithParam actualParam : actualParams) {
73 adoptChildExpression(actualParam.getSelectExpression());
74 }
75 for (WithParam tunnelParam : tunnelParams) {
76 adoptChildExpression(tunnelParam.getSelectExpression());
77 }
78 }
79
80 /**
81 * Get the name (QName) of the template being called
82 * @return the name of the target template
83 */
84
85 public StructuredQName getCalledTemplateName() {
86 return calledTemplateName;
87 }
88
89 /**
90 * Get the symbolic name of the template being called. This is essentially the component kind (template)
91 * plus the QName of the target template
92 *
93 * @return the symbolic name of the target template, or null in the case of saxon:call-template where
94 * the name is defined dynamically
95 */
96
97 public SymbolicName getSymbolicName() {
98 return calledTemplateName == null ? null : new SymbolicName(StandardNames.XSL_TEMPLATE, calledTemplateName);
99 }
100
101 public Component getTarget() {
102 return template.getDeclaringComponent();
103 }
104
105 public Component getFixedTarget() {
106 Component c = getTarget();
107 Visibility v = c.getVisibility();
108 if (v == Visibility.PRIVATE || v == Visibility.FINAL) {
109 return c;
110 } else {
111 return null;
112 }
113 }
114
115 /**
116 * Get the actual parameters passed to the called template
117 *
118 * @return the non-tunnel parameters
119 */
120
121 /*@NotNull*/
122 public WithParam[] getActualParams() {
123 return actualParams;
124 }
125
126 /**
127 * Get the tunnel parameters passed to the called template
128 *
129 * @return the tunnel parameters
130 */
131
132 /*@NotNull*/
133 public WithParam[] getTunnelParams() {
134 return tunnelParams;
135 }
136
137 /**
138 * Set the target template
139 * @param target the target template
140 */
141
142 public void setTargetTemplate(NamedTemplate target) {
143 this.template = target;
144 }
145
146 /**
147 * Get the target template
148 *
149 * @return the target template
150 */
151
152 public NamedTemplate getTargetTemplate() {
153 return template;
154 }
155
156 /**
157 * Ask whether this is a tail call
158 *
159 * @return true if this is a tail call
160 */
161
162 public boolean usesTailRecursion() {
163 return useTailRecursion;
164 }
165
166 /**
167 * Return the name of this instruction.
168 */
169
170 public int getInstructionNameCode() {
171 return StandardNames.XSL_CALL_TEMPLATE;
172 }
173
174 /**
175 * Set the binding slot to be used. This is the offset within the binding vector of the containing
176 * component where the actual target template is to be found. The target template is not held directly
177 * in the CallTemplate instruction itself because it can be overridden in a using package.
178 *
179 * @param slot the offset in the binding vector of the containing package where the target template
180 * can be found.
181 */
182
183 public void setBindingSlot(int slot) {
184 bindingSlot = slot;
185 }
186
187 /**
188 * Get the binding slot to be used. This is the offset within the binding vector of the containing
189 * component where the actual target template is to be found.
190 *
191 * @return the offset in the binding vector of the containing package where the target template
192 * can be found.
193 */
194
195 public int getBindingSlot() {
196 return bindingSlot;
197 }
198
199 /**
200 * Simplify an expression. This performs any static optimization (by rewriting the expression
201 * as a different expression).
202 *
203 * @return the simplified expression
204 * @throws XPathException if an error is discovered during expression
205 * rewriting
206 */
207
208 /*@NotNull*/
209 public Expression simplify() throws XPathException {
210 WithParam.simplify(actualParams);
211 WithParam.simplify(tunnelParams);
212 return this;
213 }
214
215 /*@NotNull*/
216 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
217 WithParam.typeCheck(actualParams, visitor, contextInfo);
218 WithParam.typeCheck(tunnelParams, visitor, contextInfo);
219 // For non-tunnel parameters, see if the supplied value is type-safe against the declared
220 // type of the value, and if so, avoid the dynamic type check
221 // Can't do this check unless the target template has been compiled.
222 boolean backwards = visitor.getStaticContext().isInBackwardsCompatibleMode();
223 TypeChecker tc = visitor.getConfiguration().getTypeChecker(backwards);
224 for (int p = 0; p < actualParams.length; p++) {
225 WithParam wp = actualParams[p];
226 //int id = wp.getParameterId();
227 NamedTemplate.LocalParamInfo lp = template.getLocalParamInfo(wp.getVariableQName());
228 if (lp != null) {
229 SequenceType req = lp.requiredType;
230 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.PARAM, wp.getVariableQName().getDisplayName(), p);
231 role.setErrorCode("XTTE0590");
232 Expression select = tc.staticTypeCheck(
233 wp.getSelectExpression(), req, role, visitor);
234 wp.setSelectExpression(this, select);
235 wp.setTypeChecked(true);
236 }
237 }
238
239 return this;
240 }
241
242 /*@NotNull*/
243 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
244 WithParam.optimize(visitor, actualParams, contextItemType);
245 WithParam.optimize(visitor, tunnelParams, contextItemType);
246 return this;
247 }
248
249
250 /**
251 * Get the cardinality of the sequence returned by evaluating this instruction
252 *
253 * @return the static cardinality
254 */
255
256 public int computeCardinality() {
257 if (template == null) {
258 return StaticProperty.ALLOWS_ZERO_OR_MORE;
259 } else {
260 return template.getRequiredType().getCardinality();
261 }
262 }
263
264 /**
265 * Get the item type of the items returned by evaluating this instruction
266 *
267 * @return the static item type of the instruction
268 */
269
270 /*@NotNull*/
271 public ItemType getItemType() {
272 if (template == null) {
273 return AnyItemType.getInstance();
274 } else {
275 return template.getRequiredType().getPrimaryType();
276 }
277 }
278
279 /**
280 * Copy an expression. This makes a deep copy.
281 *
282 * @return the copy of the original expression
283 * @param rebindings Variables that need to be re-bound
284 */
285
286 /*@NotNull*/
287 public Expression copy(RebindingMap rebindings) {
288 CallTemplate ct = new CallTemplate(template, calledTemplateName, useTailRecursion, isWithinDeclaredStreamableConstruct);
289 ExpressionTool.copyLocationInfo(this, ct);
290 ct.actualParams = WithParam.copy(ct, actualParams, rebindings);
291 ct.tunnelParams = WithParam.copy(ct, tunnelParams, rebindings);
292 return ct;
293 }
294
295 public int getIntrinsicDependencies() {
296 // we could go to the called template and find which parts of the context it depends on, but this
297 // would create the risk of infinite recursion. So we just assume that the dependencies exist
298 return StaticProperty.DEPENDS_ON_XSLT_CONTEXT |
299 StaticProperty.DEPENDS_ON_FOCUS;
300 }
301
302 /**
303 * Determine whether this instruction creates new nodes.
304 * This implementation currently returns true unconditionally.
305 */
306
307 public final boolean mayCreateNewNodes() {
308 return true;
309 }
310
311 @Override
312 public Iterable<Operand> operands() {
313 ArrayList<Operand> list = new ArrayList<>(10);
314 WithParam.gatherOperands(this, actualParams, list);
315 WithParam.gatherOperands(this, tunnelParams, list);
316 return list;
317 }
318
319
320 /**
321 * Process this instruction, without leaving any tail calls.
322 *
323 * @param context the dynamic context for this transformation
324 * @throws XPathException if a dynamic error occurs
325 */
326
327 public void process(XPathContext context) throws XPathException {
328
329 NamedTemplate t;
330 Component target = getFixedTarget();
331 if (bindingSlot >= 0) {
332 target = context.getTargetComponent(bindingSlot);
333 if (target.isHiddenAbstractComponent()) {
334 XPathException err = new XPathException("Cannot call an abstract template (" +
335 calledTemplateName.getDisplayName() +
336 ") with no implementation", "XTDE3052");
337 err.setLocation(getLocation());
338 throw err;
339 }
340 }
341 t = (NamedTemplate) target.getActor();
342 XPathContextMajor c2 = context.newContext();
343 c2.setCurrentComponent(target);
344 c2.setOrigin(this);
345 c2.openStackFrame(t.getStackFrameMap());
346 c2.setLocalParameters(assembleParams(context, actualParams));
347 c2.setTunnelParameters(assembleTunnelParams(context, tunnelParams));
348 if (isWithinDeclaredStreamableConstruct) {
349 c2.setCurrentGroupIterator(null);
350 }
351
352 try {
353 TailCall tc = t.expand(c2);
354 while (tc != null) {
355 tc = tc.processLeavingTail();
356 }
357 } catch (StackOverflowError e) {
358 XPathException err = new XPathException("Too many nested template or function calls. The stylesheet may be looping.");
359 err.setLocation(getLocation());
360 err.setXPathContext(context);
361 throw err;
362 }
363 }
364
365 /**
366 * Process this instruction. If the called template contains a tail call (which may be
367 * an xsl:call-template or xsl:apply-templates instruction) then the tail call will not
368 * actually be evaluated, but will be returned in a TailCall object for the caller to execute.
369 *
370 * @param context the dynamic context for this transformation
371 * @return an object containing information about the tail call to be executed by the
372 * caller. Returns null if there is no tail call.
373 */
374
375 public TailCall processLeavingTail(XPathContext context) throws XPathException {
376 if (useTailRecursion) {
377 Component targetComponent;
378 if (bindingSlot >= 0) {
379 targetComponent = context.getTargetComponent(bindingSlot);
380 } else {
381 targetComponent = getFixedTarget();
382 }
383 if (targetComponent == null) {
384 throw new XPathException("Internal Saxon error: No binding available for call-template instruction", SaxonErrorCode.SXPK0001, this.getLocation());
385 }
386 if (targetComponent.isHiddenAbstractComponent()) {
387 throw new XPathException("Cannot call an abstract template (" +
388 calledTemplateName.getDisplayName() +
389 ") with no implementation", "XTDE3052", this.getLocation());
390 }
391
392 // handle parameters if any
393
394 ParameterSet params = assembleParams(context, actualParams);
395 ParameterSet tunnels = assembleTunnelParams(context, tunnelParams);
396
397 // Call the named template. Actually, don't call it; rather construct a call package
398 // and return it to the caller, who will then process this package.
399
400 //System.err.println("Call template using tail recursion");
401 if (params == null) { // bug 490967
402 params = ParameterSet.EMPTY_PARAMETER_SET;
403 }
404
405 // clear all the local variables: they are no longer needed
406 Arrays.fill(context.getStackFrame().getStackFrameValues(), null);
407
408 return new CallTemplatePackage(targetComponent, params, tunnels, this, context);
409
410 } else {
411 process(context);
412 return null;
413 }
414 }
415
416 public StructuredQName getObjectName() {
417 return template == null ? null : template.getTemplateName();
418 }
419
420 /**
421 * Export of expression structure. The abstract expression tree
422 * is written to the supplied output destination.
423 */
424
425 public void export(ExpressionPresenter out) throws XPathException {
426 out.startElement("callT", this);
427 String flags = "";
428 if (template != null && template.getTemplateName() != null) {
429 out.emitAttribute("name", template.getTemplateName());
430 }
431 out.emitAttribute("bSlot", ""+getBindingSlot());
432 if (isWithinDeclaredStreamableConstruct) {
433 flags += "d";
434 }
435 if (useTailRecursion) {
436 flags += "t";
437 }
438 if (!flags.isEmpty()) {
439 out.emitAttribute("flags", flags);
440 }
441 if (actualParams.length > 0) {
442 WithParam.exportParameters(actualParams, out, false);
443 }
444 if (tunnelParams.length > 0) {
445 WithParam.exportParameters(tunnelParams, out, true);
446 }
447 out.endElement();
448 }
449
450
451 /**
452 * A CallTemplatePackage is an object that encapsulates the name of a template to be called,
453 * the parameters to be supplied, and the execution context. This object can be returned as a tail
454 * call, so that the actual call is made from a lower point on the stack, allowing a tail-recursive
455 * template to execute in a finite stack size
456 */
457
458 public static class CallTemplatePackage implements TailCall {
459
460 private Component targetComponent;
461 private ParameterSet params;
462 private ParameterSet tunnelParams;
463 private CallTemplate instruction;
464 private XPathContext evaluationContext;
465
466 /**
467 * Construct a CallTemplatePackage that contains information about a call.
468 *
469 * @param targetComponent the Template to be called
470 * @param params the parameters to be supplied to the called template
471 * @param tunnelParams the tunnel parameter supplied to the called template
472 * @param instruction the xsl:call-template instruction
473 * @param evaluationContext saved context information from the Controller (current mode, etc)
474 * which must be reset to ensure that the template is called with all the context information
475 * intact
476 */
477
478 public CallTemplatePackage(Component targetComponent,
479 ParameterSet params,
480 ParameterSet tunnelParams,
481 CallTemplate instruction,
482 XPathContext evaluationContext) {
483 this.targetComponent = targetComponent;
484 if (!(targetComponent.getActor() instanceof NamedTemplate)) {
485 throw new ClassCastException("Target of call-template must be a named template");
486 }
487 this.params = params;
488 this.tunnelParams = tunnelParams;
489 this.instruction = instruction;
490 this.evaluationContext = evaluationContext;
491 }
492
493 /**
494 * Process the template call encapsulated by this package.
495 *
496 * @return another TailCall. This will never be the original call, but it may be the next
497 * recursive call. For example, if A calls B which calls C which calls D, then B may return
498 * a TailCall to A representing the call from B to C; when this is processed, the result may be
499 * a TailCall representing the call from C to D.
500 * @throws XPathException if a dynamic error occurs
501 */
502
503 public TailCall processLeavingTail() throws XPathException {
504 // TODO: the idea of tail call optimization is to reuse the caller's stack frame rather than
505 // creating a new one. We're doing this for the Java stack, but not for the context stack where
506 // local variables are held. It should be possible to avoid creating a new context, and instead
507 // to update the existing one in situ.
508 NamedTemplate template = (NamedTemplate)targetComponent.getActor();
509 XPathContextMajor c2 = evaluationContext.newContext();
510 c2.setCurrentComponent(targetComponent);
511 c2.setOrigin(instruction);
512 c2.setLocalParameters(params);
513 c2.setTunnelParameters(tunnelParams);
514 c2.openStackFrame(template.getStackFrameMap());
515
516 // System.err.println("Tail call on template");
517
518 return template.expand(c2);
519 }
520 }
521
522 @Override
523 public String toString() {
524 // fallback implementation
525 FastStringBuffer buff = new FastStringBuffer(FastStringBuffer.C64);
526 buff.append("CallTemplate#");
527 if (template.getObjectName() != null) {
528 buff.append(template.getObjectName().getDisplayName());
529 }
530 boolean first = true;
531 for (WithParam p : getActualParams()) {
532 buff.append(first ? "(" : ", ");
533 buff.append(p.getVariableQName().getDisplayName());
534 buff.append("=");
535 buff.append(p.getSelectExpression().toString());
536 first = false;
537 }
538 if (!first) {
539 buff.append(")");
540 }
541 return buff.toString();
542 }
543
544 @Override
545 public String toShortString() {
546 // fallback implementation
547 FastStringBuffer buff = new FastStringBuffer(FastStringBuffer.C64);
548 buff.append("CallTemplate#");
549 buff.append(template.getObjectName().getDisplayName());
550 return buff.toString();
551 }
552
553 @Override
554 public String getStreamerName() {
555 return "CallTemplate";
556 }
557
558 }
559