Debian Codegraph @

net/sf/saxon/style/PrincipalStylesheetModule.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.Expression;
13 import net.sf.saxon.expr.accum.Accumulator;
14 import net.sf.saxon.expr.accum.AccumulatorRegistry;
15 import net.sf.saxon.expr.instruct.*;
16 import net.sf.saxon.expr.parser.ExpressionTool;
17 import net.sf.saxon.expr.parser.Optimizer;
18 import net.sf.saxon.functions.DocumentFn;
19 import net.sf.saxon.functions.ExecutableFunctionLibrary;
20 import net.sf.saxon.lib.SaxonOutputKeys;
21 import net.sf.saxon.om.*;
22 import net.sf.saxon.pattern.NameTest;
23 import net.sf.saxon.pattern.NodeKindTest;
24 import net.sf.saxon.query.XQueryFunction;
25 import net.sf.saxon.query.XQueryFunctionLibrary;
26 import net.sf.saxon.serialize.CharacterMap;
27 import net.sf.saxon.serialize.CharacterMapIndex;
28 import net.sf.saxon.trans.*;
29 import net.sf.saxon.trans.rules.RuleManager;
30 import net.sf.saxon.tree.iter.AxisIterator;
31 import net.sf.saxon.tree.linked.DocumentImpl;
32 import net.sf.saxon.type.Type;
33 import net.sf.saxon.value.Whitespace;
34 import net.sf.saxon.z.IntHashMap;
35
36 import javax.xml.transform.URIResolver;
37 import java.util.*;
38
39
40 /**
41 * Represents both the stylesheet module at the root of the import tree, that is, the module
42 * that includes or imports all the others, and also the XSLT package that has this stylesheet
43 * module as its root.
44 * <p>This version of the StylesheetPackage class represents a trivial package that is constructed
45 * by the system to wrap an ordinary (non-package) stylesheet, as available in XSLT 2.0. A subclass
46 * is used for "real" packages, currently available only in Saxon-EE.</p>
47 */
48 public class PrincipalStylesheetModule extends StylesheetModule implements GlobalVariableManager {
49
50 private StylesheetPackage stylesheetPackage;
51 private boolean declaredModes;
52
53
54 // table of functions imported from XQuery library modules
55 //private XQueryFunctionLibrary queryFunctions;
56
57 // library of functions that are in-scope for XPath expressions in this stylesheet
58 //private FunctionLibraryList functionLibrary;
59
60 // index of global variables and parameters, by StructuredQName
61 // (overridden variables are excluded).
62 private HashMap<StructuredQName, ComponentDeclaration> globalVariableIndex =
63 new HashMap<>(20);
64
65
66 // index of templates - only includes those actually declared within this package
67 private HashMap<StructuredQName, ComponentDeclaration> templateIndex = new HashMap<>(20);
68
69 // Table of named stylesheet functions.
70 private HashMap<SymbolicName, ComponentDeclaration> functionIndex = new HashMap<>(8);
71
72 // key manager for all the xsl:key definitions in this package
73 private KeyManager keyManager;
74
75 // decimal format manager for all the xsl:decimal-format definitions in this package
76 private DecimalFormatManager decimalFormatManager;
77
78 // rule manager for template rules
79 private RuleManager ruleManager;
80
81 // manager class for accumulator rules (XSLT 3.0 only)
82 private AccumulatorRegistry accumulatorManager = null;
83
84 // namespace aliases. This information is needed at compile-time only
85 private int numberOfAliases = 0;
86 private List<ComponentDeclaration> namespaceAliasList = new ArrayList<>(5);
87 private HashMap<String, NamespaceBinding> namespaceAliasMap;
88 private Set<String> aliasResultUriSet;
89
90 // attribute sets. A package can contain several declarations attribute sets with the same name.
91 // They are indexed in the order they will be applied, that is, highest precedence first
92 private Map<StructuredQName, List<ComponentDeclaration>> attributeSetDeclarations = new HashMap<>();
93
94 // cache of stylesheet documents. Note that multiple imports of the same URI
95 // lead to the stylesheet tree being reused
96 private HashMap<DocumentURI, XSLModuleRoot> moduleCache = new HashMap<>(4);
97
98 private TypeAliasManager typeAliasManager;
99
100
101 private CharacterMapIndex characterMapIndex;
102
103 private List<Action> fixupActions = new ArrayList<>();
104 private boolean needsDynamicOutputProperties = false;
105
106
107 /**
108 * Create a PrincipalStylesheetModule
109 *
110 * @param sourceElement the xsl:package element at the root of the package manifest
111 */
112
113 public PrincipalStylesheetModule(XSLPackage sourceElement) throws XPathException {
114 super(sourceElement, 0);
115 declaredModes = sourceElement.isDeclaredModes();
116 stylesheetPackage = getConfiguration().makeStylesheetPackage();
117 CompilerInfo compilerInfo = sourceElement.getCompilation().getCompilerInfo();
118 stylesheetPackage.setTargetEdition(compilerInfo.getTargetEdition());
119 stylesheetPackage.setRelocatable(compilerInfo.isRelocatable());
120 stylesheetPackage.setJustInTimeCompilation(compilerInfo.isJustInTimeCompilation());
121 stylesheetPackage.setImplicitPackage(!sourceElement.getLocalPart().equals("package"));
122
123 keyManager = stylesheetPackage.getKeyManager();
124 decimalFormatManager = stylesheetPackage.getDecimalFormatManager();
125
126 ruleManager = new RuleManager(stylesheetPackage, compilerInfo);
127 ruleManager.getUnnamedMode().makeDeclaringComponent(Visibility.PRIVATE, stylesheetPackage);
128 stylesheetPackage.setRuleManager(ruleManager);
129 stylesheetPackage.setDeclaredModes(declaredModes);
130 StructuredQName defaultMode = sourceElement.getDefaultMode();
131 stylesheetPackage.setDefaultMode(sourceElement.getDefaultMode());
132 if (defaultMode != null) {
133 ruleManager.obtainMode(defaultMode, !declaredModes);
134 }
135
136
137 characterMapIndex = new CharacterMapIndex();
138 stylesheetPackage.setCharacterMapIndex(characterMapIndex);
139
140 typeAliasManager = getConfiguration().makeTypeAliasManager();
141 stylesheetPackage.setTypeAliasManager(typeAliasManager);
142
143 try {
144 setInputTypeAnnotations(sourceElement.getInputTypeAnnotationsAttribute());
145 } catch (XPathException err) {
146 // it will be reported some other time
147 }
148 }
149
150
151 /**
152 * Search the package for a component with a given name
153 *
154 * @param name the symbolic name of the required component
155 * @return the requested component if found, or null otherwise
156 */
157
158 public Component getComponent(SymbolicName name) {
159 return stylesheetPackage.getComponentIndex().get(name);
160 }
161
162 /**
163 * Get the outermost stylesheet module in a package
164 *
165 * @return this module (this class represents both the package and its outermost module)
166 */
167
168 /*@NotNull*/
169 @Override
170 public PrincipalStylesheetModule getPrincipalStylesheetModule() {
171 return this;
172 }
173
174 /**
175 * Get the stylesheet package
176 *
177 * @return the associated stylesheet package
178 */
179
180 public StylesheetPackage getStylesheetPackage() {
181 return stylesheetPackage;
182 }
183
184 /**
185 * Get the key manager used to manage xsl:key declarations in this package
186 *
187 * @return the key manager
188 */
189
190 public KeyManager getKeyManager() {
191 return keyManager;
192 }
193
194 /**
195 * Get the decimal format manager used to manage xsl:decimal-format declarations in this package
196 *
197 * @return the decimal format manager
198 */
199
200 public DecimalFormatManager getDecimalFormatManager() {
201 return decimalFormatManager;
202 }
203
204 /**
205 * Get the rule manager used to manage modes declared explicitly or implicitly in this package
206 *
207 * @return the rule manager
208 */
209
210 public RuleManager getRuleManager() {
211 return ruleManager;
212 }
213
214 /**
215 * Ask whether it is required that modes be explicitly declared
216 *
217 * @return true if modes referenced within this package must be explicitly declared
218 */
219
220 public boolean isDeclaredModes() {
221 return declaredModes;
222 }
223
224
225 /**
226 * Register a callback action to be performed during the fixup phase
227 *
228 * @param action the callback action
229 */
230
231 public void addFixupAction(Action action) {
232 fixupActions.add(action);
233 }
234
235 /**
236 * Say that this stylesheet package needs dynamic output properties
237 *
238 * @param b true if this stylesheet needs dynamic output properties
239 */
240
241 public void setNeedsDynamicOutputProperties(boolean b) {
242 needsDynamicOutputProperties = b;
243 }
244
245
246 /**
247 * Get an index of character maps declared using xsl:character-map entries in this package
248 *
249 * @return the character map index
250 */
251
252 public CharacterMapIndex getCharacterMapIndex() {
253 return characterMapIndex;
254 }
255
256 /**
257 * Get the type alias manager (type aliases are a Saxon extension)
258 *
259 * @return the type alias manager
260 */
261
262 public TypeAliasManager getTypeAliasManager() {
263 return typeAliasManager;
264 }
265
266
267 /**
268 * Declare an imported XQuery function
269 *
270 * @param function the imported function
271 * @throws net.sf.saxon.trans.XPathException if an error occurs
272 */
273
274 public void declareXQueryFunction(XQueryFunction function) throws XPathException {
275 XQueryFunctionLibrary lib = getStylesheetPackage().getXQueryFunctionLibrary();
276 if (getStylesheetPackage().getFunction(function.getUserFunction().getSymbolicName()) != null) {
277 throw new XPathException("Duplication declaration of " +
278 function.getUserFunction().getSymbolicName(), "XQST0034");
279 }
280 lib.declareFunction(function);
281 }
282
283 /**
284 * Add a module to the cache of stylesheet modules
285 *
286 * @param key the key to be used (based on the absolute URI)
287 * @param module the stylesheet document tree corresponding to this absolute URI
288 */
289
290 public void putStylesheetDocument(DocumentURI key, XSLStylesheet module) {
291 moduleCache.put(key, module);
292 }
293
294 /**
295 * Get a module from the cache of stylesheet modules
296 *
297 * @param key the key to be used (based on the absolute URI)
298 * @return the stylesheet document tree corresponding to this absolute URI
299 */
300
301 public XSLModuleRoot getStylesheetDocument(DocumentURI key) {
302 XSLModuleRoot sheet = moduleCache.get(key);
303 if (sheet != null) {
304 XPathException warning = new XPathException(
305 "Stylesheet module " + key + " is included or imported more than once. " +
306 "This is permitted, but may lead to errors or unexpected behavior");
307 sheet.issueWarning(warning);
308 }
309 return sheet;
310 }
311
312 /**
313 * Preprocess does all the processing possible before the source document is available.
314 * It is done once per stylesheet, so the stylesheet can be reused for multiple source
315 * documents. The method is called only on the XSLStylesheet element representing the
316 * principal stylesheet module
317 *
318 * @throws net.sf.saxon.trans.XPathException if errors are found in the stylesheet
319 */
320
321 public void preprocess() throws XPathException {
322
323
324 net.sf.saxon.trans.Timer timer;
325 if (Compilation.TIMING) {
326 timer = new net.sf.saxon.trans.Timer();
327 }
328
329 // process any xsl:use-package, xsl:include and xsl:import elements
330
331 spliceUsePackages((XSLPackage) getRootElement(), getRootElement().getCompilation());
332
333 if (Compilation.TIMING) {
334 timer.report("spliceIncludes");
335 }
336
337 // import schema documents
338
339 importSchemata();
340
341 if (Compilation.TIMING) {
342 timer.report("importSchemata");
343 }
344
345 // process type aliases
346
347 getTypeAliasManager().processAllDeclarations(topLevel);
348
349 // build indexes for selected top-level elements
350
351 buildIndexes();
352
353 if (Compilation.TIMING) {
354 timer.report("buildIndexes");
355 }
356
357 // check for use of schema-aware constructs
358
359 checkForSchemaAwareness();
360
361 if (Compilation.TIMING) {
362 timer.report("checkForSchemaAwareness");
363 }
364
365 // process the attributes of every node in the tree
366
367 processAllAttributes();
368
369 if (Compilation.TIMING) {
370 timer.report("processAllAttributes");
371 }
372 // collect any namespace aliases
373
374 collectNamespaceAliases();
375
376 if (Compilation.TIMING) {
377 timer.report("collectNamespaceAliases");
378 }
379
380 // fix up references from XPath expressions to variables and functions, for static typing
381
382 for (ComponentDeclaration decl : topLevel) {
383 StyleElement inst = decl.getSourceElement();
384 if (!inst.isActionCompleted(StyleElement.ACTION_FIXUP)) {
385 inst.setActionCompleted(StyleElement.ACTION_FIXUP);
386 inst.fixupReferences();
387 }
388 }
389
390 if (Compilation.TIMING) {
391 timer.report("fixupReferences");
392 }
393
394
395 // Validate the whole package (i.e. with included and imported stylesheet modules)
396
397 XSLPackage top = (XSLPackage) getStylesheetElement();
398 //setInputTypeAnnotations(top.getInputTypeAnnotationsAttribute());
399 ComponentDeclaration decl = new ComponentDeclaration(this, top);
400 if (!top.isActionCompleted(StyleElement.ACTION_VALIDATE)) {
401 top.setActionCompleted(StyleElement.ACTION_VALIDATE);
402 top.validate(null);
403 for (ComponentDeclaration d : topLevel) {
404 d.getSourceElement().validateSubtree(d, false);
405 }
406 }
407
408 if (Compilation.TIMING) {
409 timer.report("validate");
410 timer.reportCumulative("total preprocess");
411 }
412
413 // Gather the output properties
414
415 Properties props = gatherOutputProperties(null);
416 props.setProperty(SaxonOutputKeys.STYLESHEET_VERSION, getStylesheetPackage().getVersion() + "");
417 getStylesheetPackage().setDefaultOutputProperties(props);
418
419 // Handle named output formats for use at run-time
420
421 HashSet<StructuredQName> outputNames = new HashSet<>(5);
422 for (ComponentDeclaration outputDecl : topLevel) {
423 if (outputDecl.getSourceElement() instanceof XSLOutput) {
424 XSLOutput out = (XSLOutput) outputDecl.getSourceElement();
425 StructuredQName qName = out.getFormatQName();
426 if (qName != null) {
427 outputNames.add(qName);
428 }
429 }
430 }
431 if (outputNames.isEmpty()) {
432 if (needsDynamicOutputProperties) {
433 throw new XPathException(
434 "The stylesheet contains xsl:result-document instructions that calculate the output " +
435 "format name at run-time, but there are no named xsl:output declarations", "XTDE1460");
436 }
437 } else {
438 for (StructuredQName qName : outputNames) {
439 Properties oprops = gatherOutputProperties(qName);
440 //if (needsDynamicOutputProperties) { // needed for saxon:serialize
441 getStylesheetPackage().setNamedOutputProperties(qName, oprops);
442 //}
443 }
444 }
445
446 // Index the character maps
447
448 for (ComponentDeclaration d : topLevel) {
449 StyleElement inst = d.getSourceElement();
450 if (inst instanceof XSLCharacterMap) {
451 XSLCharacterMap xcm = (XSLCharacterMap) inst;
452 StructuredQName qn = xcm.getCharacterMapName();
453 IntHashMap<String> map = new IntHashMap<>();
454 xcm.assemble(map);
455 characterMapIndex.putCharacterMap(xcm.getCharacterMapName(), new CharacterMap(qn, map));
456 }
457 }
458
459 }
460
461 /**
462 * Incorporate declarations from used packages
463 *
464 * @param xslpackage the used package
465 * @param compilation this compilation
466 * @throws XPathException if any error is detected in the used package
467 */
468
469 protected void spliceUsePackages(XSLPackage xslpackage, Compilation compilation) throws XPathException {
470 // CompilerInfo info = compilation.getCompilerInfo();
471
472 // Warning message deleted by bug 3278
473 // if (info.isVersionWarning() &&
474 // xslpackage.getEffectiveVersion() != 30) {
475 // XPathException w = new XPathException(
476 // "Running an XSLT " + xslpackage.getEffectiveVersionAsString() + " stylesheet with an XSLT 3.0 processor");
477 // w.setLocator(xslpackage);
478 // compilation.reportWarning(w);
479 // }
480
481 List<XSLUsePackage> useDeclarations = new ArrayList<>();
482 gatherUsePackageDeclarations(compilation, xslpackage, useDeclarations);
483
484 // First pass: gather all the named overriding declarations and add them to the topLevel declaration list
485 Set<SymbolicName> overrides = new HashSet<>();
486 for (XSLUsePackage use : useDeclarations) {
487 gatherOverridingDeclarations(use, compilation, overrides);
488 }
489 //gatherOverridingDeclarations(compilation, xslpackage, overrides);
490
491 // Second pass: make modified copies of the named components in the used packages
492 StylesheetPackage thisPackage = getStylesheetPackage();
493 for (XSLUsePackage use : useDeclarations) {
494 List<XSLAccept> acceptors = use.getAcceptors();
495 thisPackage.addComponentsFromUsedPackage(use.getUsedPackage(), acceptors, overrides);
496 }
497
498 // Third pass: process the overriding template rules, creating new mode objects
499 for (XSLUsePackage use : useDeclarations) {
500 use.gatherRuleOverrides(this, overrides);
501 }
502
503 // Now process the declarations contained within this package, both in the top-level module
504 // and within its included and imported modules
505 spliceIncludes();
506 }
507
508
509 private static void gatherUsePackageDeclarations(Compilation compilation, StyleElement wrapper, List<XSLUsePackage> declarations) throws XPathException {
510 wrapper.iterateAxis(AxisInfo.CHILD).forEachOrFail(use -> {
511 if (use instanceof XSLUsePackage) {
512 declarations.add((XSLUsePackage) use);
513 } else if (use instanceof XSLInclude) {
514 String href = Whitespace.trim(use.getAttributeValue("", "href"));
515 URIResolver resolver = compilation.getCompilerInfo().getURIResolver();
516 DocumentURI key = DocumentFn.computeDocumentKey(href, use.getBaseURI(), compilation.getPackageData(), resolver, false);
517 TreeInfo includedTree = compilation.getStylesheetModules().get(key);
518 StyleElement incWrapper = (StyleElement) ((DocumentImpl) includedTree.getRootNode()).getDocumentElement();
519 gatherUsePackageDeclarations(compilation, incWrapper, declarations);
520 }
521 });
522 }
523
524 private void gatherOverridingDeclarations(XSLUsePackage use, Compilation compilation, Set<SymbolicName> overrides) throws XPathException {
525 use.findUsedPackage(compilation.getCompilerInfo());
526 use.gatherNamedOverrides(this, topLevel, overrides);
527 }
528
529
530 /**
531 * Process import-schema declarations
532 *
533 * @throws net.sf.saxon.trans.XPathException if errors are detected
534 */
535
536 protected void importSchemata() throws XPathException {
537 // Outside Saxon-EE, xsl:import-schemas are an error
538 for (int i = topLevel.size() - 1; i >= 0; i--) {
539 ComponentDeclaration decl = topLevel.get(i);
540 if (decl.getSourceElement() instanceof XSLImportSchema) {
541 XPathException xe = new XPathException("xsl:import-schema requires Saxon-EE");
542 xe.setErrorCode("XTSE1650");
543 xe.setLocator(decl.getSourceElement());
544 throw xe;
545 }
546 }
547
548 }
549
550
551 /**
552 * Build indexes for selected top-level declarations
553 *
554 * @throws net.sf.saxon.trans.XPathException if errors are detected
555 */
556
557 private void buildIndexes() throws XPathException {
558 // Scan the declarations in reverse order, that is, highest precedence first
559 for (int i = topLevel.size() - 1; i >= 0; i--) {
560 ComponentDeclaration decl = topLevel.get(i);
561 decl.getSourceElement().index(decl, this);
562 }
563 }
564
565 /**
566 * Process the attributes of every node in the stylesheet
567 *
568 * @throws net.sf.saxon.trans.XPathException if static errors are found in the stylesheet
569 */
570
571 public void processAllAttributes() throws XPathException {
572 getRootElement().processDefaultCollationAttribute();
573 getRootElement().processDefaultMode();
574 getRootElement().prepareAttributes();
575 for (XSLModuleRoot xss : moduleCache.values()) {
576 xss.prepareAttributes();
577 }
578 for (ComponentDeclaration decl : topLevel) {
579 StyleElement inst = decl.getSourceElement();
580 if (!inst.isActionCompleted(StyleElement.ACTION_PROCESS_ATTRIBUTES)) {
581 inst.setActionCompleted(StyleElement.ACTION_PROCESS_ATTRIBUTES);
582 try {
583 inst.processAllAttributes();
584 } catch (XPathException err) {
585 decl.getSourceElement().compileError(err);
586 }
587 }
588 }
589 }
590
591 /**
592 * Add a stylesheet function to the index
593 *
594 * @param decl The declaration wrapping an XSLFunction object
595 */
596 protected void indexFunction(ComponentDeclaration decl) {
597 HashMap<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
598 XSLFunction sourceFunction = (XSLFunction) decl.getSourceElement();
599 UserFunction compiledFunction = sourceFunction.getCompiledFunction();
600 Component declaringComponent = compiledFunction.obtainDeclaringComponent(sourceFunction);
601 SymbolicName.F sName = sourceFunction.getSymbolicName();
602 //StructuredQName qName = template.getTemplateName();
603 if (sName != null) {
604 // see if there is already a named function with this precedence
605 Component other = componentIndex.get(sName);
606 if (other == null) {
607 // this is the first
608 componentIndex.put(sName, declaringComponent);
609 functionIndex.put(sName, decl);
610 } else {
611 if (other.getDeclaringPackage() == getStylesheetPackage()) {
612 // check the precedences
613 int thisPrecedence = decl.getPrecedence();
614 ComponentDeclaration otherFunction = functionIndex.get(sName);
615 int otherPrecedence = otherFunction.getPrecedence();
616 if (thisPrecedence == otherPrecedence) {
617 sourceFunction.compileError("Duplicate named function (see line " +
618 otherFunction.getSourceElement().getLineNumber() + " of " + otherFunction.getSourceElement().getSystemId() + ')', "XTSE0770");
619 } else if (thisPrecedence < otherPrecedence) {
620 //template.setRedundantNamedTemplate();
621 } else {
622 // can't happen, but we'll play safe
623 //other.setRedundantNamedTemplate();
624 componentIndex.put(sName, declaringComponent);
625 functionIndex.put(sName, decl);
626 }
627 } else if (sourceFunction.findAncestorElement(StandardNames.XSL_OVERRIDE) != null) {
628 // the new one wins
629 componentIndex.put(sName, declaringComponent);
630 functionIndex.put(sName, decl);
631 } else {
632 sourceFunction.compileError("Function " + sName.getShortName() +
633 " conflicts with a public function in package " + other.getDeclaringPackage().getPackageName(), "XTSE3050");
634
635 }
636 }
637 }
638
639 }
640
641 /**
642 * Index a global xsl:variable or xsl:param element
643 *
644 * @param decl The Declaration referencing the XSLVariable or XSLParam element
645 * @throws XPathException if an error occurs
646 */
647
648 protected void indexVariableDeclaration(ComponentDeclaration decl) throws XPathException {
649 XSLGlobalVariable varDecl = (XSLGlobalVariable) decl.getSourceElement();
650 StructuredQName qName = varDecl.getSourceBinding().getVariableQName();
651 GlobalVariable compiledVariable = (GlobalVariable) varDecl.getActor();
652 Component declaringComponent = compiledVariable.obtainDeclaringComponent(varDecl);
653 HashMap<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
654 if (qName != null) {
655 // see if there is already a global variable with this precedence
656 SymbolicName sName = varDecl.getSymbolicName();
657 Component other = componentIndex.get(sName);
658 if (other == null) {
659 // this is the first
660 globalVariableIndex.put(qName, decl);
661 componentIndex.put(new SymbolicName(StandardNames.XSL_VARIABLE, qName),
662 varDecl.getActor().getDeclaringComponent());
663 } else {
664 if (other.getDeclaringPackage() == getStylesheetPackage()) {
665 // check the precedences
666 int thisPrecedence = decl.getPrecedence();
667 ComponentDeclaration otherVarDecl = globalVariableIndex.get(sName.getComponentName());
668 int otherPrecedence = otherVarDecl.getPrecedence();
669 if (thisPrecedence == otherPrecedence) {
670 StyleElement v2 = otherVarDecl.getSourceElement();
671 if (v2 == varDecl) {
672 varDecl.compileError(
673 "Global variable or parameter $" + qName.getDisplayName() + " is declared more than once " +
674 "(caused by including the containing module more than once)",
675 "XTSE0630");
676 } else {
677 varDecl.compileError("Duplicate global variable/parameter declaration (see line " +
678 v2.getLineNumber() + " of " + v2.getSystemId() + ')', "XTSE0630");
679 }
680 } else if (thisPrecedence < otherPrecedence && varDecl != otherVarDecl.getSourceElement()) {
681 varDecl.setRedundant(true);
682 } else if (varDecl != otherVarDecl.getSourceElement()) {
683 ((XSLGlobalVariable) otherVarDecl.getSourceElement()).setRedundant(true);
684 globalVariableIndex.put(qName, decl);
685 componentIndex.put(new SymbolicName(StandardNames.XSL_VARIABLE, qName),
686 varDecl.getActor().getDeclaringComponent());
687 }
688 } else if (varDecl.findAncestorElement(StandardNames.XSL_OVERRIDE) != null) {
689 // the new one wins
690 componentIndex.put(sName, declaringComponent);
691 globalVariableIndex.put(sName.getComponentName(), decl);
692 } else {
693 String kind = varDecl instanceof XSLGlobalParam ? "parameter" : "variable";
694 varDecl.compileError("Global " + kind + " $" + sName.getComponentName().getDisplayName() +
695 " conflicts with a public variable/parameter in package " + other.getDeclaringPackage().getPackageName(), "XTSE3050");
696
697 }
698
699 }
700 }
701 }
702
703 /**
704 * Get the global variable or parameter with a given name (taking
705 * precedence rules into account). This will only return global variables
706 * declared in the same package where they are used.
707 *
708 * @param qName name of the global variable or parameter
709 * @return the variable declaration, or null if it does not exist
710 */
711
712 public SourceBinding getGlobalVariableBinding(StructuredQName qName) {
713 ComponentDeclaration decl = globalVariableIndex.get(qName);
714 return decl == null ? null : ((XSLGlobalVariable) decl.getSourceElement()).getSourceBinding();
715 }
716
717 /**
718 * Add a named template to the index
719 *
720 * @param decl the declaration of the Template object
721 * @throws XPathException if an error occurs
722 */
723 protected void indexNamedTemplate(ComponentDeclaration decl) throws XPathException {
724 HashMap<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
725 XSLTemplate sourceTemplate = (XSLTemplate) decl.getSourceElement();
726 SymbolicName sName = sourceTemplate.getSymbolicName();
727 if (sName != null) {
728 // see if there is already a named template with this precedence
729 Component other = componentIndex.get(sName);
730 if (other == null) {
731 // this is the first
732 //NamedTemplate compiledTemplate = new NamedTemplate();
733 NamedTemplate compiledTemplate = ((XSLTemplate) decl.getSourceElement()).getCompiledNamedTemplate();
734 Component declaringComponent = compiledTemplate.obtainDeclaringComponent(sourceTemplate);
735 componentIndex.put(sName, declaringComponent);
736 setLocalParamDetails(sourceTemplate, compiledTemplate);
737 templateIndex.put(sName.getComponentName(), decl);
738 } else {
739 if (other.getDeclaringPackage() == getStylesheetPackage()) {
740 // check the precedences
741 int thisPrecedence = decl.getPrecedence();
742 ComponentDeclaration otherTemplate = templateIndex.get(sName.getComponentName());
743 int otherPrecedence = otherTemplate.getPrecedence();
744 if (thisPrecedence == otherPrecedence) {
745 String errorCode = sourceTemplate.getParent() instanceof XSLOverride ? "XTSE3055" : "XTSE0660";
746 sourceTemplate.compileError("Duplicate named template (see line " +
747 otherTemplate.getSourceElement().getLineNumber() + " of " + otherTemplate.getSourceElement().getSystemId() + ')', errorCode);
748 } else if (thisPrecedence < otherPrecedence) {
749 //return;
750 } else {
751 // can't happen, but we'll play safe
752 //other.setRedundantNamedTemplate();
753 NamedTemplate compiledTemplate = new NamedTemplate(sName.getComponentName());
754 Component declaringComponent = compiledTemplate.obtainDeclaringComponent(sourceTemplate);
755 componentIndex.put(sName, declaringComponent);
756 templateIndex.put(sName.getComponentName(), decl);
757 setLocalParamDetails(sourceTemplate, compiledTemplate);
758 }
759 } else if (sourceTemplate.findAncestorElement(StandardNames.XSL_OVERRIDE) != null) {
760 // the new one wins
761 NamedTemplate compiledTemplate = sourceTemplate.getCompiledNamedTemplate();//new NamedTemplate();
762 Component declaringComponent = compiledTemplate.obtainDeclaringComponent(sourceTemplate);
763 componentIndex.put(sName, declaringComponent);
764 templateIndex.put(sName.getComponentName(), decl);
765 } else {
766 sourceTemplate.compileError("Named template " + sName.getComponentName().getDisplayName() +
767 " conflicts with a public named template in package " + other.getDeclaringPackage().getPackageName(), "XTSE3050");
768
769 }
770 }
771 }
772 }
773
774
775 private static void setLocalParamDetails(XSLTemplate source, NamedTemplate nt) throws XPathException {
776 AxisIterator kids = source.iterateAxis(AxisInfo.CHILD, NodeKindTest.ELEMENT);
777 List<NamedTemplate.LocalParamInfo> details = new ArrayList<>();
778 kids.forEachOrFail(child -> {
779 if (child instanceof XSLLocalParam) {
780 XSLLocalParam lp = (XSLLocalParam) child;
781 lp.prepareTemplateSignatureAttributes();
782 NamedTemplate.LocalParamInfo info = new NamedTemplate.LocalParamInfo();
783 info.name = lp.getVariableQName();
784 info.requiredType = lp.getRequiredType();
785 info.isRequired = lp.isRequiredParam();
786 info.isTunnel = lp.isTunnelParam();
787 details.add(info);
788 }
789 });
790 nt.setLocalParamDetails(details);
791 }
792
793
794 /**
795 * Get the named template with a given name
796 *
797 * @param name the name of the required template
798 * @return the template with the given name, if there is one, or null otherwise. If there
799 * are several templates with the same name, the one with highest import precedence
800 * is returned. Note that this template may subsequently be overridden in another package,
801 * but only by another template with a compatible signature.
802 */
803
804 public NamedTemplate getNamedTemplate(StructuredQName name) {
805 HashMap<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
806 Component component = componentIndex.get(new SymbolicName(StandardNames.XSL_TEMPLATE, name));
807 return component == null ? null : (NamedTemplate) component.getActor();
808 }
809
810 /**
811 * Add an attribute set to the index
812 *
813 * @param decl the declaration of the attribute set object
814 * @throws XPathException if an error occurs
815 */
816 protected void indexAttributeSet(ComponentDeclaration decl) throws XPathException {
817 //HashMap<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
818 XSLAttributeSet sourceAttributeSet = (XSLAttributeSet) decl.getSourceElement();
819 StructuredQName name = sourceAttributeSet.getAttributeSetName();
820 List<ComponentDeclaration> entries = attributeSetDeclarations.get(name);
821 if (entries == null) {
822 entries = new ArrayList<>();
823 attributeSetDeclarations.put(name, entries);
824 } else {
825 String thisVis = Whitespace.trim(sourceAttributeSet.getAttributeValue("", "visibility"));
826 String firstVis = Whitespace.trim(entries.get(0).getSourceElement().getAttributeValue("", "visibility"));
827 if (thisVis == null ? firstVis != null : !thisVis.equals(firstVis)) {
828 throw new XPathException("Visibility attributes on attribute-sets sharing the same name must all be the same", "XTSE0010");
829 }
830 }
831 entries.add(0, decl);
832 }
833
834 /**
835 * Return all the attribute set declarations in the package having a particular QName
836 *
837 * @param name the name of the required declarations
838 * @return the set of declarations having this name, or null if there are none
839 */
840
841 public List<ComponentDeclaration> getAttributeSetDeclarations(StructuredQName name) {
842 return attributeSetDeclarations.get(name);
843 }
844
845 /**
846 * Combine all like-named xsl:attribute-set declarations in this package into a single Component, whose body
847 * is an AttributeSet object. The resulting attribute set Components are saved in the StylesheetPackage
848 * object.
849 *
850 * @throws XPathException if a failure occurs
851 */
852
853
854 public void combineAttributeSets(Compilation compilation) throws XPathException {
855 Map<StructuredQName, AttributeSet> index = new HashMap<>();
856 for (Map.Entry<StructuredQName, List<ComponentDeclaration>> entry : attributeSetDeclarations.entrySet()) {
857 AttributeSet as = new AttributeSet();
858 as.setName(entry.getKey());
859 as.setPackageData(stylesheetPackage);
860 StyleElement firstDecl = entry.getValue().get(0).getSourceElement();
861 as.setSystemId(firstDecl.getSystemId());
862 as.setLineNumber(firstDecl.getLineNumber());
863 index.put(entry.getKey(), as);
864
865 Component declaringComponent = as.getDeclaringComponent();
866 if (declaringComponent == null) {
867 declaringComponent = as.makeDeclaringComponent(Visibility.PRIVATE, stylesheetPackage);
868 }
869 stylesheetPackage.addComponent(declaringComponent);
870 }
871 for (Map.Entry<StructuredQName, List<ComponentDeclaration>> entry : attributeSetDeclarations.entrySet()) {
872 List<Expression> content = new ArrayList<>();
873 Visibility vis = null;
874 boolean explicitVisibility = false;
875 boolean streamable = false;
876
877 // Bug 3195. If the same xsl:attribute-set element is present more than
878 // once in the list, we need to remove all but the last occurrence, otherwise
879 // the same expression will be present more than once in the tree. This can
880 // happen when a stylesheet module is included/imported more than once.
881 List<ComponentDeclaration> entries = new ArrayList<>();
882 Set<XSLAttributeSet> elements = new HashSet<>();
883 for (int i = entry.getValue().size() - 1; i >= 0; i--) {
884 ComponentDeclaration decl = entry.getValue().get(i);
885 XSLAttributeSet src = (XSLAttributeSet) decl.getSourceElement();
886 if (!elements.contains(src)) {
887 entries.add(0, decl);
888 elements.add(src);
889 }
890 }
891 for (ComponentDeclaration decl : entries) {
892 XSLAttributeSet src = (XSLAttributeSet) decl.getSourceElement();
893 streamable |= src.isDeclaredStreamable();
894 src.compileDeclaration(compilation, decl);
895 content.addAll(src.getContainedInstructions());
896 vis = src.getVisibility();
897 explicitVisibility = explicitVisibility || src.getAttributeValue("", "visibility") != null;
898 }
899
900 AttributeSet aSet = index.get(entry.getKey());
901 aSet.setDeclaredStreamable(streamable);
902 Expression block = Block.makeBlock(content);
903 aSet.setBody(block);
904 SlotManager frame = getConfiguration().makeSlotManager();
905 ExpressionTool.allocateSlots(block, 0, frame);
906 aSet.setStackFrameMap(frame);
907 VisibilityProvenance provenance = explicitVisibility ? VisibilityProvenance.EXPLICIT : VisibilityProvenance.DEFAULTED;
908 aSet.getDeclaringComponent().setVisibility(vis, provenance);
909
910 if (streamable) {
911 checkStreamability(aSet);
912 }
913
914 }
915 }
916
917 /**
918 * Check the streamability of an attribute set declared within this stylesheet module.
919 * (Null implementation for Saxon-HE).
920 *
921 * @param aSet the attribute set to be checked
922 * @throws XPathException if the streamability rules are not satisifed
923 */
924
925 protected void checkStreamability(AttributeSet aSet) throws XPathException {
926 }
927
928 /**
929 * Get the list of attribute-set declarations associated with a given QName.
930 * This is used for xsl:element, xsl:copy, xsl:attribute-set, and on literal
931 * result elements
932 *
933 * @param name the name of the required attribute set
934 * @param list a list to hold the list of XSLAttributeSet elements in the stylesheet tree.
935 */
936
937 protected void getAttributeSets(StructuredQName name, List<ComponentDeclaration> list) {
938
939 // search for the named attribute set, using all of them if there are several with the
940 // same name
941
942 for (ComponentDeclaration decl : topLevel) {
943 if (decl.getSourceElement() instanceof XSLAttributeSet) {
944 XSLAttributeSet t = (XSLAttributeSet) decl.getSourceElement();
945 if (t.getAttributeSetName().equals(name)) {
946 list.add(decl);
947 }
948 }
949 }
950 }
951
952 /**
953 * Handle an explicitly-declared mode
954 *
955 * @param decl the declaration of the Mode object
956 */
957 public void indexMode(ComponentDeclaration decl) {
958 XSLMode sourceMode = (XSLMode) decl.getSourceElement();
959 StructuredQName modeName = sourceMode.getObjectName();
960 if (modeName == null) {
961 return; // Not a named mode
962 }
963 SymbolicName sName = new SymbolicName(StandardNames.XSL_MODE, modeName);
964 // see if there is already a named mode with this precedence
965 Mode other = getStylesheetPackage().getRuleManager().obtainMode(modeName, false);
966 if (other != null && other.getDeclaringComponent().getDeclaringPackage() != getStylesheetPackage()) {
967 sourceMode.compileError("Mode " + sName.getComponentName().getDisplayName() +
968 " conflicts with a public mode declared in package " +
969 other.getDeclaringComponent().getDeclaringPackage().getPackageName(), "XTSE3050");
970
971 }
972 }
973
974 /**
975 * Check that it is legitimate to add a given template rule to a given mode
976 *
977 * @param template the template rule
978 * @param mode the mode
979 */
980
981 public boolean checkAcceptableModeForPackage(XSLTemplate template, Mode mode) {
982 StylesheetPackage templatePack = template.getPackageData();
983 if (mode.getDeclaringComponent() == null) {
984 return true;
985 }
986 StylesheetPackage modePack = mode.getDeclaringComponent().getDeclaringPackage();
987 if (templatePack != modePack) {
988 NodeInfo parent = template.getParent();
989 boolean bad = false;
990 if (!(parent instanceof XSLOverride)) {
991 bad = true;
992 } else {
993 NodeInfo grandParent = parent.getParent();
994 if (!(grandParent instanceof XSLUsePackage)) {
995 bad = true;
996 } else {
997 SymbolicName modeName = mode.getSymbolicName();
998 Component.M usedMode = (Component.M)((XSLUsePackage) grandParent).getUsedPackage().getComponent(modeName);
999 if (usedMode == null) {
1000 bad = true;
1001 } else if (usedMode.getVisibility() == Visibility.FINAL) {
1002 bad = true;
1003 }
1004 }
1005 }
1006 if (bad) {
1007 template.compileError("A template rule cannot be added to a mode declared in a used package " +
1008 "unless the xsl:template declaration appears within an xsl:override child of the appropriate xsl:use-package element",
1009 "XTSE3050");
1010 return false;
1011 }
1012 }
1013 return true;
1014 }
1015
1016 /**
1017 * Check for schema-awareness.
1018 * Typed input nodes are recognized if and only if the stylesheet contains an import-schema declaration.
1019 */
1020
1021 private void checkForSchemaAwareness() {
1022 Compilation compilation = getRootElement().getCompilation();
1023 if (!compilation.isSchemaAware() &&
1024 getConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XSLT)) {
1025 for (ComponentDeclaration decl : topLevel) {
1026 StyleElement node = decl.getSourceElement();
1027 if (node instanceof XSLImportSchema) {
1028 compilation.setSchemaAware(true);
1029 return;
1030 }
1031 }
1032 }
1033 }
1034
1035 /**
1036 * Get the class that manages accumulator functions
1037 *
1038 * @return the class that manages accumulators. Always null in Saxon-HE
1039 */
1040
1041 public AccumulatorRegistry getAccumulatorManager() {
1042 return accumulatorManager;
1043 }
1044
1045 /**
1046 * Set the class that manages accumulator functions
1047 *
1048 * @param accumulatorManager the manager of accumulator functions
1049 */
1050
1051 public void setAccumulatorManager(AccumulatorRegistry accumulatorManager) {
1052 this.accumulatorManager = accumulatorManager;
1053 stylesheetPackage.setAccumulatorRegistry(accumulatorManager);
1054 }
1055
1056
1057 protected void addNamespaceAlias(ComponentDeclaration node) {
1058 namespaceAliasList.add(node);
1059 numberOfAliases++;
1060 }
1061
1062 /**
1063 * Get the declared namespace alias for a given namespace URI code if there is one.
1064 * If there is more than one, we get the last.
1065 *
1066 * @param uri The uri used in the stylesheet.
1067 * @return The namespace binding to be used (prefix and uri): return null
1068 * if no alias is defined
1069 */
1070
1071 protected NamespaceBinding getNamespaceAlias(String uri) {
1072 return namespaceAliasMap.get(uri);
1073 }
1074
1075 /**
1076 * Determine if a namespace is included in the result-prefix of a namespace-alias
1077 *
1078 * @param uri the namespace URI
1079 * @return true if an xsl:namespace-alias has been defined for this namespace URI
1080 */
1081
1082 protected boolean isAliasResultNamespace(String uri) {
1083 return aliasResultUriSet.contains(uri);
1084 }
1085
1086 /**
1087 * Collect any namespace aliases
1088 */
1089
1090 private void collectNamespaceAliases() {
1091 namespaceAliasMap = new HashMap<>(numberOfAliases);
1092 aliasResultUriSet = new HashSet<>(numberOfAliases);
1093 HashSet<String> aliasesAtThisPrecedence = new HashSet<>();
1094 int currentPrecedence = -1;
1095 // Note that we are processing the list in reverse stylesheet order,
1096 // that is, highest precedence first.
1097 for (int i = 0; i < numberOfAliases; i++) {
1098 ComponentDeclaration decl = namespaceAliasList.get(i);
1099 XSLNamespaceAlias xna = (XSLNamespaceAlias) decl.getSourceElement();
1100 String scode = xna.getStylesheetURI();
1101 NamespaceBinding resultBinding = xna.getResultNamespaceBinding();
1102 int prec = decl.getPrecedence();
1103
1104 // check that there isn't a conflict with another xsl:namespace-alias
1105 // at the same precedence
1106
1107 if (currentPrecedence != prec) {
1108 currentPrecedence = prec;
1109 aliasesAtThisPrecedence.clear();
1110 //precedenceBoundary = i;
1111 }
1112 if (aliasesAtThisPrecedence.contains(scode)) {
1113 if (!namespaceAliasMap.get(scode).getURI().equals(resultBinding.getURI())) {
1114 xna.compileError("More than one alias is defined for the same namespace", "XTSE0810");
1115 }
1116 }
1117 if (namespaceAliasMap.get(scode) == null) {
1118 namespaceAliasMap.put(scode, resultBinding);
1119 aliasResultUriSet.add(resultBinding.getURI());
1120 }
1121 aliasesAtThisPrecedence.add(scode);
1122 }
1123 namespaceAliasList = null; // throw it in the garbage
1124 }
1125
1126 protected boolean hasNamespaceAliases() {
1127 return numberOfAliases > 0;
1128 }
1129
1130 /**
1131 * Create an output properties object representing the xsl:output elements in the stylesheet.
1132 *
1133 * @param formatQName The name of the output format required. If set to null, gathers
1134 * information for the unnamed output format
1135 * @return the Properties object containing the details of the specified output format
1136 * @throws XPathException if a named output format does not exist in
1137 * the stylesheet
1138 */
1139
1140 public Properties gatherOutputProperties(/*@Nullable*/ StructuredQName formatQName) throws XPathException {
1141 boolean found = formatQName == null;
1142 Configuration config = getConfiguration();
1143 Properties details = new Properties(config.getDefaultSerializationProperties());
1144 HashMap<String, Integer> precedences = new HashMap<>(10);
1145 for (int i = topLevel.size() - 1; i >= 0; i--) {
1146 ComponentDeclaration decl = topLevel.get(i);
1147 if (decl.getSourceElement() instanceof XSLOutput) {
1148 XSLOutput xo = (XSLOutput) decl.getSourceElement();
1149 if (formatQName == null
1150 ? xo.getFormatQName() == null
1151 : formatQName.equals(xo.getFormatQName())) {
1152 found = true;
1153 xo.gatherOutputProperties(details, precedences, decl.getPrecedence());
1154 }
1155 }
1156 }
1157 if (!found) {
1158 compileError("Requested output format " + formatQName.getDisplayName() +
1159 " has not been defined", "XTDE1460");
1160 }
1161 return details;
1162 }
1163
1164
1165 /**
1166 * Compile the source XSLT stylesheet package
1167 *
1168 * @param compilation the compilation episode
1169 * @throws XPathException if compilation fails for any reason
1170 */
1171
1172 protected void compile(Compilation compilation) throws XPathException {
1173
1174 try {
1175
1176 net.sf.saxon.trans.Timer timer;
1177 if (Compilation.TIMING) {
1178 timer = new net.sf.saxon.trans.Timer();
1179 }
1180
1181 //PreparedStylesheet pss = getPreparedStylesheet();
1182 Configuration config = getConfiguration();
1183
1184 // If any XQuery functions were imported, fix up all function calls
1185 // registered against these functions.
1186 XQueryFunctionLibrary queryFunctions = stylesheetPackage.getXQueryFunctionLibrary();
1187 Iterator qf = queryFunctions.getFunctionDefinitions();
1188 while (qf.hasNext()) {
1189 XQueryFunction f = (XQueryFunction) qf.next();
1190 f.fixupReferences();
1191 }
1192
1193 if (Compilation.TIMING) {
1194 timer.report("fixup Query functions");
1195 }
1196
1197 // Register all modes with the rule manager
1198
1199 boolean allowImplicit = !getStylesheetPackage().isDeclaredModes();
1200 for (ComponentDeclaration decl : topLevel) {
1201 StyleElement snode = decl.getSourceElement();
1202 if (snode instanceof XSLMode) {
1203 getRuleManager().obtainMode(snode.getObjectName(), true);
1204 }
1205 if (allowImplicit) {
1206 registerImplicitModes(snode, getRuleManager());
1207 }
1208 }
1209
1210 // Register template rules with the rule manager
1211
1212 for (ComponentDeclaration decl : topLevel) {
1213 StyleElement snode = decl.getSourceElement();
1214 if (snode instanceof XSLTemplate) {
1215 ((XSLTemplate) snode).register(decl);
1216 }
1217 }
1218
1219 if (Compilation.TIMING) {
1220 timer.report("register templates");
1221 }
1222
1223 // Adjust the visibility of components based on xsl:expose declarations
1224
1225 adjustExposedVisibility();
1226
1227 // Call compile method for each top-level object in the stylesheet
1228 // Note, some declarations (templates) need to be compiled repeatedly if the module
1229 // is imported repeatedly; others (variables, functions) do not
1230
1231 for (ComponentDeclaration decl : topLevel) {
1232 StyleElement snode = decl.getSourceElement();
1233 if (!snode.isActionCompleted(StyleElement.ACTION_COMPILE)) {
1234 snode.setActionCompleted(StyleElement.ACTION_COMPILE);
1235 snode.compileDeclaration(compilation, decl);
1236 }
1237 }
1238
1239 if (Compilation.TIMING) {
1240 timer.report("compile top-level objects");
1241 }
1242
1243 // Call type-check method for each user-defined function in the stylesheet. This is no longer
1244 // done during the optimize step, to avoid functions being inlined before they are type-checked.
1245
1246 for (ComponentDeclaration decl : functionIndex.values()) {
1247 StyleElement node = decl.getSourceElement();
1248 if (!node.isActionCompleted(StyleElement.ACTION_TYPECHECK)) {
1249 node.setActionCompleted(StyleElement.ACTION_TYPECHECK);
1250 if (node.getVisibility() != Visibility.ABSTRACT) {
1251 ((XSLFunction) node).getCompiledFunction().typeCheck(node.makeExpressionVisitor());
1252 }
1253 }
1254 }
1255
1256 if (Compilation.TIMING) {
1257 timer.report("typeCheck functions");
1258 }
1259
1260 if (compilation.getErrorCount() > 0) {
1261 // not much point carrying on
1262 return;
1263 }
1264
1265 // Call optimize() method for each top-level declaration
1266
1267 optimizeTopLevel();
1268
1269
1270 // optimize functions that aren't overridden
1271
1272 for (ComponentDeclaration decl : functionIndex.values()) {
1273 StyleElement node = decl.getSourceElement();
1274 if (!node.isActionCompleted(StyleElement.ACTION_OPTIMIZE)) {
1275 node.setActionCompleted(StyleElement.ACTION_OPTIMIZE);
1276 ((StylesheetComponent) node).optimize(decl);
1277 }
1278 }
1279
1280 if (Compilation.TIMING) {
1281 timer.report("optimize");
1282 }
1283
1284 if (Compilation.TIMING) {
1285 timer.report("miscellanea");
1286 }
1287
1288 // Check consistency of decimal formats
1289
1290 getDecimalFormatManager().checkConsistency();
1291
1292 // Check consistency of modes
1293
1294 getRuleManager().checkConsistency();
1295 getRuleManager().computeRankings();
1296
1297
1298 if (Compilation.TIMING) {
1299 timer.report("build template rule tables");
1300 }
1301
1302 // Build a run-time function library. This supports the use of function-available()
1303 // with a dynamic argument, and extensions such as saxon:evaluate(). The run-time
1304 // function library differs from the compile-time function library in that both
1305 // the StylesheetFunctionLibrary's on the library list are replaced by equivalent
1306 // ExecutableFunctionLibrary's. This is to prevent the retaining of run-time links
1307 // to the stylesheet document tree.
1308
1309 ExecutableFunctionLibrary overriding = new ExecutableFunctionLibrary(config);
1310 ExecutableFunctionLibrary underriding = new ExecutableFunctionLibrary(config);
1311
1312 for (Component decl : stylesheetPackage.getComponentIndex().values()) {
1313 Visibility vis = decl.getVisibility();
1314 if (/*(vis == Visibility.PUBLIC || vis == Visibility.FINAL) &&*/ decl.getActor() instanceof UserFunction) {
1315 UserFunction f = (UserFunction) decl.getActor();
1316 if (f.isOverrideExtensionFunction()) {
1317 overriding.addFunction(f);
1318 } else {
1319 underriding.addFunction(f);
1320 }
1321 }
1322 }
1323
1324 getStylesheetPackage().setFunctionLibraryDetails(null, overriding, underriding);
1325
1326 if (Compilation.TIMING) {
1327 timer.report("build runtime function tables");
1328 timer.reportCumulative("total compile phase");
1329 }
1330
1331 // Allocate binding slots to named templates
1332
1333 for (ComponentDeclaration decl : topLevel) {
1334 StyleElement inst = decl.getSourceElement();
1335 if (inst instanceof XSLTemplate) {
1336 NamedTemplate proc = ((XSLTemplate) inst).getActor();
1337 if (proc != null && proc.getTemplateName() == null) {
1338 proc.allocateAllBindingSlots(stylesheetPackage);
1339 }
1340 }
1341 }
1342
1343 // Allocate binding slots to component reference expressions
1344
1345 HashMap<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
1346 for (Component decl : componentIndex.values()) {
1347 Actor proc = decl.getActor();
1348 if (proc != null) {
1349 proc.allocateAllBindingSlots(stylesheetPackage);
1350 }
1351 }
1352
1353 // Allocate binding slots in key definitions
1354
1355 KeyManager keyMan = getKeyManager();
1356 for (KeyDefinitionSet keySet : keyMan.getAllKeyDefinitionSets()) {
1357 for (KeyDefinition keyDef : keySet.getKeyDefinitions()) {
1358 keyDef.makeDeclaringComponent(Visibility.PRIVATE, getStylesheetPackage());
1359 keyDef.allocateAllBindingSlots(stylesheetPackage);
1360 }
1361 }
1362
1363 // Allocate binding slots in accumulators
1364
1365 AccumulatorRegistry accMan = getAccumulatorManager();
1366 if (accMan != null) {
1367 for (Accumulator acc : accMan.getAllAccumulators()) {
1368 acc.allocateAllBindingSlots(stylesheetPackage);
1369 }
1370 }
1371
1372 // Generate byte code where appropriate
1373
1374 if (compilation.getCompilerInfo().isGenerateByteCode() &&
1375 !config.isDeferredByteCode(Configuration.XSLT)) {
1376 if (Compilation.TIMING) {
1377 config.getStandardErrorOutput().println("Generating byte code...");
1378 }
1379
1380 Optimizer opt = config.obtainOptimizer();
1381 for (ComponentDeclaration decl : topLevel) {
1382 StyleElement inst = decl.getSourceElement();
1383 if (inst instanceof StylesheetComponent) {
1384 ((StylesheetComponent) inst).generateByteCode(opt);
1385 }
1386 }
1387 }
1388
1389 } catch (RuntimeException err) {
1390 // if syntax errors were reported earlier, then exceptions may occur during this phase
1391 // due to inconsistency of data structures. We can ignore these exceptions as they
1392 // will go away when the user corrects the stylesheet
1393 if (compilation.getErrorCount() == 0) {
1394 // rethrow the exception
1395 throw err;
1396 }
1397 }
1398 }
1399
1400 private void registerImplicitModes(StyleElement element, RuleManager manager) {
1401 if (element instanceof XSLApplyTemplates || element instanceof XSLTemplate) {
1402 String modeAtt = element.getAttributeValue("mode");
1403 if (modeAtt != null) {
1404 String[] tokens = Whitespace.trim(modeAtt).split("[ \t\n\r]+");
1405 for (String s : tokens) {
1406 if (!s.startsWith("#")) {
1407 try {
1408 StructuredQName modeName = element.makeQName(s);
1409 SymbolicName sName = new SymbolicName(StandardNames.XSL_MODE, modeName);
1410 HashMap<SymbolicName, Component> componentIndex = getStylesheetPackage().getComponentIndex();
1411 Component existing = componentIndex.get(sName);
1412 if (existing != null && existing.getDeclaringPackage() != getStylesheetPackage()) {
1413 if (element instanceof XSLTemplate && !(element.getParent() instanceof XSLOverride)) {
1414 element.compileError("A template rule cannot be added to a mode declared in a used package " +
1415 "unless the xsl:template declaration appears within an xsl:override child of the appropriate xsl:use-package element",
1416 "XTSE3050");
1417 }
1418 } else {
1419 manager.obtainMode(modeName, true);
1420 }
1421 } catch (XPathException e) {
1422 // skip invalid names
1423 }
1424 }
1425 }
1426 }
1427 }
1428 NodeInfo child;
1429 AxisIterator kids = element.iterateAxis(AxisInfo.CHILD);
1430 while ((child = kids.next()) != null) {
1431 if (child instanceof StyleElement) {
1432 registerImplicitModes((StyleElement) child, manager);
1433 }
1434 }
1435 }
1436
1437 public void optimizeTopLevel() throws XPathException {
1438 // Call optimize method for each top-level object in the stylesheet
1439 // But for functions, do it only for those of highest precedence.
1440
1441 for (ComponentDeclaration decl : topLevel) {
1442 StyleElement node = decl.getSourceElement();
1443 if (node instanceof StylesheetComponent && !(node instanceof XSLFunction) &&
1444 !node.isActionCompleted(StyleElement.ACTION_OPTIMIZE)) {
1445 node.setActionCompleted(StyleElement.ACTION_OPTIMIZE);
1446 ((StylesheetComponent) node).optimize(decl);
1447 }
1448 if (node instanceof XSLTemplate) {
1449 ((XSLTemplate) node).allocatePatternSlotNumbers();
1450 }
1451 }
1452 }
1453
1454
1455 /**
1456 * Get an imported schema with a given namespace
1457 *
1458 * @param targetNamespace The target namespace of the required schema.
1459 * Supply an empty string for the default namespace
1460 * @return the required Schema, or null if no such schema has been imported
1461 */
1462
1463 protected boolean isImportedSchema(String targetNamespace) {
1464 return stylesheetPackage.getSchemaNamespaces().contains(targetNamespace);
1465 }
1466
1467 protected void addImportedSchema(String targetNamespace) {
1468 stylesheetPackage.getSchemaNamespaces().add(targetNamespace);
1469 }
1470
1471 protected Set<String> getImportedSchemaTable() {
1472 return stylesheetPackage.getSchemaNamespaces();
1473 }
1474
1475 /**
1476 * Get a character map, identified by the fingerprint of its name.
1477 * Search backwards through the stylesheet.
1478 *
1479 * @param name The character map name being sought
1480 * @return the identified character map, or null if not found
1481 */
1482
1483 public ComponentDeclaration getCharacterMap(StructuredQName name) {
1484 for (int i = topLevel.size() - 1; i >= 0; i--) {
1485 ComponentDeclaration decl = topLevel.get(i);
1486 if (decl.getSourceElement() instanceof XSLCharacterMap) {
1487 XSLCharacterMap t = (XSLCharacterMap) decl.getSourceElement();
1488 if (t.getCharacterMapName().equals(name)) {
1489 return decl;
1490 }
1491 }
1492 }
1493 return null;
1494 }
1495
1496 /**
1497 * Adjust visibility of components by applying xsl:expose rules
1498 */
1499
1500 public void adjustExposedVisibility() throws XPathException {
1501 List<XSLExpose> exposeDeclarations = new ArrayList<>(); // xsl:expose declarations in reverse order
1502 for (ComponentDeclaration decl : topLevel) {
1503 if (decl.getSourceElement() instanceof XSLExpose) {
1504 exposeDeclarations.add(0, (XSLExpose) decl.getSourceElement());
1505 }
1506 }
1507 if (exposeDeclarations.isEmpty()) {
1508 return;
1509 }
1510
1511 NamePool pool = getConfiguration().getNamePool();
1512 Map<SymbolicName, Component> componentIndex = stylesheetPackage.getComponentIndex();
1513 for (Component component : componentIndex.values()) {
1514 // for (ComponentDeclaration decl : topLevel) {
1515 // StyleElement e = decl.getSourceElement();
1516 // int fp = e.getFingerprint();
1517 // if (fp == StandardNames.XSL_VARIABLE ||
1518 // fp == StandardNames.XSL_ATTRIBUTE_SET ||
1519 // fp == StandardNames.XSL_FUNCTION ||
1520 // fp == StandardNames.XSL_MODE ||
1521 // (fp == StandardNames.XSL_TEMPLATE && ((XSLTemplate) e).getTemplateName() != null)) {
1522 // Component component;
1523 // if (fp == StandardNames.XSL_MODE) {
1524 // component = getRuleManager().obtainMode(e.getObjectName(), false).getDeclaringComponent();
1525 // } else {
1526 // component = ((StylesheetComponent) e).getActor().getDeclaringComponent();
1527 // }
1528 int fp = component.getComponentKind();
1529 ComponentTest exactNameTest =
1530 new ComponentTest(fp,
1531 new NameTest(Type.ELEMENT, new FingerprintedQName(component.getActor().getObjectName(), pool), pool), -1);
1532 ComponentTest exactFunctionTest = null;
1533 if (fp == StandardNames.XSL_FUNCTION) {
1534 Function fn = (Function)component.getActor();
1535 exactFunctionTest =
1536 new ComponentTest(fp,
1537 new NameTest(Type.ELEMENT,
1538 new FingerprintedQName(fn.getFunctionName(), pool), pool), fn.getArity());
1539 }
1540 boolean matched = false;
1541 for (XSLExpose exposure : exposeDeclarations) {
1542 Set<ComponentTest> explicitComponentTests = exposure.getExplicitComponentTests();
1543 if (explicitComponentTests.contains(exactNameTest) ||
1544 (exactFunctionTest != null && explicitComponentTests.contains(exactFunctionTest))) {
1545 component.setVisibility(exposure.getVisibility(), VisibilityProvenance.EXPOSED);
1546 matched = true;
1547 break;
1548 }
1549 }
1550 if (!matched && component.getVisibilityProvenance() == VisibilityProvenance.DEFAULTED) {
1551 // Look for a matching wildcard
1552 partialWildcardSearch:
1553 for (XSLExpose exposure : exposeDeclarations) {
1554 for (ComponentTest test : exposure.getWildcardComponentTests()) {
1555 if (test.isPartialWildcard() && test.matches(component.getActor())) {
1556 component.setVisibility(exposure.getVisibility(), VisibilityProvenance.EXPOSED);
1557 matched = true;
1558 break partialWildcardSearch;
1559 }
1560 }
1561 }
1562 if (!matched) {
1563 anyWildcardSearch:
1564 for (XSLExpose exposure : exposeDeclarations) {
1565 for (ComponentTest test : exposure.getWildcardComponentTests()) {
1566 if (test.matches(component.getActor())) {
1567 component.setVisibility(exposure.getVisibility(), VisibilityProvenance.EXPOSED);
1568 break anyWildcardSearch;
1569 }
1570 }
1571 }
1572 }
1573
1574 }
1575
1576 }
1577 }
1578
1579 /**
1580 * Compile time error, specifying an error code
1581 *
1582 * @param message the error message
1583 * @param errorCode the error code. May be null if not known or not defined
1584 * @throws XPathException unconditionally
1585 */
1586
1587 protected void compileError(String message, String errorCode) throws XPathException {
1588 XPathException tce = new XPathException(message, errorCode);
1589 compileError(tce);
1590 }
1591
1592 /**
1593 * Report an error with diagnostic information
1594 *
1595 * @param error contains information about the error
1596 */
1597
1598 protected void compileError(XPathException error) {
1599 error.setIsStaticError(true);
1600 getRootElement().compileError(error);
1601 }
1602
1603 protected void fixup() throws XPathException {
1604 // Perform the fixup actions
1605 for (Action a : fixupActions) {
1606 a.doAction();
1607 }
1608 }
1609
1610 protected void complete() throws XPathException {
1611 stylesheetPackage.complete();
1612 }
1613
1614 public SlotManager getSlotManager() {
1615 return null;
1616 }
1617
1618
1619 @Override
1620 public GlobalVariable getEquivalentVariable(Expression select) {
1621 return null; // implemented in Saxon-EE
1622 }
1623
1624 @Override
1625 public void addGlobalVariable(GlobalVariable variable) {
1626 addGlobalVariable(variable, Visibility.PRIVATE);
1627 }
1628
1629 public void addGlobalVariable(GlobalVariable variable, Visibility visibility) {
1630 Component component = variable.makeDeclaringComponent(visibility, getStylesheetPackage());
1631 if (variable.getPackageData() == null) {
1632 variable.setPackageData(stylesheetPackage);
1633 }
1634 if (visibility == Visibility.HIDDEN) {
1635 stylesheetPackage.addHiddenComponent(component);
1636 } else {
1637 stylesheetPackage.getComponentIndex().put(
1638 new SymbolicName(StandardNames.XSL_VARIABLE, variable.getVariableQName()), component);
1639 }
1640 }
1641
1642
1643 }
1644