Debian Codegraph @

net/sf/saxon/expr/instruct/TemplateRule.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.Location;
12 import net.sf.saxon.expr.parser.RebindingMap;
13 import net.sf.saxon.expr.parser.RoleDiagnostic;
14 import net.sf.saxon.om.StandardNames;
15 import net.sf.saxon.om.StructuredQName;
16 import net.sf.saxon.pattern.Pattern;
17 import net.sf.saxon.style.Compilation;
18 import net.sf.saxon.style.ComponentDeclaration;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trace.InstructionInfo;
21 import net.sf.saxon.trace.LocationKind;
22 import net.sf.saxon.trans.UncheckedXPathException;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.trans.rules.Rule;
25 import net.sf.saxon.trans.rules.RuleTarget;
26 import net.sf.saxon.tree.jiter.MonoIterator;
27 import net.sf.saxon.type.AnyItemType;
28 import net.sf.saxon.type.ItemType;
29 import net.sf.saxon.type.TypeHierarchy;
30 import net.sf.saxon.value.SequenceType;
31
32 import java.util.ArrayList;
33 import java.util.Iterator;
34 import java.util.List;
35
36 /**
37 * The runtime object corresponding to an xsl:template element in the stylesheet.
38 * <p>Note that the Template object no longer has precedence information associated with it; this is now
39 * only in the Rule object that references this Template. This allows two rules to share the same template,
40 * with different precedences. This occurs when a stylesheet module is imported more than once, from different
41 * places, with different import precedences.</p>
42 * <p>From Saxon 9.7, the old Template class is split into NamedTemplate and TemplateRule.</p>
43 * <p>From Saxon 9.8, a subclass is used in Saxon-EE</p>
44 */
45
46 public class TemplateRule implements RuleTarget, Location, ExpressionOwner, InstructionInfo {
47
48 // The body of the template is represented by an expression,
49 // which is responsible for any type checking that's needed.
50
51 protected Expression body;
52 protected Pattern matchPattern;
53 private boolean hasRequiredParams;
54 private boolean bodyIsTailCallReturner;
55 private SequenceType requiredType;
56 private boolean declaredStreamable;
57 private ItemType requiredContextItemType = AnyItemType.getInstance();
58 private boolean absentFocus;
59 private SlotManager stackFrameMap;
60 private PackageData packageData;
61 private String systemId;
62 private int lineNumber;
63
64
65 private List<Rule> rules = new ArrayList<>();
66 protected List<TemplateRule> slaveCopies = new ArrayList<>();
67
68 /**
69 * Create a template
70 */
71
72 public TemplateRule() {
73 }
74
75 /**
76 * Set the match pattern used with this template
77 *
78 * @param pattern the match pattern (may be null for a named template)
79 */
80
81 public void setMatchPattern(Pattern pattern) {
82 // if (matchPattern != pattern) {
83 // for (Rule r : rules) {
84 // r.setPattern(pattern);
85 // }
86 // }
87 matchPattern = pattern;
88
89 }
90
91 public Expression getBody() {
92 return body;
93 }
94
95 /**
96 * Set the required context item type. Used when there is an xsl:context-item child element
97 *
98 * @param type the required context item type
99 * @param absentFocus true if the context item is treated as absent even if supplied (use="absent")
100 */
101
102 public void setContextItemRequirements(ItemType type, boolean absentFocus) {
103 requiredContextItemType = type;
104 this.absentFocus = absentFocus;
105 }
106
107 public int getComponentKind() {
108 return StandardNames.XSL_TEMPLATE;
109 }
110
111 /**
112 * Get the match pattern used with this template
113 *
114 * @return the match pattern, or null if this is a named template with no match pattern. In the case of
115 * a template rule whose pattern is a union pattern, this will be the original union pattern; the individual
116 * Rule objects contain the branches of the union pattern.
117 */
118
119 public Pattern getMatchPattern() {
120 return matchPattern;
121 }
122
123 /**
124 * Set the expression that forms the body of the template
125 *
126 * @param body the body of the template
127 */
128
129 public void setBody(Expression body) {
130 this.body = body;
131 bodyIsTailCallReturner = (body instanceof TailCallReturner);
132 }
133
134 public void setStackFrameMap(SlotManager map) {
135 stackFrameMap = map;
136 }
137
138 public SlotManager getStackFrameMap() {
139 return stackFrameMap;
140 }
141
142 // @Override
143 // public void allocateAllBindingSlots(StylesheetPackage pack) {
144 // super.allocateAllBindingSlots(pack);
145 // if (matchPattern != null) {
146 // allocateBindingSlotsRecursive(pack, this, matchPattern);
147 // }
148 // }
149
150 /**
151 * Set whether this template has one or more required parameters
152 *
153 * @param has true if the template has at least one required parameter
154 */
155
156 public void setHasRequiredParams(boolean has) {
157 hasRequiredParams = has;
158 }
159
160 /**
161 * Ask whether this template has one or more required parameters
162 *
163 * @return true if this template has at least one required parameter
164 */
165
166 public boolean hasRequiredParams() {
167 return hasRequiredParams;
168 }
169
170 /**
171 * Set the required type to be returned by this template
172 *
173 * @param type the required type as defined in the "as" attribute on the xsl:template element
174 */
175
176 public void setRequiredType(SequenceType type) {
177 requiredType = type;
178 }
179
180 /**
181 * Get the required type to be returned by this template
182 *
183 * @return the required type as defined in the "as" attribute on the xsl:template element
184 */
185
186 public SequenceType getRequiredType() {
187 if (requiredType == null) {
188 return SequenceType.ANY_SEQUENCE;
189 } else {
190 return requiredType;
191 }
192 }
193
194 /**
195 * Register a rule for which this is the target
196 *
197 * @param rule a rule in which this is the target
198 */
199 public void registerRule(Rule rule) {
200 rules.add(rule);
201 }
202
203 /**
204 * Get the rules that use this template. For a template with no match pattern, this will be
205 * an empty list. For a union pattern, there will be one rule for each branch of the union.
206 *
207 * @return the rules corresponding to this template.
208 */
209
210 public List<Rule> getRules() {
211 return rules;
212 }
213
214
215 public int getContainerGranularity() {
216 return 0;
217 }
218
219 public PackageData getPackageData() {
220 return packageData;
221 }
222
223 public void setPackageData(PackageData data) {
224 this.packageData = data;
225 }
226
227 public String getPublicId() {
228 return null;
229 }
230
231 public String getSystemId() {
232 return systemId;
233 }
234
235 public void setSystemId(String id) {
236 this.systemId = id;
237 }
238
239 public int getLineNumber() {
240 return lineNumber;
241 }
242
243 public void setLineNumber(int line) {
244 this.lineNumber = line;
245 }
246
247 public int getColumnNumber() {
248 return -1;
249 }
250
251 /**
252 * Get an immutable copy of this Location object. By default Location objects may be mutable, so they
253 * should not be saved for later use. The result of this operation holds the same location information,
254 * but in an immutable form.
255 */
256 public Location saveLocation() {
257 return this;
258 }
259
260 public ItemType getRequiredContextItemType() {
261 return requiredContextItemType;
262 }
263
264 public boolean isAbsentFocus() {
265 return absentFocus;
266 }
267
268
269 public List<LocalParam> getLocalParams() {
270 List<LocalParam> result = new ArrayList<>();
271 gatherLocalParams(getInterpretedBody(), result);
272 return result;
273 }
274
275 private static void gatherLocalParams(Expression exp, List<LocalParam> result) {
276 if (exp instanceof LocalParam) {
277 result.add((LocalParam) exp);
278 } else {
279 for (Operand o : exp.operands()) {
280 gatherLocalParams(o.getChildExpression(), result);
281 }
282 }
283 }
284
285 /**
286 * Prepare for JIT compilation.
287 *
288 * @param compilation the XSLT compilation
289 * @param decl the component declaration of this template rule
290 */
291
292 public void prepareInitializer(Compilation compilation, ComponentDeclaration decl, StructuredQName modeName) {
293 // No action in Saxon-HE
294 }
295
296 /**
297 * Ensure that any first-time initialization has been done. Used in Saxon-EE
298 * to do JIT compilation
299 */
300
301 public void initialize() throws XPathException {
302 // No action needed in Saxon-HE
303 }
304
305 /**
306 * Process the template, without returning any tail calls. This path is used by
307 * xsl:apply-imports and xsl:next-match
308 *
309 * @param context The dynamic context, giving access to the current node,
310 * @throws XPathException if a dynamic error occurs while evaluating
311 * the template
312 */
313
314 public void apply(XPathContextMajor context) throws XPathException {
315 TailCall tc = applyLeavingTail(context);
316 while (tc != null) {
317 tc = tc.processLeavingTail();
318 }
319 }
320
321 /**
322 * Process this template, with the possibility of returning a tail call package if the template
323 * contains any tail calls that are to be performed by the caller.
324 *
325 * @param context the XPath dynamic context
326 * @return null if the template exited normally; but if it was a tail call, details of the call
327 * that hasn't been made yet and needs to be made by the caller
328 * @throws XPathException if a dynamic error occurs while evaluating
329 * the template
330 */
331
332 public TailCall applyLeavingTail(XPathContext context) throws XPathException {
333 //initialize();
334 TypeHierarchy th = context.getConfiguration().getTypeHierarchy();
335 if (requiredContextItemType != AnyItemType.getInstance() &&
336 !requiredContextItemType.matches(context.getContextItem(), th)) {
337 RoleDiagnostic role = new RoleDiagnostic(
338 RoleDiagnostic.MISC, "context item for the template rule", 0);
339 String message = role.composeErrorMessage(requiredContextItemType, context.getContextItem(), th);
340 XPathException err = new XPathException(message, "XTTE0590");
341 err.setLocation(this);
342 err.setIsTypeError(true);
343 throw err;
344 }
345 if (absentFocus) {
346 context = context.newMinorContext();
347 context.setCurrentIterator(null);
348 }
349
350 try {
351 if (bodyIsTailCallReturner) {
352 return ((TailCallReturner) body).processLeavingTail(context);
353 } else {
354 body.process(context);
355 return null;
356 }
357 } catch (UncheckedXPathException e) {
358 XPathException xe = e.getXPathException();
359 xe.maybeSetLocation(this);
360 xe.maybeSetContext(context);
361 throw xe;
362 } catch (XPathException e) {
363 e.maybeSetLocation(this);
364 e.maybeSetContext(context);
365 throw e;
366 } catch (Exception e2) {
367 String message = "Internal error evaluating template rule "
368 + (getLineNumber() > 0 ? " at line " + getLineNumber() : "")
369 + (getSystemId() != null ? " in module " + getSystemId() : "");
370 e2.printStackTrace();
371 throw new RuntimeException(message, e2);
372 }
373 }
374
375 /**
376 * Get the type of construct. This will either be the fingerprint of a standard XSLT instruction name
377 * (values in {@link StandardNames}: all less than 1024)
378 * or it will be a constant in class {@link LocationKind}.
379 */
380
381 public int getConstructType() {
382 return LocationKind.TEMPLATE;
383 }
384
385 /**
386 * Output diagnostic explanation to an ExpressionPresenter
387 */
388
389 public void export(ExpressionPresenter presenter) throws XPathException {
390 // NOT USED - see Rule.export
391 throw new UnsupportedOperationException();
392 // presenter.startElement("template");
393 //
394 // explainProperties(presenter);
395 //
396 // presenter.emitAttribute("slots", "" + getStackFrameMap().getNumberOfVariables());
397 // //presenter.emitAttribute("binds", "" + getDeclaringComponent().getComponentBindings().size());
398 //
399 // if (matchPattern != null) {
400 // presenter.setChildRole("match");
401 // matchPattern.export(presenter);
402 // }
403 // if (getBody() != null) {
404 // presenter.setChildRole("body");
405 // getBody().export(presenter);
406 // }
407 // presenter.endElement();
408 }
409
410 /**
411 * Say whether or not this template is declared as streamable
412 *
413 * @param streamable true if the template belongs to a streamable mode; set to false if it does not belong
414 * to a streamable mode, or if it is found that the template is not actually streamable, and fallback
415 * to non-streaming has been requested.
416 */
417
418 public void setDeclaredStreamable(boolean streamable) {
419 // Overridden in Saxon-EE
420 }
421
422 public boolean isDeclaredStreamable() {
423 // Overridden in Saxon-EE
424 return false;
425 }
426
427 public void explainProperties(ExpressionPresenter presenter) throws XPathException {
428 if (getRequiredContextItemType() != AnyItemType.getInstance()) {
429 presenter.emitAttribute("cxt", getRequiredContextItemType().toString());
430 if ("JS".equals(((ExpressionPresenter.ExportOptions) presenter.getOptions()).target)) {
431 int targetVersion = ((ExpressionPresenter.ExportOptions) presenter.getOptions()).targetVersion;
432 presenter.emitAttribute("jsTest", getRequiredContextItemType().generateJavaScriptItemTypeTest(AnyItemType.getInstance(), targetVersion));
433 }
434 }
435
436 String flags = "";
437 if (!absentFocus) {
438 flags += "s";
439 }
440 presenter.emitAttribute("flags", flags);
441 if (getRequiredType() != SequenceType.ANY_SEQUENCE) {
442 presenter.emitAttribute("as", getRequiredType().toExportString());
443 }
444 presenter.emitAttribute("line", getLineNumber() + "");
445 presenter.emitAttribute("module", getSystemId());
446 if (isDeclaredStreamable()) {
447 presenter.emitAttribute("streamable", "1");
448 }
449 }
450
451 public Expression getInterpretedBody() {
452 return body.getInterpretedExpression();
453 }
454
455
456 /**
457 * Create a copy of a template rule. This is needed when copying a rule from the "omniMode" (mode=#all)
458 * to a specific mode. Because we want the rules to be chained in the right order within the mode object,
459 * we create the copy as soon as we know it is needed. The problem is that at this stage many of the properties
460 * of the template rule are still uninitialised. So we mark the new copy as a slave of the original, and at
461 * the end of the compilation process we update all the slave copies to match the properties of the original.
462 */
463
464 public TemplateRule copy() {
465 TemplateRule tr = new TemplateRule();
466 if (body == null || matchPattern == null) {
467 slaveCopies.add(tr);
468 } else {
469 copyTo(tr);
470 }
471 return tr;
472 }
473
474 /**
475 * Update the properties of template rules that have been marked as slave copies of this one (typically the same
476 * template, but in a different mode).
477 */
478
479 public void updateSlaveCopies() {
480 for (TemplateRule tr : slaveCopies) {
481 copyTo(tr);
482 }
483 }
484
485 protected void copyTo(TemplateRule tr) {
486 if (body != null) {
487 tr.body = body.copy(new RebindingMap());
488 }
489 if (matchPattern != null) {
490 tr.matchPattern = matchPattern.copy(new RebindingMap());
491 }
492 tr.hasRequiredParams = hasRequiredParams;
493 tr.bodyIsTailCallReturner = bodyIsTailCallReturner;
494 tr.requiredType = requiredType;
495 tr.declaredStreamable = declaredStreamable; // ? this can vary from one mode to another
496 tr.requiredContextItemType = requiredContextItemType;
497 tr.absentFocus = absentFocus;
498 tr.stackFrameMap = stackFrameMap;
499 tr.packageData = packageData;
500 tr.systemId = systemId;
501 tr.lineNumber = lineNumber;
502 }
503
504 public void setChildExpression(Expression expr) {
505 setBody(expr);
506 }
507
508 @Override
509 public StructuredQName getObjectName() {
510 return StandardNames.getStructuredQName(StandardNames.XSL_TEMPLATE);
511 }
512
513 @Override
514 public Object getProperty(String name) {
515 return name.equals("match") ? getMatchPattern().toShortString() : null;
516 }
517
518 @Override
519 public Iterator<String> getProperties() {
520 return new MonoIterator<>("match");
521 }
522
523
524 }
525