Debian Codegraph @

net/sf/saxon/style/StylesheetPackage.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.PreparedStylesheet;
12 import net.sf.saxon.expr.Component;
13 import net.sf.saxon.expr.ComponentBinding;
14 import net.sf.saxon.expr.PackageData;
15 import net.sf.saxon.expr.instruct.*;
16 import net.sf.saxon.expr.parser.OptimizerOptions;
17 import net.sf.saxon.functions.ExecutableFunctionLibrary;
18 import net.sf.saxon.functions.FunctionLibrary;
19 import net.sf.saxon.functions.FunctionLibraryList;
20 import net.sf.saxon.functions.registry.ConstructorFunctionLibrary;
21 import net.sf.saxon.om.Action;
22 import net.sf.saxon.om.SpaceStrippingRule;
23 import net.sf.saxon.om.StructuredQName;
24 import net.sf.saxon.pattern.NodeTest;
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.trace.ExpressionPresenter;
29 import net.sf.saxon.trans.*;
30 import net.sf.saxon.trans.rules.RuleManager;
31 import net.sf.saxon.tree.util.FastStringBuffer;
32 import net.sf.saxon.type.TypeHierarchy;
33
34 import java.util.*;
35
36 import static net.sf.saxon.trans.Visibility.PRIVATE;
37
38 /**
39 * A (compiled) stylesheet package. This may be created either by compiling a source XSLT package,
40 * or by loading a saved package from disk. It therefore has no references to source XSLT documents.
41 */
42 public class StylesheetPackage extends PackageData {
43
44 private final static boolean TRACING = false;
45
46 private PackageVersion packageVersion = null;
47 private String packageName;
48 private List<StylesheetPackage> usedPackages = new ArrayList<>();
49 private int xsltVersion;
50
51 private RuleManager ruleManager;
52 private CharacterMapIndex characterMapIndex;
53
54 private boolean createsSecondaryResultDocuments;
55
56 private List<Action> completionActions = new ArrayList<>();
57 protected GlobalContextRequirement globalContextRequirement = null;
58 private boolean containsGlobalContextItemDeclaration = false;
59 protected SpaceStrippingRule stripperRules;
60 private boolean stripsWhitespace = false;
61 private boolean stripsTypeAnnotations = false;
62 protected Properties defaultOutputProperties;
63 private StructuredQName defaultMode;
64 private boolean declaredModes;
65 protected Map<StructuredQName, Properties> namedOutputProperties = new HashMap<>(4);
66 private boolean implicitPackage;
67
68 // table of imported schemas. The members of this set are strings holding the target namespace.
69 protected Set<String> schemaIndex = new HashSet<>(10);
70
71 private FunctionLibraryList functionLibrary;
72 private XQueryFunctionLibrary queryFunctions;
73 private ExecutableFunctionLibrary overriding;
74 private ExecutableFunctionLibrary underriding;
75 private int maxFunctionArity = -1;
76 private boolean retainUnusedFunctions = false;
77
78
79 // Table of components declared in this package or imported from used packages. Key is the symbolic identifier of the
80 // component; value is the component itself. Hidden components are not included in this table because their names
81 // need not be unique, and because they are not available for reference by name.
82
83 private HashMap<SymbolicName, Component> componentIndex = new HashMap<>(20);
84
85 protected List<Component> hiddenComponents = new ArrayList<>();
86
87 protected HashMap<SymbolicName, Component> overriddenComponents = new HashMap<>();
88
89 private HashMap<SymbolicName, Component> abstractComponents = new HashMap<>();
90
91 /**
92 * Create a stylesheet package
93 *
94 * @param config the Saxon Configuration
95 */
96
97 public StylesheetPackage(Configuration config) {
98 super(config);
99 setHostLanguage(Configuration.XSLT);
100 setAccumulatorRegistry(config.makeAccumulatorRegistry());
101 }
102
103 /**
104 * Get a map containing all the components in this package, indexed by symbolic name
105 *
106 * @return a map containing all the components in the package. This does not include components
107 * in used packages, except to the extent that they have been copied into this package.
108 */
109
110 public HashMap<SymbolicName, Component> getComponentIndex() {
111 return componentIndex;
112 }
113
114 /**
115 * Get the packages referenced from this package in an xsl:use-package declaration
116 *
117 * @return the packages used by this package
118 */
119
120 public Iterable<StylesheetPackage> getUsedPackages() {
121 return usedPackages;
122 }
123
124 /**
125 * Add a package to the list of packages directly used by this one
126 * @param pack the used package
127 */
128
129 public void addUsedPackage(StylesheetPackage pack) {
130 usedPackages.add(pack);
131 }
132
133 /**
134 * Ask whether a given library package is within the package subtree rooted at this package
135 * @param pack the library package
136 * @return true if the given library package is in the transitive contents of this package
137 */
138
139 public boolean contains(StylesheetPackage pack) {
140 for (StylesheetPackage p : usedPackages) {
141 if (p == pack || p.contains(pack)) {
142 return true;
143 }
144 }
145 return false;
146 }
147
148 /**
149 * Set the version of the XSLT language specification to which the package manifest conforms
150 *
151 * @param version the version (times ten) as an integer
152 */
153 public void setVersion(int version) {
154 this.xsltVersion = version;
155 }
156
157 /**
158 * Set the name of the package
159 *
160 * @param packageName the name of the package. This is supposed to be an absolute URI, but Saxon accepts any string.
161 */
162 public void setPackageName(String packageName) {
163 this.packageName = packageName;
164 }
165
166 /**
167 * Get the version of the XSLT language specification to which the package manifest conforms
168 *
169 * @return the version of the xslPackage, times ten, as an integer
170 */
171 public int getVersion() {
172 return xsltVersion;
173 }
174
175 /**
176 * Get the package-version identifier appearing on the xsl:package element
177 *
178 * @return the version identifier as a structured entity
179 */
180 public PackageVersion getPackageVersion() {
181 return packageVersion;
182 }
183
184 /**
185 * Set the package-version identifier appearing on the xsl:package element
186 *
187 * @param version the version identifier as a structured entity
188 */
189 public void setPackageVersion(PackageVersion version) {
190 packageVersion = version;
191 }
192
193 /**
194 * Get the name identifier of the xsl:package as an absolute URI
195 *
196 * @return a string value. This is supposed to be an absolute URI, but Saxon accepts any string.
197 */
198 public String getPackageName() {
199 return packageName;
200 }
201
202 /**
203 * Ask if this is an implicit package (one rooted at xsl:stylesheet or xsl:transform rather than xsl:package
204 * @return true if this package was rooted at an xsl:stylesheet or xsl:transform element
205 */
206 public boolean isImplicitPackage() {
207 return implicitPackage;
208 }
209
210 /**
211 * Say whether this is an implicit package (one rooted at xsl:stylesheet or xsl:transform rather than xsl:package
212 * @param implicitPackage true if this package was rooted at an xsl:stylesheet or xsl:transform element
213 */
214
215 public void setImplicitPackage(boolean implicitPackage) {
216 this.implicitPackage = implicitPackage;
217 }
218
219
220 /**
221 * Ask whether the package was compiled with just-in-time compilation of template rules enabled
222 *
223 * @return false (always) for Saxon-HE
224 */
225
226 public boolean isJustInTimeCompilation() {
227 return false;
228 }
229
230 /**
231 * Say whether the package was compiled with just-in-time compilation of template rules enabled.
232 * This method is called by the compiler itself and should not be called by users. The setting is ignored
233 * in Saxon-HE.
234 *
235 * @param justInTimeCompilation set to true if just-in-time compilation was enabled when the package was compiled
236 */
237
238 public void setJustInTimeCompilation(boolean justInTimeCompilation) {
239 // no action
240 }
241
242 /**
243 * Get the rule manager, which knows about all the modes present in the package
244 * @return the rule manager
245 */
246
247 public RuleManager getRuleManager() {
248 return ruleManager;
249 }
250
251 /**
252 * Set the rule manager, which knows about all the modes present in the package
253 * @param ruleManager the rule manager
254 */
255
256 public void setRuleManager(RuleManager ruleManager) {
257 this.ruleManager = ruleManager;
258 }
259
260
261 /**
262 * Get the default mode for the package
263 * @return the default mode for the package as a whole (this may change for individual elements/subtrees within
264 * the package)
265 */
266
267 public StructuredQName getDefaultMode() {
268 return defaultMode;
269 }
270
271 /**
272 * Set the default mode for the package
273 * @param defaultMode the default mode for the package
274 */
275
276 public void setDefaultMode(StructuredQName defaultMode) {
277 this.defaultMode = defaultMode;
278 }
279
280 /**
281 * Say whether it is required that modes be explicitly declared
282 *
283 * @param declared true if modes referenced within this package must be explicitly declared
284 */
285
286 public void setDeclaredModes(boolean declared) {
287 declaredModes = declared;
288 }
289
290 /**
291 * Ask whether it is required that modes be explicitly declared
292 *
293 * @return true if modes referenced within this package must be explicitly declared
294 */
295
296 public boolean isDeclaredModes() {
297 return declaredModes;
298 }
299
300 /**
301 * Get the whitespace stripping rules for this package
302 *
303 * @return the whitespace stripping rules (based on xsl:strip-space and xsl:preserve-space)
304 */
305
306 public SpaceStrippingRule getSpaceStrippingRule() {
307 return stripperRules;
308 }
309
310 /**
311 * Get the index of named character maps defined in this package
312 * @return the index of character maps
313 */
314
315 public CharacterMapIndex getCharacterMapIndex() {
316 return characterMapIndex;
317 }
318
319 /**
320 * Set the index of named character maps defined in this package
321 * @param characterMapIndex the index of named character maps
322 */
323
324 public void setCharacterMapIndex(CharacterMapIndex characterMapIndex) {
325 this.characterMapIndex = characterMapIndex;
326 }
327
328 /**
329 * Ask whether the package contains an xsl:result-document instruction
330 * @return true if the package contains an xsl:result-document instruction
331 */
332
333 public boolean isCreatesSecondaryResultDocuments() {
334 return createsSecondaryResultDocuments;
335 }
336
337 /**
338 * Say whether the package contains an xsl:result-document instruction
339 * @param createsSecondaryResultDocuments true if the package contains an xsl:result-document instruction
340 */
341
342 public void setCreatesSecondaryResultDocuments(boolean createsSecondaryResultDocuments) {
343 this.createsSecondaryResultDocuments = createsSecondaryResultDocuments;
344 }
345
346 /**
347 * Ask whether the package defines that type annotations should be stripped from input
348 * documents loaded from within this package
349 * @return true if documents loaded by this package should have any type annotations stripped.
350 */
351
352 public boolean isStripsTypeAnnotations() {
353 return stripsTypeAnnotations;
354 }
355
356 /**
357 * Say whether the package defines that type annotations should be stripped from input
358 * documents loaded from within this package
359 *
360 * @param stripsTypeAnnotations set to true if documents loaded by this package
361 * should have any type annotations stripped.
362 */
363
364
365 public void setStripsTypeAnnotations(boolean stripsTypeAnnotations) {
366 this.stripsTypeAnnotations = stripsTypeAnnotations;
367 }
368
369 /**
370 * Get the whitespace stripping rules for source documents loaded from within this package
371 * @return the whitespace stripping rules for this package
372 */
373
374 public SpaceStrippingRule getStripperRules() {
375 return stripperRules;
376 }
377
378 /**
379 * Set the whitespace stripping rules for source documents loaded from within this package
380 * @param stripperRules the whitespace stripping rules for this package
381 */
382
383 public void setStripperRules(SpaceStrippingRule stripperRules) {
384 this.stripperRules = stripperRules;
385 }
386
387 /**
388 * Set the default (unnamed) serialization properties to be used for documents output
389 * using xsl:result-document instructions within this package
390 * @param props the default serialization properties for this package
391 */
392
393 public void setDefaultOutputProperties(Properties props) {
394 defaultOutputProperties = props;
395 }
396
397 /**
398 * Define a named set serialization properties to be used for documents output
399 * using xsl:result-document instructions within this package
400 * @param name the name of the serialization property set
401 * @param props the serialization properties
402 */
403
404 public void setNamedOutputProperties(StructuredQName name, Properties props) {
405 namedOutputProperties.put(name, props);
406 }
407
408 /**
409 * Get a set of named output properties
410 * @param name the output declaration name
411 * @return the corresponding properties; or null if the name is unknown
412 */
413
414 public Properties getNamedOutputProperties(StructuredQName name) {
415 return namedOutputProperties.get(name);
416 }
417
418 /**
419 * Get the set of namespaces of schema declarations imported into this package
420 * @return the set of imported namespaces
421 */
422
423 public Set<String> getSchemaNamespaces() {
424 return schemaIndex;
425 }
426
427 /**
428 * Set the required context item type. Used when there is an xsl:global-context-item child element
429 * @param requirement details of the requirement for the global context item
430 */
431
432 public void setContextItemRequirements(GlobalContextRequirement requirement) throws XPathException {
433 if (containsGlobalContextItemDeclaration) {
434 // the new requirements must be consistent with the existing requirements
435 if ((!requirement.isAbsentFocus() && globalContextRequirement.isAbsentFocus()) ||
436 (requirement.isMayBeOmitted() && !globalContextRequirement.isMayBeOmitted())) {
437 throw new XPathException(
438 "The package contains two xsl:global-context-item declarations with conflicting @use attributes", "XTSE3087");
439 }
440 TypeHierarchy th = getConfiguration().getTypeHierarchy();
441 if (th.relationship(requirement.getRequiredItemType(), globalContextRequirement.getRequiredItemType()) != TypeHierarchy.SAME_TYPE) {
442 throw new XPathException("The package contains two xsl:global-context-item declarations with conflicting item types", "XTSE3087");
443 }
444 }
445 containsGlobalContextItemDeclaration = true;
446 globalContextRequirement = requirement;
447 }
448
449 /**
450 * Get the required context item type and other details of the global context item.
451 * Used when there is an xsl:global-context-item child element
452 * @return details of the requirement for the global context item
453 */
454
455 public GlobalContextRequirement getContextItemRequirements() {
456 return globalContextRequirement;
457 }
458
459 /**
460 * Say whether there is an xsl:strip-space declaration in the stylesheet package
461 *
462 * @param strips true if an xsl:strip-space declaration has been found
463 */
464
465 public void setStripsWhitespace(boolean strips) {
466 this.stripsWhitespace = strips;
467 }
468
469 /**
470 * Ask whether there is an xsl:strip-space declaration in the stylesheet package
471 *
472 * @return true if an xsl:strip-space declaration has been found
473 */
474
475 public boolean isStripsWhitespace() {
476 return this.stripsWhitespace;
477 }
478
479 /**
480 * Register a callback action to be performed during the completion phase of building the package
481 *
482 * @param action the callback action
483 */
484
485 public void addCompletionAction(Action action) {
486 completionActions.add(action);
487 }
488
489 /**
490 * Perform all registered completion actions for the package
491 * @throws XPathException if any of these completion actions fails
492 */
493
494 protected void complete() throws XPathException {
495 // Perform the completion actions
496 for (Action a : completionActions) {
497 a.doAction();
498 }
499 allocateBinderySlots();
500
501 }
502
503 /**
504 * Allocate slots to global variables. Slot numbers are unique within a package
505 */
506
507 public void allocateBinderySlots() {
508 SlotManager slotManager = getConfiguration().makeSlotManager();
509 for (Component c : componentIndex.values()) {
510 registerGlobalVariable(c, slotManager);
511 }
512 for (Component c : hiddenComponents) {
513 registerGlobalVariable(c, slotManager);
514 }
515 setGlobalSlotManager(slotManager);
516 }
517
518 /**
519 * Register a global variable declared within this package, allocating it a slot
520 * number within the Bindery
521 * @param c the component representing a global variable; it may also be another
522 * kind of component, but in this case it is ignored
523 * @param slotManager the SlotManager defining the allocation of variables to
524 * slots in the Bindery
525 */
526
527 private void registerGlobalVariable(Component c, SlotManager slotManager) {
528 if (c.getActor() instanceof GlobalVariable) {
529 GlobalVariable var = (GlobalVariable) c.getActor();
530 int slot = slotManager.allocateSlotNumber(var.getVariableQName());
531 var.setPackageData(this);
532 var.setBinderySlotNumber(slot);
533 if (c.getVisibility() != Visibility.HIDDEN) {
534 addGlobalVariable(var);
535 }
536 }
537 }
538
539 /**
540 * Add a component to the package
541 * @param component the component to be added
542 */
543
544 public void addComponent(Component component) {
545 SymbolicName name = component.getActor().getSymbolicName();
546 componentIndex.put(name, component);
547 if (component.getVisibility() == Visibility.ABSTRACT && component.getContainingPackage() == this) {
548 abstractComponents.put(component.getActor().getSymbolicName(), component);
549 }
550 }
551
552 @Override
553 public void addGlobalVariable(GlobalVariable variable) {
554 super.addGlobalVariable(variable);
555 SymbolicName name = variable.getSymbolicName();
556 if (componentIndex.get(name) == null) {
557 Component comp = variable.getDeclaringComponent();
558 if (comp == null) {
559 comp = variable.makeDeclaringComponent(PRIVATE, this);
560 }
561 addComponent(comp);
562 }
563 }
564
565 /**
566 * Get the maximum arity of functions in this package
567 * @return the maximum arity
568 */
569
570 public int getMaxFunctionArity() {
571 if (maxFunctionArity == -1) {
572 for (Component c : componentIndex.values()) {
573 if (c.getActor() instanceof UserFunction) {
574 if (((UserFunction) c.getActor()).getArity() > maxFunctionArity) {
575 maxFunctionArity = ((UserFunction) c.getActor()).getArity();
576 }
577 }
578 }
579 }
580 return maxFunctionArity;
581 }
582
583 /**
584 * Get the component within this package having a given symbolic name
585 *
586 * @param name the symbolic name of the required component
587 * @return the requested component, or null if it does not exist in the package
588 */
589
590 public Component getComponent(SymbolicName name) {
591 return componentIndex.get(name);
592 }
593
594 // public Component getHiddenComponent(SymbolicName name) {
595 // return hiddenComponents.get(name);
596 // }
597
598 public void addHiddenComponent(Component component) {
599 hiddenComponents.add(component);
600 }
601
602 /**
603 * If this component overrides a component named N, get the component that N overrides (that
604 * is, the component identified by xsl:original appearing within the overriding declaration of N)
605 * @param name the name N
606 * @return if there is an overriding declaration of N, then the original declaration of N from the
607 * used package; otherwise null
608 */
609
610 public Component getOverriddenComponent(SymbolicName name) {
611 return overriddenComponents.get(name);
612 }
613
614 public void addOverriddenComponent(Component comp) {
615 overriddenComponents.put(comp.getActor().getSymbolicName(), comp);
616 }
617
618 /**
619 * Add modified copies of components from a package that is referenced from this one in an xsl:use-package declaration
620 *
621 * @param usedPackage the used package
622 * @param acceptors abstraction of a list of xsl:accept declarations, which can modify the visibility of accepted components
623 * @param overrides the set of names of components from the used package that are overridden in the using package
624 * @throws XPathException if duplicate components are found
625 */
626
627 public void addComponentsFromUsedPackage(StylesheetPackage usedPackage,
628 List<XSLAccept> acceptors,
629 final Set<SymbolicName> overrides) throws XPathException {
630 usedPackages.add(usedPackage);
631
632 trace("=== Adding components from " + usedPackage.getPackageName() + " to " + getPackageName() + " ===");
633
634 // Create copies of the components in the used package, with suitably adjusted visibility
635
636 // Create a mapping from components in the used package to their corresponding components
637 // in the using package, so that we can re-bind the component bindings
638
639 final Map<Component, Component> correspondence = new HashMap<>();
640
641 for (Map.Entry<SymbolicName, Component> namedComponentEntry : usedPackage.componentIndex.entrySet()) {
642 SymbolicName name = namedComponentEntry.getKey();
643 Component oldC = namedComponentEntry.getValue();
644
645 Visibility oldV = oldC.getVisibility();
646
647 Visibility newV = null;
648
649 if (overrides.contains(name) && !(oldC.getActor() instanceof Mode)) {
650 newV = Visibility.HIDDEN;
651 } else {
652 Visibility acceptedVisibility = explicitAcceptedVisibility(name, acceptors);
653 if (acceptedVisibility != null) {
654 if (!XSLAccept.isCompatible(oldV, acceptedVisibility)) {
655 throw new XPathException("Cannot accept a " + oldV.show() +
656 " component (" + name + ") from package " + usedPackage.getPackageName()
657 + " with visibility " + acceptedVisibility.show(), "XTSE3040");
658 }
659 newV = acceptedVisibility;
660 } else {
661 acceptedVisibility = wildcardAcceptedVisibility(name, acceptors);
662 if (acceptedVisibility != null) {
663 if (XSLAccept.isCompatible(oldV, acceptedVisibility)) {
664 newV = acceptedVisibility;
665 }
666 }
667 }
668
669 if (newV == null) {
670 if (oldV == Visibility.PUBLIC || oldV == Visibility.FINAL) {
671 newV = Visibility.PRIVATE;
672 } else {
673 newV = Visibility.HIDDEN;
674 }
675 }
676 }
677
678 trace(oldC.getActor().getSymbolicName() + " (" + oldV.show() + ") becomes " + newV.show());
679
680 final Component newC = Component.makeComponent(oldC.getActor(), newV, VisibilityProvenance.DERIVED, this, oldC.getDeclaringPackage());
681 correspondence.put(oldC, newC);
682 newC.setBaseComponent(oldC);
683
684 if (overrides.contains(name)) {
685 // Note: overrides is all the overrides, not only those for this xsl:use-package;
686 // but we have already checked that xsl:override declarations match something in the
687 // right package.
688 overriddenComponents.put(name, newC);
689 if (newV != Visibility.ABSTRACT) {
690 abstractComponents.remove(name);
691 }
692 }
693 if (newC.getVisibility() == Visibility.HIDDEN) {
694 hiddenComponents.add(newC);
695 } else if (componentIndex.get(name) != null) {
696 if (!(oldC.getActor() instanceof Mode)) {
697 throw new XPathException("Duplicate " + namedComponentEntry.getKey(), "XTSE3050", oldC.getActor());
698 }
699 } else {
700 componentIndex.put(name, newC);
701 if (oldC.getActor() instanceof Mode && (oldV == Visibility.PUBLIC || oldV == Visibility.FINAL) ) {
702 Mode existing = getRuleManager().obtainMode(name.getComponentName(), false);
703 if (existing != null) {
704 throw new XPathException("Duplicate " + namedComponentEntry.getKey(), "XTSE3050", oldC.getActor());
705 } else {
706 //getRuleManager().registerMode((Mode)oldC.getCode());
707 }
708 }
709 }
710
711 if (newC.getActor() instanceof Mode && overrides.contains(name)) {
712 addCompletionAction(() -> {
713 trace("Doing mode completion for " + newC.getActor().getSymbolicName());
714 List<ComponentBinding> oldBindings = newC.getBaseComponent().getComponentBindings();
715 List<ComponentBinding> newBindings = newC.getComponentBindings();
716 for (int i=0; i<oldBindings.size(); i++) {
717 SymbolicName name12 = oldBindings.get(i).getSymbolicName();
718 Component target;
719 if (overrides.contains(name12)) {
720 // if there is an override in this package, we bind to it
721 target = getComponent(name12);
722 if (target == null) {
723 throw new AssertionError("We know there's an override for " + name12 + ", but we can't find it");
724 }
725 } else {
726 // otherwise we bind to the component in this package that corresponds to the component in the used package
727 target = correspondence.get(oldBindings.get(i).getTarget());
728 if (target == null) {
729 throw new AssertionError("Saxon can't find the new component corresponding to " + name12);
730 }
731 }
732 ComponentBinding newBinding = new ComponentBinding(name12, target);
733 newBindings.set(i, newBinding);
734 }
735
736 });
737 } else {
738 addCompletionAction(() -> {
739 trace("Doing normal completion for " + newC.getActor().getSymbolicName());
740 List<ComponentBinding> oldBindings = newC.getBaseComponent().getComponentBindings();
741 List<ComponentBinding> newBindings = new ArrayList<>(oldBindings.size());
742 makeNewComponentBindings(overrides, correspondence, oldBindings, newBindings);
743 newC.setComponentBindings(newBindings);
744 });
745 }
746
747 }
748
749 for (Component oldC : usedPackage.hiddenComponents) {
750
751 trace(oldC.getActor().getSymbolicName() + " (HIDDEN, declared in " + oldC.getDeclaringPackage().getPackageName() + ") becomes HIDDEN");
752
753 final Component newC = Component.makeComponent(oldC.getActor(), Visibility.HIDDEN, VisibilityProvenance.DERIVED, this, oldC.getDeclaringPackage());
754 correspondence.put(oldC, newC);
755 newC.setBaseComponent(oldC);
756
757 hiddenComponents.add(newC);
758
759 addCompletionAction(() -> {
760 List<ComponentBinding> oldBindings = newC.getBaseComponent().getComponentBindings();
761 List<ComponentBinding> newBindings = new ArrayList<>(oldBindings.size());
762 makeNewComponentBindings(overrides, correspondence, oldBindings, newBindings);
763 newC.setComponentBindings(newBindings);
764 });
765
766 }
767
768 if (usedPackage.isCreatesSecondaryResultDocuments()) {
769 setCreatesSecondaryResultDocuments(true);
770 }
771 }
772
773 private void makeNewComponentBindings(Set<SymbolicName> overrides, Map<Component, Component> correspondence, List<ComponentBinding> oldBindings, List<ComponentBinding> newBindings) {
774 for (ComponentBinding oldBinding : oldBindings) {
775 SymbolicName name = oldBinding.getSymbolicName();
776 Component target;
777 if (overrides.contains(name)) {
778 // if there is an override in this package, we bind to it
779 target = getComponent(name);
780 if (target == null) {
781 throw new AssertionError("We know there's an override for " + name + ", but we can't find it");
782 }
783 } else {
784 // otherwise we bind to the component in this package that corresponds to the component in the used package
785 target = correspondence.get(oldBinding.getTarget());
786 if (target == null) {
787 throw new AssertionError("Saxon can't find the new component corresponding to " + name);
788 }
789 }
790 ComponentBinding newBinding = new ComponentBinding(name, target);
791 newBindings.add(newBinding);
792 }
793 }
794
795 private void trace(String message) {
796 if (TRACING) {
797 System.err.println(message);
798 }
799 }
800
801 private Visibility explicitAcceptedVisibility(SymbolicName name, List<XSLAccept> acceptors) throws XPathException {
802 for (XSLAccept acceptor : acceptors) {
803 for (ComponentTest test : acceptor.getExplicitComponentTests()) {
804 if (test.matches(name)) {
805 return acceptor.getVisibility();
806 }
807 }
808 }
809 return null;
810 }
811
812 private Visibility wildcardAcceptedVisibility(SymbolicName name, List<XSLAccept> acceptors) throws XPathException {
813 // Note: last one wins
814 Visibility vis = null;
815 for (XSLAccept acceptor : acceptors) {
816 for (ComponentTest test : acceptor.getWildcardComponentTests()) {
817 if (((NodeTest) test.getQNameTest()).getDefaultPriority() == -0.25 && test.matches(name)) {
818 vis = acceptor.getVisibility();
819 }
820 }
821 }
822 if (vis != null) {
823 return vis;
824 }
825 for (XSLAccept acceptor : acceptors) {
826 for (ComponentTest test : acceptor.getWildcardComponentTests()) {
827 if (test.matches(name)) {
828 vis = acceptor.getVisibility();
829 }
830 }
831 }
832 return vis;
833 }
834
835
836 /**
837 * Create the function library containing stylesheet functions declared in this package
838 */
839
840 public void createFunctionLibrary() {
841
842 String target = getTargetEdition();
843 FunctionLibraryList functionLibrary = new FunctionLibraryList();
844 boolean includeHOF = !("HE".equals(target) || "JS".equals(target));
845 functionLibrary.addFunctionLibrary(includeHOF ? config.getXSLT30FunctionSet() : new Configuration().getXSLT30FunctionSet());
846 functionLibrary.addFunctionLibrary(new StylesheetFunctionLibrary(this, true));
847 functionLibrary.addFunctionLibrary(config.getBuiltInExtensionLibraryList());
848 functionLibrary.addFunctionLibrary(new ConstructorFunctionLibrary(config));
849 if ("JS".equals(target) || "JS2".equals(target)) {
850 addIxslFunctionLibrary(functionLibrary);
851 }
852
853 queryFunctions = new XQueryFunctionLibrary(config);
854 functionLibrary.addFunctionLibrary(queryFunctions);
855 functionLibrary.addFunctionLibrary(config.getIntegratedFunctionLibrary());
856 config.addExtensionBinders(functionLibrary);
857 functionLibrary.addFunctionLibrary(new StylesheetFunctionLibrary(this, false));
858 this.functionLibrary = functionLibrary;
859 }
860
861 protected void addIxslFunctionLibrary(FunctionLibraryList functionLibrary) {}
862
863 /**
864 * Get the function library.
865 *
866 * @return the function library
867 */
868
869 public FunctionLibraryList getFunctionLibrary() {
870 return functionLibrary;
871 }
872
873 /**
874 * Get the library of functions imported from XQuery
875 * @return the XQuery function library
876 */
877
878 public XQueryFunctionLibrary getXQueryFunctionLibrary() {
879 return queryFunctions;
880 }
881
882
883 /**
884 * Set details of functions available for calling anywhere in this package. This is the
885 * function library used for resolving run-time references to functions, for example
886 * from xsl:evaluate, function-available(), or function-lookup().
887 * @param overriding library of stylesheet functions declared with override=yes
888 * @param underriding library of stylesheet functions declared with override=no
889 */
890
891
892 public void setFunctionLibraryDetails(FunctionLibraryList library,
893 ExecutableFunctionLibrary overriding,
894 ExecutableFunctionLibrary underriding) {
895 if (library != null) {
896 this.functionLibrary = library;
897 }
898 this.overriding = overriding;
899 this.underriding = underriding;
900 }
901
902 /**
903 * Get the function with a given name and arity
904 *
905 * @param name the symbolic name of the function (QName plus arity)
906 * @return the requested function, or null if none can be found
907 */
908
909 protected UserFunction getFunction(SymbolicName.F name) {
910 if (name.getArity() == -1) {
911 // supports the single-argument function-available() function
912 int maximumArity = 20;
913 for (int a = 0; a < maximumArity; a++) {
914 SymbolicName.F sn = new SymbolicName.F(name.getComponentName(), a);
915 UserFunction uf = getFunction(sn);
916 if (uf != null) {
917 uf.incrementReferenceCount();
918 return uf;
919 }
920 }
921 return null;
922 } else {
923 Component component = getComponentIndex().get(name);
924 if (component != null) {
925 UserFunction uf = (UserFunction) component.getActor();
926 uf.incrementReferenceCount();
927 return uf;
928 } else {
929 return null;
930 }
931 }
932 }
933
934 /**
935 * Ask whether private functions for which there are no static references need to be
936 * retained
937 * @return true if such functions need to be retained, typically because the stylesheet
938 * package uses xsl:evaluate or fn:function-lookup
939 */
940
941 public boolean isRetainUnusedFunctions() {
942 return retainUnusedFunctions;
943 }
944
945 /**
946 * Say that private functions need to be retained, typically because the stylesheet
947 * package uses xsl:evaluate or fn:function-lookup
948 */
949
950 public void setRetainUnusedFunctions() {
951 this.retainUnusedFunctions = true;
952 }
953
954 /**
955 * Copy information from this package to the PreparedStylesheet.
956 *
957 * @param pss the PreparedStylesheet to be updated
958 * @throws net.sf.saxon.trans.XPathException if the PreparedStylesheet cannot be updated
959 */
960
961 public void updatePreparedStylesheet(PreparedStylesheet pss) throws XPathException {
962
963 for (Map.Entry<SymbolicName, Component> entry : componentIndex.entrySet()) {
964 if (entry.getValue().getVisibility() == Visibility.ABSTRACT) {
965 abstractComponents.put(entry.getKey(), entry.getValue());
966 }
967 }
968
969 pss.setTopLevelPackage(this);
970 if (isSchemaAware() || !schemaIndex.isEmpty()) {
971 pss.setSchemaAware(true);
972 }
973 pss.setHostLanguage(Configuration.XSLT);
974
975 //pss.setStylesheetFunctionLibrary(stylesheetFunctionLibrary);
976
977 FunctionLibraryList libraryList = new FunctionLibraryList();
978 for (FunctionLibrary lib : functionLibrary.getLibraryList()) {
979 if (lib instanceof StylesheetFunctionLibrary) {
980 if (((StylesheetFunctionLibrary) lib).isOverrideExtensionFunction()) {
981 libraryList.addFunctionLibrary(overriding);
982 //pss.getStylesheetFunctions().addFunctionLibrary(overriding);
983 } else {
984 libraryList.addFunctionLibrary(underriding);
985 //pss.getStylesheetFunctions().addFunctionLibrary(underriding);
986 }
987 } else {
988 libraryList.addFunctionLibrary(lib);
989 }
990 }
991 pss.setFunctionLibrary(libraryList);
992
993 if (!pss.createsSecondaryResult()) {
994 pss.setCreatesSecondaryResult(mayCreateSecondaryResultDocuments());
995 }
996 pss.setDefaultOutputProperties(defaultOutputProperties);
997 for (Map.Entry<StructuredQName, Properties> entry : namedOutputProperties.entrySet()) {
998 pss.setOutputProperties(entry.getKey(), entry.getValue());
999 }
1000
1001 // Build the index of named character maps
1002
1003 if (characterMapIndex != null) {
1004 for (CharacterMap cm : characterMapIndex) {
1005 pss.getCharacterMapIndex().putCharacterMap(cm.getName(), cm);
1006 }
1007 }
1008
1009 // Finish off the lists of template rules
1010
1011 ruleManager.checkConsistency();
1012 ruleManager.computeRankings();
1013 ruleManager.invertStreamableTemplates();
1014 if (config.obtainOptimizer().isOptionSet(OptimizerOptions.RULE_SET)) {
1015 ruleManager.optimizeRules();
1016 }
1017 pss.setRuleManager(ruleManager);
1018
1019
1020 // Add named templates to the prepared stylesheet
1021
1022 for (Component comp : componentIndex.values()) {
1023 if (comp.getActor() instanceof NamedTemplate) {
1024 NamedTemplate t = (NamedTemplate) comp.getActor();
1025 pss.putNamedTemplate(t.getTemplateName(), t);
1026 }
1027 }
1028
1029 // Share the component index with the prepared stylesheet
1030
1031 pss.setComponentIndex(componentIndex);
1032
1033 // Register stylesheet parameters
1034
1035 for (Component comp : componentIndex.values()) {
1036 if (comp.getActor() instanceof GlobalParam) {
1037 GlobalParam gv = (GlobalParam) comp.getActor();
1038 pss.registerGlobalParameter(gv);
1039 }
1040 }
1041
1042 // Set the requirements for the global context item
1043
1044 if (globalContextRequirement != null) {
1045 pss.setGlobalContextRequirement(globalContextRequirement);
1046 }
1047
1048 }
1049
1050 private boolean mayCreateSecondaryResultDocuments() {
1051 if (createsSecondaryResultDocuments) {
1052 return true;
1053 }
1054 for (StylesheetPackage p : usedPackages) {
1055 if (p.mayCreateSecondaryResultDocuments()) {
1056 return true;
1057 }
1058 }
1059 return false;
1060 }
1061
1062 public Map<SymbolicName, Component> getAbstractComponents() {
1063 return abstractComponents;
1064 }
1065
1066 /**
1067 * Output the abstract expression tree to the supplied destination.
1068 *
1069 * @param presenter the expression presenter used to display the structure
1070 */
1071
1072 public void export(ExpressionPresenter presenter) throws XPathException {
1073 throw new XPathException("Exporting a stylesheet requires Saxon-EE");
1074 }
1075
1076 public void checkForAbstractComponents() throws XPathException {
1077 for (Map.Entry<SymbolicName, Component> entry : componentIndex.entrySet()) {
1078 if (entry.getValue().getVisibility() == Visibility.ABSTRACT && entry.getValue().getContainingPackage() == this) {
1079 abstractComponents.put(entry.getKey(), entry.getValue());
1080 }
1081 }
1082 if (!abstractComponents.isEmpty()) {
1083 FastStringBuffer buff = new FastStringBuffer(256);
1084 int count = 0;
1085 for (SymbolicName name : abstractComponents.keySet()) {
1086 if (count++ > 0) {
1087 buff.append(", ");
1088 }
1089 buff.append(name.toString());
1090 if (buff.length() > 300) {
1091 buff.append(" ...");
1092 break;
1093 }
1094 }
1095 throw new XPathException(
1096 "The package is not executable, because it contains abstract components: " +
1097 buff, "XTSE3080");
1098 }
1099 }
1100
1101 /**
1102 * Ask whether a non-streamable construct has been found, forcing the entire stylesheet
1103 * to fall back to unstreamed processing
1104 *
1105 * @return true if the stylesheet must fall back to unstreamed processing
1106 */
1107
1108 public boolean isFallbackToNonStreaming() {
1109 return true;
1110 }
1111
1112 public void setFallbackToNonStreaming() {
1113 // No action except in EE
1114 }
1115
1116
1117 }
1118