Debian Codegraph @

net/sf/saxon/style/XSLTemplate.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.style;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.Component;
12 import net.sf.saxon.expr.ErrorExpression;
13 import net.sf.saxon.expr.Expression;
14 import net.sf.saxon.expr.StaticProperty;
15 import net.sf.saxon.expr.instruct.*;
16 import net.sf.saxon.expr.parser.*;
17 import net.sf.saxon.lib.Feature;
18 import net.sf.saxon.lib.Logger;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.pattern.Pattern;
22 import net.sf.saxon.trace.LocationKind;
23 import net.sf.saxon.trans.*;
24 import net.sf.saxon.trans.rules.Rule;
25 import net.sf.saxon.trans.rules.RuleManager;
26 import net.sf.saxon.tree.iter.AxisIterator;
27 import net.sf.saxon.tree.linked.NodeImpl;
28 import net.sf.saxon.type.AnyItemType;
29 import net.sf.saxon.type.ErrorType;
30 import net.sf.saxon.type.ItemType;
31 import net.sf.saxon.type.TypeHierarchy;
32 import net.sf.saxon.value.BigDecimalValue;
33 import net.sf.saxon.value.SequenceType;
34 import net.sf.saxon.value.Whitespace;
35
36 import java.util.*;
37
38 /**
39 * An xsl:template element in the style sheet.
40 */
41
42 public final class XSLTemplate extends StyleElement implements StylesheetComponent {
43
44 private String matchAtt = null;
45 private String modeAtt = null;
46 private String nameAtt = null;
47 private String priorityAtt = null;
48 private String asAtt = null;
49 private String visibilityAtt = null;
50
51 private StructuredQName[] modeNames;
52 private String diagnosticId;
53 private Pattern match;
54 private boolean prioritySpecified;
55 private double priority;
56 private SlotManager stackFrameMap;
57 // A compiled named template exists if the template has a name
58 private NamedTemplate compiledNamedTemplate;
59 // A set of compiled template rules exists if the template has a match pattern: one TemplateRule for each mode
60 private Map<StructuredQName, TemplateRule> compiledTemplateRules = new HashMap<>();
61 private SequenceType requiredType = SequenceType.ANY_SEQUENCE;
62 private boolean hasRequiredParams = false;
63 private boolean isTailRecursive = false;
64 private Visibility visibility = Visibility.PRIVATE;
65 private ItemType requiredContextItemType = AnyItemType.getInstance();
66 private boolean mayOmitContextItem = true;
67 //private boolean maySupplyContextItem = true;
68 private boolean absentFocus = false;
69 private boolean jitCompilationDone = false;
70 //private Expression body;
71
72 /**
73 * Get the corresponding NamedTemplate object that results from the compilation of this
74 * StylesheetComponent
75 */
76 public NamedTemplate getActor() {
77 return compiledNamedTemplate;
78 }
79
80 // public Expression getBody() {
81 // return body;
82 // }
83
84 @Override
85 public void setCompilation(Compilation compilation) {
86 super.setCompilation(compilation);
87 //compiledNamedTemplate.setPackageData(compilation.getPackageData());
88 }
89
90 /**
91 * Ask whether this node is a declaration, that is, a permitted child of xsl:stylesheet
92 * (including xsl:include and xsl:import).
93 *
94 * @return true for this element
95 */
96
97 @Override
98 public boolean isDeclaration() {
99 return true;
100 }
101
102 /**
103 * Ask whether the compilation of the template should be deferred
104 *
105 * @param compilation the compilation
106 * @return true if compilation should be deferred
107 */
108
109 public boolean isDeferredCompilation(Compilation compilation) {
110 return compilation.isPreScan() && getTemplateName() == null && !compilation.isLibraryPackage();
111 }
112
113 /**
114 * Determine whether this type of element is allowed to contain a template-body
115 *
116 * @return true: yes, it may contain a template-body
117 */
118
119 public boolean mayContainSequenceConstructor() {
120 return true;
121 }
122
123 protected boolean mayContainParam() {
124 return true;
125 }
126
127 protected boolean isWithinDeclaredStreamableConstruct() {
128 try {
129 for (Mode m : getApplicableModes()) {
130 if (m.isDeclaredStreamable()) {
131 return true;
132 }
133 }
134 } catch (XPathException e) {
135 return false;
136 }
137 return false;
138 }
139
140 /**
141 * Set the required context item type. Used when there is an xsl:context-item child element
142 *
143 * @param type the required context item type
144 * @param mayBeOmitted true if the context item may be absent
145 * @param absentFocus true if use=absent is specified
146 */
147
148 public void setContextItemRequirements(ItemType type, boolean mayBeOmitted, boolean absentFocus) {
149 requiredContextItemType = type;
150 mayOmitContextItem = mayBeOmitted;
151 this.absentFocus = absentFocus;
152 }
153
154 /**
155 * Specify that xsl:param and xsl:context-item are permitted children
156 */
157
158 protected boolean isPermittedChild(StyleElement child) {
159 return child instanceof XSLLocalParam || child.getFingerprint() == StandardNames.XSL_CONTEXT_ITEM;
160 }
161
162 /**
163 * Return the name of this template. Note that this may
164 * be called before prepareAttributes has been called.
165 *
166 * @return the name of the template as a Structured QName.
167 */
168
169 /*@Nullable*/
170 public StructuredQName getTemplateName() {
171
172 //We use null to mean "not yet evaluated"
173
174 try {
175 if (getObjectName() == null) {
176 // allow for forwards references
177 String nameAtt = getAttributeValue("", "name");
178 if (nameAtt != null) {
179 setObjectName(makeQName(nameAtt));
180 }
181 }
182 return getObjectName();
183 } catch (XPathException err) {
184 return null; // the errors will be picked up later
185 }
186 }
187
188 public SymbolicName getSymbolicName() {
189 if (getTemplateName() == null) {
190 return null;
191 } else {
192 return new SymbolicName(StandardNames.XSL_TEMPLATE, getTemplateName());
193 }
194 }
195
196 public ItemType getRequiredContextItemType() {
197 return requiredContextItemType;
198 }
199
200 public boolean isMayOmitContextItem() {
201 return mayOmitContextItem;
202 }
203
204
205 public void checkCompatibility(Component component) {
206 NamedTemplate other = (NamedTemplate) component.getActor();
207 if (!getSymbolicName().equals(other.getSymbolicName())) {
208 throw new IllegalArgumentException();
209 }
210
211 SequenceType req = requiredType == null ? SequenceType.ANY_SEQUENCE : requiredType;
212 if (!req.equals(other.getRequiredType())) {
213 compileError("The overriding template has a different required type from the overridden template", "XTSE3070");
214 return;
215 }
216
217 if (!requiredContextItemType.equals(other.getRequiredContextItemType()) ||
218 mayOmitContextItem != other.isMayOmitContextItem() ||
219 absentFocus != other.isAbsentFocus()) {
220 compileError("The required context item for the overriding template differs from that of the overridden template", "XTSE3070");
221 return;
222 }
223
224 List<NamedTemplate.LocalParamInfo> otherParams = other.getLocalParamDetails();
225 Set<StructuredQName> overriddenParams = new HashSet<>();
226 for (NamedTemplate.LocalParamInfo lp0 : otherParams) {
227 XSLLocalParam lp1 = getParam(lp0.name);
228 if (lp1 == null) {
229 if (!lp0.isTunnel) {
230 compileError("The overridden template declares a parameter " +
231 lp0.name.getDisplayName() + " which is not declared in the overriding template", "XTSE3070");
232 }
233 return;
234 }
235 if (!lp1.getRequiredType().equals(lp0.requiredType)) {
236 lp1.compileError("The parameter " +
237 lp0.name.getDisplayName() + " has a different required type in the overridden template", "XTSE3070");
238 return;
239 }
240 if (lp1.isRequiredParam() != lp0.isRequired && !lp0.isTunnel) {
241 lp1.compileError("The parameter " +
242 lp0.name.getDisplayName() + " is " +
243 (lp1.isRequiredParam() ? "required" : "optional") +
244 " in the overriding template, but " +
245 (lp0.isRequired ? "required" : "optional") +
246 " in the overridden template", "XTSE3070");
247 return;
248 }
249 if (lp1.isTunnelParam() != lp0.isTunnel) {
250 lp1.compileError("The parameter " +
251 lp0.name.getDisplayName() + " is a " +
252 (lp1.isTunnelParam() ? "tunnel" : "non-tunnel") +
253 " parameter in the overriding template, but " +
254 (lp0.isTunnel ? "tunnel" : "non-tunnel") +
255 " parameter in the overridden template", "XTSE3070");
256 return;
257 }
258 overriddenParams.add(lp0.name);
259 }
260
261 AxisIterator params = iterateAxis(AxisInfo.CHILD);
262 NodeInfo param;
263 while ((param = params.next()) != null) {
264 if (param instanceof XSLLocalParam &&
265 !overriddenParams.contains(((XSLLocalParam) param).getObjectName()) &&
266 ((XSLLocalParam) param).isRequiredParam()) {
267 ((XSLLocalParam) param).compileError(
268 "An overriding template cannot introduce a required parameter that is not declared in the overridden template", "XTSE3070");
269 }
270 }
271
272 }
273
274 public XSLLocalParam getParam(StructuredQName name) {
275 AxisIterator params = iterateAxis(AxisInfo.CHILD);
276 NodeInfo param;
277 while ((param = params.next()) != null) {
278 if (param instanceof XSLLocalParam && name.equals(((XSLLocalParam) param).getObjectName())) {
279 return (XSLLocalParam) param;
280 }
281 }
282 return null;
283 }
284
285
286 public void prepareAttributes() throws XPathException {
287
288 AttributeCollection atts = getAttributeList();
289 String extraAsAtt = null;
290
291 for (int a = 0; a < atts.getLength(); a++) {
292 String f = atts.getQName(a);
293 if (f.equals("mode")) {
294 modeAtt = Whitespace.trim(atts.getValue(a));
295 } else if (f.equals("name")) {
296 nameAtt = Whitespace.trim(atts.getValue(a));
297 } else if (f.equals("match")) {
298 matchAtt = atts.getValue(a);
299 } else if (f.equals("priority")) {
300 priorityAtt = Whitespace.trim(atts.getValue(a));
301 } else if (f.equals("as")) {
302 asAtt = atts.getValue(a);
303 } else if (f.equals("visibility")) {
304 visibilityAtt = Whitespace.trim(atts.getValue(a));
305 } else if (atts.getURI(a).equals(NamespaceConstant.SAXON)) {
306 if (atts.getLocalName(a).equals("as")) {
307 extraAsAtt = atts.getValue(a);
308 }
309 } else {
310 checkUnknownAttribute(atts.getNodeName(a));
311 }
312 }
313 try {
314 if (modeAtt == null) {
315 if (matchAtt != null) {
316 // XSLT 3.0 allows the default mode to be specified on any element
317 StructuredQName defaultMode = getDefaultMode();
318 if (defaultMode == null) {
319 defaultMode = Mode.UNNAMED_MODE_NAME;
320 }
321 modeNames = new StructuredQName[1];
322 modeNames[0] = defaultMode;
323 }
324 } else {
325 if (matchAtt == null) {
326 compileError("The mode attribute must be absent if the match attribute is absent", "XTSE0500");
327 }
328 getModeNames();
329 }
330 } catch (XPathException err) {
331 err.maybeSetErrorCode("XTSE0280");
332 if (err.getErrorCodeLocalPart().equals("XTSE0020")) {
333 err.setErrorCode("XTSE0550");
334 }
335 err.setIsStaticError(true);
336 compileError(err);
337 }
338
339 try {
340 if (nameAtt != null) {
341 StructuredQName qName = makeQName(nameAtt);
342 setObjectName(qName);
343 if (compiledNamedTemplate != null /*bug3549*/) {
344 compiledNamedTemplate.setTemplateName(qName);
345 }
346 diagnosticId = nameAtt;
347 }
348 } catch (XPathException err) {
349 err.maybeSetErrorCode("XTSE0280");
350 err.setIsStaticError(true);
351 compileError(err);
352 }
353
354 prioritySpecified = priorityAtt != null;
355 if (prioritySpecified) {
356 if (matchAtt == null) {
357 compileError("The priority attribute must be absent if the match attribute is absent", "XTSE0500");
358 }
359 try {
360 // it's got to be a valid decimal, but we want it as a double, so parse it twice
361 if (!BigDecimalValue.castableAsDecimal(priorityAtt)) {
362 compileError("Invalid numeric value for priority (" + priority + ')', "XTSE0530");
363 }
364 priority = Double.parseDouble(priorityAtt);
365 } catch (NumberFormatException err) {
366 // shouldn't happen
367 compileError("Invalid numeric value for priority (" + priority + ')', "XTSE0530");
368 }
369 }
370
371 if (matchAtt != null) {
372 match = makePattern(matchAtt, "match");
373 if (diagnosticId == null) {
374 diagnosticId = "match=\"" + matchAtt + '\"';
375 if (modeAtt != null) {
376 diagnosticId += " mode=\"" + modeAtt + '\"';
377 }
378 }
379 }
380
381 if (match == null && nameAtt == null) {
382 compileError("xsl:template must have a name or match attribute (or both)", "XTSE0500");
383 }
384 if (asAtt != null) {
385 try {
386 requiredType = makeSequenceType(asAtt);
387 } catch (XPathException e) {
388 compileErrorInAttribute(e.getMessage(), e.getErrorCodeLocalPart(), "as");
389 }
390 }
391
392 if (extraAsAtt != null) {
393 SequenceType extraResultType = null;
394 try {
395 extraResultType = makeExtendedSequenceType(extraAsAtt);
396 } catch (XPathException e) {
397 compileErrorInAttribute(e.getMessage(), e.getErrorCodeLocalPart(), "saxon:as");
398 extraResultType = requiredType; // error recovery
399 }
400 if (asAtt != null) {
401 int rel = getConfiguration().getTypeHierarchy().sequenceTypeRelationship(extraResultType, requiredType);
402 if (rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMED_BY) {
403 requiredType = extraResultType;
404 } else {
405 compileErrorInAttribute("When both are present, @saxon:as must be a subtype of @as", "SXER7TBA", "saxon:as");
406 }
407 } else {
408 requiredType = extraResultType;
409 }
410 }
411
412 if (visibilityAtt != null) {
413 visibility = interpretVisibilityValue(visibilityAtt, "");
414 if (nameAtt == null) {
415 compileError("xsl:template/@visibility can be specified only if the template has a @name attribute", "XTSE0020");
416 } else {
417 compiledNamedTemplate.setDeclaredVisibility(getVisibility());
418 }
419 }
420 }
421
422 @Override
423 public void processAllAttributes() throws XPathException {
424 String mode = getAttributeValue("mode");
425 mode = mode == null ? "" : Whitespace.trim(mode);
426 if (!isDeferredCompilation(getCompilation())) {
427 super.processAllAttributes(); //TODO - sort out the duplicated code. This repeats the code below
428 } else {
429 processDefaultCollationAttribute();
430 processDefaultMode();
431 staticContext = new ExpressionContext(this, null);
432 processAttributes();
433
434 }
435 }
436
437 /**
438 * Return the list of mode names to which this template rule is applicable.
439 *
440 * @return the list of mode names. If the mode attribute is absent, #default is assumed.
441 * If #default is present explicitly or implicitly, it is replaced by the default mode, taken
442 * from the in-scope default-modes attribute, which defaults to #unnamed. The unnamed mode
443 * is represented by {@link Mode#UNNAMED_MODE_NAME}. The token #all translates to
444 * {@link Mode#OMNI_MODE}.
445 * @throws XPathException if the attribute is invalid.
446 */
447
448 public StructuredQName[] getModeNames() throws XPathException {
449 if (modeNames == null) {
450 // modeAtt is a space-separated list of mode names, or "#default", or "#all"
451 if (modeAtt == null) {
452 modeAtt = getAttributeValue("mode");
453 if (modeAtt == null) {
454 modeAtt = "#default";
455 }
456 }
457
458 boolean allModes = false;
459 String[] tokens = Whitespace.trim(modeAtt).split("[ \t\n\r]+");
460 int count = tokens.length;
461
462 modeNames = new StructuredQName[count];
463 count = 0;
464 for (String s : tokens) {
465 StructuredQName mname;
466 if ("#default".equals(s)) {
467 mname = getDefaultMode();
468 if (mname == null) {
469 mname = Mode.UNNAMED_MODE_NAME;
470 }
471 } else if ("#unnamed".equals(s)) {
472 mname = Mode.UNNAMED_MODE_NAME;
473 } else if ("#all".equals(s)) {
474 allModes = true;
475 mname = Mode.OMNI_MODE;
476 } else {
477 try {
478 mname = makeQName(s);
479 } catch (XPathException e) {
480 compileError(e.getMessage(), "XTSE0550");
481 mname = Mode.UNNAMED_MODE_NAME;
482 }
483 }
484 for (int e = 0; e < count; e++) {
485 if (modeNames[e].equals(mname)) {
486 compileError("In the list of modes, the value " + s + " is duplicated", "XTSE0550");
487 }
488 }
489 modeNames[count++] = mname;
490 }
491 if (allModes && (count > 1)) {
492 compileError("mode='#all' cannot be combined with other modes", "XTSE0550");
493 }
494 }
495 return modeNames;
496 }
497
498 /**
499 * Get the modes to which this template rule applies
500 *
501 * @return the set of modes to which it applies
502 * @throws XPathException should not happen
503 */
504
505 public Set<Mode> getApplicableModes() throws XPathException {
506 StructuredQName[] names = getModeNames();
507 Set<Mode> modes = new HashSet<>(names.length);
508 RuleManager mgr = getPrincipalStylesheetModule().getRuleManager();
509 for (StructuredQName name : names) {
510 if (name.equals(Mode.OMNI_MODE)) {
511 modes.add(mgr.getUnnamedMode());
512 modes.addAll(mgr.getAllNamedModes());
513 } else {
514 Mode mode = mgr.obtainMode(name, false);
515 if (mode != null) {
516 modes.add(mode);
517 }
518 }
519 }
520 return modes;
521 }
522
523 /**
524 * Ask whether this is a template rule with mode="#all
525 */
526
527 public boolean isOmniMode() throws XPathException {
528 for (StructuredQName name : getModeNames()) {
529 if (name.equals(Mode.OMNI_MODE)) {
530 return true;
531 }
532 }
533 return false;
534 }
535
536 public void validate(ComponentDeclaration decl) throws XPathException {
537 stackFrameMap = getConfiguration().makeSlotManager();
538 checkTopLevel("XTSE0010", true);
539
540 // the check for duplicates is now done in the buildIndexes() method of XSLStylesheet
541 if (match != null) {
542 match = typeCheck("match", match);
543 if (match.getItemType() instanceof ErrorType) {
544 issueWarning(new XPathException("Pattern will never match anything", SaxonErrorCode.SXWN9015, this));
545 }
546 if (getPrincipalStylesheetModule().isDeclaredModes()) {
547 RuleManager manager = getPrincipalStylesheetModule().getRuleManager();
548 if (modeNames != null) {
549 for (StructuredQName name : modeNames) {
550 if (name.equals(Mode.UNNAMED_MODE_NAME) && !manager.isUnnamedModeExplicit()) {
551 compileError("The unnamed mode has not been declared in an xsl:mode declaration", "XTSE3085");
552 }
553 if (manager.obtainMode(name, false) == null) {
554 compileError("Mode name " + name.getDisplayName() + " has not been declared in an xsl:mode declaration", "XTSE3085");
555 }
556 }
557 } else {
558 if (!manager.isUnnamedModeExplicit()) {
559 compileError("The unnamed mode has not been declared in an xsl:mode declaration", "XTSE3085");
560 }
561 }
562 }
563 if (visibility == Visibility.ABSTRACT) {
564 compileError("An abstract template must have no match attribute");
565 }
566 }
567
568 // See if there are any required parameters.
569 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
570 boolean hasContent = false;
571 NodeImpl param;
572 while ((param = (NodeImpl) kids.next()) != null) {
573 if (param instanceof StyleElement) {
574 if (param.getFingerprint() == StandardNames.XSL_CONTEXT_ITEM) {
575 // no action
576 } else if (param instanceof XSLLocalParam) {
577 if (((XSLLocalParam) param).isRequiredParam()) {
578 hasRequiredParams = true;
579 }
580 } else {
581 hasContent = true;
582 }
583 }
584 }
585
586 if (visibility == Visibility.ABSTRACT && hasContent) {
587 compileError("A template with visibility='abstract' must have no body");
588 }
589
590 }
591
592 @Override
593 public void validateSubtree(ComponentDeclaration decl, boolean excludeStylesheet) throws XPathException {
594 if (!isDeferredCompilation(getCompilation())) {
595 super.validateSubtree(decl, excludeStylesheet);
596 } else {
597 try {
598 validate(decl);
599 } catch (XPathException err) {
600 compileError(err);
601 }
602 }
603 }
604
605 public void index(ComponentDeclaration decl, PrincipalStylesheetModule top) throws XPathException {
606 if (getTemplateName() != null) {
607 if (compiledNamedTemplate == null) {
608 compiledNamedTemplate = new NamedTemplate(getTemplateName());
609 }
610 top.indexNamedTemplate(decl);
611 }
612
613 }
614
615 /**
616 * Mark tail-recursive calls on templates and functions.
617 */
618
619 public boolean markTailCalls() {
620 StyleElement last = getLastChildInstruction();
621 return last != null && last.markTailCalls();
622 }
623
624 /**
625 * Compile: creates the executable form of the template
626 */
627
628 public void compileDeclaration(Compilation compilation, ComponentDeclaration decl) throws XPathException {
629 if (isDeferredCompilation(compilation)) {
630 createSkeletonTemplate(compilation, decl);
631 //System.err.println("Deferred - " + ++lazy);
632 return;
633 }
634 if (compilation.getCompilerInfo().getOptimizerOptions().isSet(OptimizerOptions.TAIL_CALLS)) {
635 isTailRecursive = markTailCalls();
636 }
637 Expression body = compileSequenceConstructor(compilation, decl, true);
638 body.restoreParentPointers();
639 RetainedStaticContext rsc = makeRetainedStaticContext();
640 if (body.getRetainedStaticContext() == null) {
641 body.setRetainedStaticContext(rsc); // bug 2608
642 }
643 if (match != null && compilation.getConfiguration().getBooleanProperty(Feature.STRICT_STREAMABILITY) &&
644 isWithinDeclaredStreamableConstruct()) {
645 checkStrictStreamability(body);
646 }
647 if (getTemplateName() != null) {
648 compileNamedTemplate(compilation, body, decl);
649 }
650 if (match != null) {
651 //System.err.println("Rules compiled - " + ++eager);
652 compileTemplateRule(compilation, body, decl);
653 }
654 }
655
656 private void checkStrictStreamability(Expression body) throws XPathException {
657 getConfiguration().checkStrictStreamability(this, body);
658 }
659
660 private void compileNamedTemplate(Compilation compilation, Expression body, ComponentDeclaration decl) throws XPathException {
661 RetainedStaticContext rsc = body.getRetainedStaticContext();
662 compiledNamedTemplate.setPackageData(rsc.getPackageData());
663 compiledNamedTemplate.setBody(body);
664 compiledNamedTemplate.setStackFrameMap(stackFrameMap);
665 compiledNamedTemplate.setSystemId(getSystemId());
666 compiledNamedTemplate.setLineNumber(getLineNumber());
667 compiledNamedTemplate.setHasRequiredParams(hasRequiredParams);
668 compiledNamedTemplate.setRequiredType(requiredType);
669 compiledNamedTemplate.setContextItemRequirements(requiredContextItemType, mayOmitContextItem, absentFocus);
670 compiledNamedTemplate.setRetainedStaticContext(rsc);
671 compiledNamedTemplate.setDeclaredVisibility(getDeclaredVisibility());
672 Component overridden = getOverriddenComponent();
673 if (overridden != null) {
674 checkCompatibility(overridden);
675 }
676
677 ContextItemStaticInfo cisi = getConfiguration().makeContextItemStaticInfo(requiredContextItemType, mayOmitContextItem);
678 Expression body2 = refineTemplateBody(body, cisi);
679
680 compiledNamedTemplate.setBody(body2);
681
682 }
683
684 private Expression refineTemplateBody(Expression body, ContextItemStaticInfo cisi) {
685 Expression old = body;
686 try {
687 body = body.simplify();
688 } catch (XPathException e) {
689 if (e.isReportableStatically()) {
690 compileError(e);
691 } else {
692 body = new ErrorExpression(e);
693 ExpressionTool.copyLocationInfo(old, body);
694 }
695 }
696
697 Configuration config = getConfiguration();
698 if (visibility != Visibility.ABSTRACT) {
699 try {
700 if (requiredType != null && requiredType != SequenceType.ANY_SEQUENCE) {
701 RoleDiagnostic role =
702 new RoleDiagnostic(RoleDiagnostic.TEMPLATE_RESULT, diagnosticId, 0);
703 role.setErrorCode("XTTE0505");
704 body = config.getTypeChecker(false).staticTypeCheck(body, requiredType, role, makeExpressionVisitor());
705 }
706 } catch (XPathException err) {
707 if (err.isReportableStatically()) {
708 compileError(err);
709 }
710 body = new ErrorExpression(err);
711 ExpressionTool.copyLocationInfo(old, body);
712 }
713 }
714
715 if (getCompilation().getCompilerInfo().isCompileWithTracing()) {
716 // Add trace wrapper code if required
717 body = makeTraceInstruction(this, body);
718 if (body instanceof TraceExpression) {
719 ((TraceExpression) body).setProperty("match", matchAtt);
720 ((TraceExpression) body).setProperty("mode", modeAtt);
721 }
722 }
723
724 try {
725 ExpressionVisitor visitor = makeExpressionVisitor();
726 body = body.typeCheck(visitor, cisi);
727 } catch (XPathException e) {
728 compileError(e);
729 }
730
731 return body;
732 }
733
734 public void compileTemplateRule(Compilation compilation, Expression body, ComponentDeclaration decl) {
735
736 Configuration config = getConfiguration();
737
738 if (getTemplateName() != null) {
739 body = body.copy(new RebindingMap());
740 }
741
742 ItemType contextItemType;
743 ContextItemStaticInfo cisi;
744 // the template can't be called by name, so the context item must match the match pattern
745 contextItemType = match.getItemType();
746 if (contextItemType.equals(ErrorType.getInstance())) {
747 // if the match pattern can't match anything, we produce a warning, not a hard error
748 contextItemType = AnyItemType.getInstance();
749 }
750 cisi = config.makeContextItemStaticInfo(contextItemType, false);
751 body = refineTemplateBody(body, cisi);
752
753 boolean needToCopy = false;
754 for (TemplateRule rule : compiledTemplateRules.values()) {
755 if (needToCopy) {
756 body = body.copy(new RebindingMap());
757 }
758 setCompiledTemplateRuleProperties(rule, body);
759 needToCopy = true;
760 rule.updateSlaveCopies();
761 }
762
763 // following code needed only for diagnostics
764 //body.verifyParentPointers();
765 }
766
767 private void createSkeletonTemplate(Compilation compilation, ComponentDeclaration decl) throws XPathException {
768 StructuredQName[] modes = modeNames;
769 if (isOmniMode()) {
770 List<StructuredQName> all = new ArrayList<>();
771 all.add(Mode.UNNAMED_MODE_NAME);
772 RuleManager mgr = getCompilation().getPrincipalStylesheetModule().getRuleManager();
773 for (Mode m : mgr.getAllNamedModes()) {
774 all.add(m.getModeName());
775 }
776 modes = all.toArray(new StructuredQName[0]);
777 }
778 for (StructuredQName modeName : modes) {
779 TemplateRule templateRule = compiledTemplateRules.get(modeName);
780 if (templateRule == null) {
781 templateRule = getConfiguration().makeTemplateRule();
782 }
783 templateRule.prepareInitializer(compilation, decl, modeName);
784 compiledTemplateRules.put(modeName, templateRule);
785 RetainedStaticContext rsc = makeRetainedStaticContext();
786 templateRule.setPackageData(rsc.getPackageData());
787 setCompiledTemplateRuleProperties(templateRule, null);
788 }
789 }
790
791 private void setCompiledTemplateRuleProperties(TemplateRule templateRule, Expression body) {
792 templateRule.setMatchPattern(match);
793 templateRule.setBody(body);
794 templateRule.setStackFrameMap(stackFrameMap);
795 templateRule.setSystemId(getSystemId());
796 templateRule.setLineNumber(getLineNumber());
797 templateRule.setHasRequiredParams(hasRequiredParams);
798 templateRule.setRequiredType(requiredType);
799 templateRule.setContextItemRequirements(requiredContextItemType, absentFocus);
800 }
801
802 /**
803 * Code executed when the template is first executed under JIT. If the template is defined in several
804 * modes, then this may be called several times, but it only does anything the first time. Mode-specific
805 * processing is done in the TemplateRuleInitializer.
806 *
807 * @param compilation the compilation episode
808 * @param decl the template rule declaration
809 * @throws XPathException if anything goes wrong
810 */
811
812 public synchronized void jitCompile(Compilation compilation, ComponentDeclaration decl) throws XPathException {
813 if (!jitCompilationDone) {
814 jitCompilationDone = true;
815 compilation.setPreScan(false);
816 processAllAttributes();
817
818 if (compilation.getErrorCount() > 0) {
819 XPathException e = new XPathException("Errors were reported during stylesheet compilation");
820 e.setHasBeenReported(true); // only intended as an exception message, not something to report to ErrorListener
821 throw e;
822 }
823
824 validateSubtree(decl, false);
825
826 if (compilation.getErrorCount() > 0) {
827 XPathException e = new XPathException("Errors were reported during stylesheet compilation");
828 e.setHasBeenReported(true); // only intended as an exception message, not something to report to ErrorListener
829 throw e;
830 }
831
832 compileDeclaration(compilation, decl);
833 // xslTemplate.optimize(decl);
834 //allocateBindingSlots();
835 if (compilation.getErrorCount() > 0) {
836 XPathException e = new XPathException("Errors were reported during stylesheet compilation");
837 e.setHasBeenReported(true); // only intended as an exception message, not something to report to ErrorListener
838 throw e;
839 }
840 }
841
842 }
843
844
845 /**
846 * Registers the template rule with each Mode that it belongs to.
847 *
848 * @param declaration Associates this template with a stylesheet module (in principle an xsl:template
849 * element can be in a document that is imported more than once; these are separate declarations)
850 * @throws XPathException if a failure occurs
851 */
852
853 public void register(ComponentDeclaration declaration) throws XPathException {
854 if (match != null) {
855 StylesheetModule module = declaration.getModule();
856 RuleManager mgr = getCompilation().getPrincipalStylesheetModule().getRuleManager();
857 ExpressionVisitor visitor = ExpressionVisitor.make(getStaticContext());
858 for (StructuredQName modeName : getModeNames()) {
859 Mode mode = mgr.obtainMode(modeName, false);
860 if (mode == null) {
861 if (mgr.existsOmniMode()) {
862 Mode omniMode = mgr.obtainMode(Mode.OMNI_MODE, true);
863 mode = mgr.obtainMode(modeName, true);
864 SimpleMode.copyRules(omniMode.getActivePart(), mode.getActivePart());
865 } else {
866 mode = mgr.obtainMode(modeName, true);
867 }
868 } else {
869 boolean ok = getPrincipalStylesheetModule().checkAcceptableModeForPackage(this, mode);
870 if (!ok) {
871 return;
872 }
873 }
874 Pattern match1 = match.copy(new RebindingMap());
875 String typed = mode.getActivePart().getPropertyValue("typed");
876 if ("strict".equals(typed) || "lax".equals(typed)) {
877 Pattern match2;
878 try {
879 match2 = match1.convertToTypedPattern(typed);
880 } catch (XPathException e) {
881 e.maybeSetLocation(this);
882 throw e;
883 }
884 if (match2 != match1) {
885 ContextItemStaticInfo info = getConfiguration().makeContextItemStaticInfo(AnyItemType.getInstance(), false);
886 ExpressionTool.copyLocationInfo(match, match2);
887 match2.setOriginalText(match.toString());
888 match2 = match2.typeCheck(visitor, info);
889 match1 = match2;
890 }
891 if (modeNames.length == 1) {
892 // If this is the only mode for the template, then we can use this enhanced match pattern
893 // for subsequent type-checking of the template body.
894 // TODO: we can now do this for all modes...
895 // TODO: but we need to take account of mode=#all, where modeNames.length==1
896 match = match2;
897 }
898 }
899 TemplateRule rule = compiledTemplateRules.get(modeName);
900 if (rule == null) {
901 rule = getConfiguration().makeTemplateRule();
902 compiledTemplateRules.put(modeName, rule);
903 }
904
905 double prio = prioritySpecified ? priority : Double.NaN;
906 mgr.registerRule(match1, rule, mode, module, prio, mgr.allocateSequenceNumber(), 0);
907
908 if (mode.isDeclaredStreamable()) {
909 rule.setDeclaredStreamable(true);
910 if (!match1.isMotionless()) {
911 boolean fallback = getConfiguration().getBooleanProperty(Feature.STREAMING_FALLBACK);
912 String message = "Template rule is declared streamable but the match pattern is not motionless";
913 if (fallback) {
914 message += "\n * Falling back to non-streaming implementation";
915 getStaticContext().issueWarning(message, this);
916 rule.setDeclaredStreamable(false);
917 getCompilation().setFallbackToNonStreaming(true);
918 } else {
919 throw new XPathException(message, "XTSE3430", this);
920 }
921 }
922 }
923
924 // if adding a rule to the omniMode (mode='all') add it to all
925 // the other modes as well. For all but the first, it needs to
926 // be copied because the external component bindings might
927 // differ from one mode to another.
928
929 if (mode.getModeName().equals(Mode.OMNI_MODE)) {
930 compiledTemplateRules.put(Mode.UNNAMED_MODE_NAME, rule);
931 mgr.registerRule(match1, rule, mgr.getUnnamedMode(), module, prio, mgr.allocateSequenceNumber(), 0);
932 for (Mode m : mgr.getAllNamedModes()) {
933 if (m instanceof SimpleMode) {
934 TemplateRule ruleCopy = rule.copy();
935 if (m.isDeclaredStreamable()) {
936 ruleCopy.setDeclaredStreamable(true);
937 }
938 compiledTemplateRules.put(m.getModeName(), ruleCopy);
939 mgr.registerRule(match1.copy(new RebindingMap()),
940 ruleCopy, m, module, prio, mgr.allocateSequenceNumber(), 0);
941 }
942 }
943 }
944 }
945 }
946 }
947
948 /**
949 * Allocate slot numbers to any local variables declared within a predicate within the match pattern
950 */
951
952 public void allocatePatternSlotNumbers() {
953 if (match != null) {
954 for (TemplateRule templateRule : compiledTemplateRules.values()) {
955 for (Rule r : templateRule.getRules()) {
956 // In the case of a union pattern, allocate slots separately for each branch
957 Pattern match = r.getPattern();
958 // first slot in pattern is reserved for current()
959 int nextFree = 0;
960 if ((match.getDependencies() & StaticProperty.DEPENDS_ON_CURRENT_ITEM) != 0) {
961 nextFree = 1;
962 }
963 int slots = match.allocateSlots(getSlotManager(), nextFree);
964 // if the pattern calls user-defined functions, allocate at least one slot,
965 // to force a new context to be created for evaluating patterns (bug 3706)
966 if (slots == 0 && ((match.getDependencies() & StaticProperty.DEPENDS_ON_USER_FUNCTIONS) != 0)) {
967 slots = 1;
968 }
969 if (slots > 0) {
970 RuleManager mgr = getCompilation().getPrincipalStylesheetModule().getRuleManager();
971 boolean appliesToAll = false;
972 for (StructuredQName nc : modeNames) {
973 if (nc.equals(Mode.OMNI_MODE)) {
974 appliesToAll = true;
975 break;
976 }
977 Mode mode = mgr.obtainMode(nc, true);
978 mode.getActivePart().allocatePatternSlots(slots);
979 }
980 if (appliesToAll) {
981 for (Mode m : mgr.getAllNamedModes()) {
982 m.getActivePart().allocatePatternSlots(slots);
983 }
984 mgr.getUnnamedMode().getActivePart().allocatePatternSlots(slots);
985 }
986 }
987
988 }
989 }
990 }
991 }
992
993
994 /**
995 * This method is a bit of a misnomer, because it does more than invoke optimization of the template body.
996 * In particular, it also registers the template rule with each Mode that it belongs to.
997 *
998 * @param declaration Associates this template with a stylesheet module (in principle an xsl:template
999 * element can be in a document that is imported more than once; these are separate declarations)
1000 * @throws XPathException if errors are found
1001 */
1002
1003 public void optimize(ComponentDeclaration declaration) throws XPathException {
1004 Configuration config = getConfiguration();
1005 if (compiledNamedTemplate != null) {
1006 Expression body = compiledNamedTemplate.getBody();
1007 ContextItemStaticInfo cisi = getConfiguration().makeContextItemStaticInfo(requiredContextItemType, mayOmitContextItem);
1008
1009 ExpressionVisitor visitor = makeExpressionVisitor();
1010 body = body.typeCheck(visitor, cisi);
1011 body = ExpressionTool.optimizeComponentBody(body, getCompilation(), visitor, cisi, true);
1012 compiledNamedTemplate.setBody(body);
1013
1014 allocateLocalSlots(body);
1015 if (isExplaining()) {
1016 Logger err = getConfiguration().getLogger();
1017 err.info("Optimized expression tree for named template at line " +
1018 getLineNumber() + " in " + getSystemId() + ':');
1019 body.explain(err);
1020 }
1021 body.restoreParentPointers();
1022 if (config.isDeferredByteCode(Configuration.XSLT) && !isTailRecursive) {
1023 Optimizer opt = config.obtainOptimizer();
1024 int evaluationModes = Expression.ITERATE_METHOD | Expression.PROCESS_METHOD;
1025 compiledNamedTemplate.setBody(opt.makeByteCodeCandidate(compiledNamedTemplate, body, diagnosticId, evaluationModes));
1026 }
1027 }
1028 if (match != null) {
1029 ItemType contextItemType = getContextItemTypeForTemplateRule();
1030 ContextItemStaticInfo cisi = config.makeContextItemStaticInfo(contextItemType, false);
1031 cisi.setContextPostureStriding();
1032 ExpressionVisitor visitor = makeExpressionVisitor();
1033 match.resetLocalStaticProperties();
1034 match = match.optimize(visitor, cisi);
1035
1036 if (!isDeferredCompilation(getCompilation())) {
1037 Expression body = compiledTemplateRules.values().stream().findFirst().map(TemplateRule::getBody).orElse(null);
1038 // Until now, all template rules share the same body.
1039
1040 ExpressionTool.resetPropertiesWithinSubtree(body);
1041 // visitor.setOptimizeForStreaming(compiledNamedTemplate.isDeclaredStreamable());
1042 Optimizer opt = getConfiguration().obtainOptimizer();
1043 try {
1044 // We've already done the typecheck of each XPath expression, but it's worth doing again at this
1045 // level because we have more information now.
1046 // body = body.typeCheck(visitor, cit);
1047 // ExpressionTool.resetPropertiesWithinSubtree(body);
1048
1049
1050 for (TemplateRule compiledTemplateRule : compiledTemplateRules.values()) {
1051 Expression templateRuleBody = compiledTemplateRules.size() > 1 ? body.copy(new RebindingMap()) : body;
1052 visitor.setOptimizeForStreaming(compiledTemplateRule.isDeclaredStreamable());
1053 templateRuleBody = templateRuleBody.typeCheck(visitor, cisi);
1054 templateRuleBody = ExpressionTool.optimizeComponentBody(templateRuleBody, getCompilation(), visitor, cisi, true);
1055 compiledTemplateRule.setBody(templateRuleBody);
1056 opt.checkStreamability(this, compiledTemplateRule);
1057 allocateLocalSlots(templateRuleBody);
1058 for (Rule r : compiledTemplateRule.getRules()) {
1059 Pattern match = r.getPattern();
1060 ContextItemStaticInfo info = getConfiguration().makeContextItemStaticInfo(match.getItemType(), false);
1061 info.setContextPostureStriding();
1062 Pattern m2 = match.optimize(visitor, info);
1063 if (compiledTemplateRules.size() > 1) {
1064 m2 = m2.copy(new RebindingMap());
1065 }
1066 if (m2 != match) {
1067 r.setPattern(m2);
1068 }
1069 }
1070
1071 if (visitor.getConfiguration().isDeferredByteCode(Configuration.XSLT) && !isTailRecursive) {
1072 int evaluationModes = Expression.ITERATE_METHOD | Expression.PROCESS_METHOD;
1073 compiledTemplateRule.setBody(opt.makeByteCodeCandidate(compiledTemplateRule, templateRuleBody, diagnosticId, evaluationModes));
1074 }
1075
1076 if (isExplaining()) {
1077 Logger err = getConfiguration().getLogger();
1078 err.info("Optimized expression tree for template rule at line " +
1079 getLineNumber() + " in " + getSystemId() + ':');
1080 templateRuleBody.explain(err);
1081 }
1082 }
1083 } catch (XPathException e) {
1084 e.maybeSetLocation(this);
1085 compileError(e);
1086 }
1087 }
1088 }
1089
1090 }
1091
1092 public ItemType getContextItemTypeForTemplateRule() throws XPathException {
1093 Configuration config = getConfiguration();
1094 ItemType contextItemType = match.getItemType();
1095 if (contextItemType.equals(ErrorType.getInstance())) {
1096 // if the match pattern can't match anything, we produce a warning, not a hard error
1097 contextItemType = AnyItemType.getInstance();
1098 }
1099 if (requiredContextItemType != AnyItemType.getInstance()) {
1100 int rel = config.getTypeHierarchy().relationship(contextItemType, requiredContextItemType);
1101 switch (rel) {
1102 case TypeHierarchy.DISJOINT:
1103 XPathException e = new XPathException("The declared context item type is inconsistent with the match pattern", "XPTY0004", this);
1104 e.setIsTypeError(true);
1105 throw e;
1106 case TypeHierarchy.SUBSUMED_BY:
1107 case TypeHierarchy.OVERLAPS:
1108 case TypeHierarchy.SAME_TYPE:
1109 // no action
1110 break;
1111 case TypeHierarchy.SUBSUMES:
1112 contextItemType = requiredContextItemType;
1113 break;
1114 }
1115 }
1116 return contextItemType;
1117 }
1118
1119
1120 /**
1121 * Generate byte code for the template (if appropriate)
1122 *
1123 * @param opt the optimizer
1124 * @throws XPathException if byte code generation fails
1125 */
1126
1127 public void generateByteCode(Optimizer opt) throws XPathException {
1128 // Generate byte code if appropriate
1129
1130 if (getCompilation().getCompilerInfo().isGenerateByteCode() && !isTailRecursive) {
1131 ICompilerService compilerService = getConfiguration().makeCompilerService(Configuration.XSLT);
1132 if (getTemplateName() != null) {
1133 try {
1134 Expression exp = compiledNamedTemplate.getBody();
1135 Expression cbody = opt.compileToByteCode(compilerService, exp, nameAtt, Expression.PROCESS_METHOD);
1136 if (cbody != null) {
1137 compiledNamedTemplate.setBody(cbody);
1138 }
1139 } catch (Exception e) {
1140 System.err.println("Failed while compiling named template " + nameAtt);
1141 e.printStackTrace();
1142 throw new XPathException(e);
1143 }
1144 }
1145 for (TemplateRule compiledTemplateRule : compiledTemplateRules.values()) {
1146 if (!compiledTemplateRule.isDeclaredStreamable()) {
1147 try {
1148 Expression exp = compiledTemplateRule.getBody();
1149 if (exp != null) {
1150 Expression cbody = opt.compileToByteCode(compilerService, exp, matchAtt, Expression.PROCESS_METHOD);
1151 if (cbody != null) {
1152 compiledTemplateRule.setBody(cbody);
1153 }
1154 }
1155 } catch (Exception e) {
1156 System.err.println("Failed while compiling template rule with match = '" + matchAtt + "'");
1157 e.printStackTrace();
1158 throw new XPathException(e);
1159 }
1160 }
1161 }
1162 }
1163 }
1164
1165
1166 /**
1167 * Get associated Procedure (for details of stack frame)
1168 */
1169
1170 public SlotManager getSlotManager() {
1171 return stackFrameMap;
1172 }
1173
1174
1175 /**
1176 * Get the compiled template
1177 *
1178 * @return the compiled template
1179 */
1180
1181 public NamedTemplate getCompiledNamedTemplate() {
1182 return compiledNamedTemplate;
1183 }
1184
1185 /**
1186 * Get the type of construct. This will be a constant in
1187 * class {@link LocationKind}. This method is part of the {@link net.sf.saxon.trace.InstructionInfo} interface
1188 */
1189
1190 public int getConstructType() {
1191 return StandardNames.XSL_TEMPLATE;
1192 }
1193
1194
1195 public Pattern getMatch() {
1196 return match;
1197 }
1198
1199 public Map<StructuredQName, TemplateRule> getTemplateRulesByMode() {
1200 return compiledTemplateRules;
1201 }
1202 }
1203