Debian Codegraph @

net/sf/saxon/expr/instruct/Executable.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.instruct;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.PackageData;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.expr.parser.RoleDiagnostic;
14 import net.sf.saxon.functions.FunctionLibraryList;
15 import net.sf.saxon.om.Item;
16 import net.sf.saxon.om.StructuredQName;
17 import net.sf.saxon.query.QueryModule;
18 import net.sf.saxon.serialize.CharacterMapIndex;
19 import net.sf.saxon.serialize.SerializationProperties;
20 import net.sf.saxon.trace.ExpressionPresenter;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.ItemType;
23 import net.sf.saxon.type.TypeHierarchy;
24
25 import java.util.*;
26
27 /**
28 * A compiled stylesheet or a query in executable form.
29 * Note that the original stylesheet tree is not retained.
30 *
31 * In the case of XSLT 3.0, the Executable represents the collection of all packages making up
32 * a stylesheet; it is synthesized when the constituent packages are linked, and is not available
33 * during compilation (because each package is compiled separately). For XSLT the Executable
34 * will always be a {@link net.sf.saxon.PreparedStylesheet}, which is a subclass.
35 */
36
37 public class Executable {
38
39 // the Configuration options
40 /*@NotNull*/
41 private Configuration config;
42
43 // the top level package
44 private PackageData topLevelPackage;
45
46 // the set of packages making up this Executable
47 private List<PackageData> packages = new ArrayList<>();
48
49 // List of global variables and parameters
50 private List<GlobalVariable> compiledGlobalVariables;
51
52 // default output properties (for the unnamed output format)
53 private Properties defaultOutputProperties;
54
55 // table of character maps indexed by StructuredQName
56 private CharacterMapIndex characterMapIndex;
57
58 // hash table of query library modules
59 private HashMap<String, List<QueryModule>> queryLibraryModules;
60
61 // hash set of query module location hints that have been processed
62 private HashSet<String> queryLocationHintsProcessed;
63
64 // list of functions available in the static context
65 private FunctionLibraryList functionLibrary;
66
67 // flag to indicate whether the principal language is for example XSLT or XQuery
68 private int hostLanguage = Configuration.XSLT;
69
70 // a list of required parameters, identified by the structured QName of their names
71 private Map<StructuredQName, GlobalParam> globalParams = new HashMap<>();
72
73 // Hash table of named (and unnamed) output declarations. This is assembled only
74 // if there is a need for it: that is, if there is a call on xsl:result-document
75 // with a format attribute computed at run-time. The key is a StructuredQName object,
76 // the value is a Properties object
77 /*@Nullable*/ private HashMap<StructuredQName, Properties> outputDeclarations = null;
78
79 // a boolean, true if the executable represents a stylesheet that uses xsl:result-document
80 private boolean createsSecondaryResult = false;
81
82 // a boolean, indicates that the executable is schema-aware. This will true by default only
83 // if it statically imports a schema. If the executable is not schema-aware, then
84 // all input documents must be untyped.
85 protected boolean schemaAware = false;
86
87 // Requirements for the initial context item
88 private GlobalContextRequirement globalContextRequirement = null;
89
90 /**
91 * Create a new Executable (a collection of stylesheet modules and/or query modules)
92 *
93 * @param config the Saxon Configuration
94 */
95
96 public Executable(Configuration config) {
97 setConfiguration(config);
98 }
99
100 /**
101 * Set the configuration
102 *
103 * @param config the Configuration
104 */
105
106 public void setConfiguration(Configuration config) {
107 this.config = config;
108 }
109
110 /**
111 * Get the configuration
112 *
113 * @return the Configuration
114 */
115
116 /*@NotNull*/
117 public Configuration getConfiguration() {
118 return config;
119 }
120
121 public PackageData getTopLevelPackage() {
122 return topLevelPackage;
123 }
124
125 public void setTopLevelPackage(PackageData topLevelPackage) {
126 this.topLevelPackage = topLevelPackage;
127 }
128
129 /**
130 * Add information about a package
131 * @param data information about a package
132 */
133
134 public void addPackage(PackageData data) {
135 packages.add(data);
136 }
137
138 /**
139 * Get information about the packages in this executable
140 * @return a list of packages
141 */
142
143 public Iterable<PackageData> getPackages() {
144 return packages;
145 }
146
147 /**
148 * Set the host language
149 * @param language the host language, as a constant such as {@link Configuration#XSLT} or
150 * {@link Configuration#XQUERY}
151 *
152 */
153
154 public void setHostLanguage(int language) {
155 hostLanguage = language;
156 }
157
158 /**
159 * Get the host language
160 *
161 * @return a value identifying the host language: {@link Configuration#XQUERY} or {@link Configuration#XSLT}
162 * or {@link Configuration#JAVA_APPLICATION}
163 */
164
165 public int getHostLanguage() {
166 return hostLanguage;
167 }
168
169 /**
170 * Get the library containing all the in-scope functions in the static context
171 *
172 * @return the function libary
173 */
174
175 public FunctionLibraryList getFunctionLibrary() {
176 return functionLibrary;
177 }
178
179 /**
180 * Set the library containing all the in-scope functions in the static context
181 *
182 * @param functionLibrary the function libary
183 */
184
185 public void setFunctionLibrary(FunctionLibraryList functionLibrary) {
186 //System.err.println("***" + this + " setFunctionLib to " + functionLibrary);
187 this.functionLibrary = functionLibrary;
188 }
189
190 /**
191 * Set the index of named character maps
192 *
193 * @param cmi a hash table that maps the names of character maps
194 * to the HashMap objects representing the character maps
195 */
196
197 public void setCharacterMapIndex(CharacterMapIndex cmi) {
198 characterMapIndex = cmi;
199 }
200
201 /**
202 * Get the index of named character maps
203 *
204 * @return the hash table that maps the names of character maps
205 * to the IntHashMap objects representing the character maps
206 */
207
208 public CharacterMapIndex getCharacterMapIndex() {
209 if (characterMapIndex == null) {
210 characterMapIndex = new CharacterMapIndex();
211 }
212 return characterMapIndex;
213 }
214
215 /**
216 * Set the default output properties (the properties for the unnamed output format)
217 *
218 * @param properties the output properties to be used when the unnamed output format
219 * is selected
220 */
221
222 public void setDefaultOutputProperties(Properties properties) {
223 defaultOutputProperties = properties;
224 }
225
226 /**
227 * Get the primary output properties, that is, the output properties for the primary
228 * result destination. In XSLT these are the properties defined on unnamed {@code xsl:output}
229 * declarations in the top-level stylesheet package; in XQuery they are the properties
230 * defined using {@code "declare option output:x = 'value'"}.
231 *
232 * @return the properties for the unnamed output format
233 */
234
235 public SerializationProperties getPrimarySerializationProperties() {
236 if (defaultOutputProperties == null) {
237 defaultOutputProperties = new Properties();
238 }
239 Properties props = defaultOutputProperties;
240 return new SerializationProperties(props, getCharacterMapIndex());
241 }
242
243 /**
244 * Add a named output format
245 *
246 * @param qName the structured QName of the output format
247 * @param properties the properties of the output format
248 */
249
250 public void setOutputProperties(StructuredQName qName, Properties properties) {
251 if (outputDeclarations == null) {
252 outputDeclarations = new HashMap<>(5);
253 }
254 outputDeclarations.put(qName, properties);
255 }
256
257 /**
258 * Get the properties for xsl:output. The object returned will
259 * be a clone of the internal values, and thus it can be mutated
260 * without mutating the Executable object.
261 * <p>The returned properties object is a new, empty, Properties object that is
262 * backed by the live properties to supply default values for missing properties.
263 * This means that the property values must be read using the getProperty() method.
264 * Calling the get() method on the underlying Hashtable will return null.</p>
265 * <p>This method gets the output properties for the unnamed output
266 * format in the stylesheet.</p>
267 *
268 * @return A Properties object reflecting the output properties defined
269 * for the default (unnamed) output format in the stylesheet. It may
270 * be mutated and supplied to the setOutputProperties() method of the
271 * Transformer, without affecting other transformations that use the
272 * same stylesheet.
273 * @see javax.xml.transform.Transformer#setOutputProperties
274 */
275
276 public Properties getOutputProperties() {
277 return new Properties(defaultOutputProperties);
278 }
279
280 /**
281 * Get a named output format
282 *
283 * @param qName the name of the output format
284 * @return properties the properties of the output format. Return null if there are
285 * no output properties with the given name
286 */
287
288 /*@Nullable*/
289 public Properties getOutputProperties(StructuredQName qName) {
290 if (outputDeclarations == null) {
291 return null;
292 } else {
293 return outputDeclarations.get(qName);
294 }
295 }
296
297 /**
298 * Add an XQuery library module to the configuration. The Executable maintains a table indicating
299 * for each module namespace, the set of modules that have been loaded from that namespace. If a
300 * module import is encountered that specifies no location hint, all the known modules for that
301 * namespace are imported.
302 *
303 * @param module the library module to be added to this executable
304 */
305
306 public void addQueryLibraryModule(QueryModule module) {
307 if (queryLibraryModules == null) {
308 queryLibraryModules = new HashMap<>(5);
309 }
310 String uri = module.getModuleNamespace();
311 List<QueryModule> existing = queryLibraryModules.get(uri);
312 if (existing == null) {
313 existing = new ArrayList<>(5);
314 existing.add(module);
315 queryLibraryModules.put(uri, existing);
316 } else if (!existing.contains(module)){
317 existing.add(module);
318 }
319 }
320
321 /**
322 * Locate the known XQuery library modules for a given module namespace.
323 *
324 * @param namespace the module namespace URI
325 * @return a list of items each of which is the StaticQueryContext representing a module, or
326 * null if the module namespace is unknown
327 */
328
329 /*@Nullable*/
330 public List<QueryModule> getQueryLibraryModules(String namespace) {
331 if (queryLibraryModules == null) {
332 return null;
333 }
334 return queryLibraryModules.get(namespace);
335 }
336
337 /**
338 * Get the query library module with a given systemID
339 *
340 * @param systemId the SystemId of the required module
341 * @param topModule the top-level query module (usually a main module, except when
342 * importing library modules into XSLT)
343 * @return the module with that system id if found, otherwise null
344 */
345
346 /*@Nullable*/
347 public QueryModule getQueryModuleWithSystemId(/*@NotNull*/ String systemId, /*@NotNull*/ QueryModule topModule) {
348 if (systemId.equals(topModule.getSystemId())) {
349 return topModule;
350 }
351 Iterator miter = getQueryLibraryModules();
352 while (miter.hasNext()) {
353 QueryModule sqc = (QueryModule) miter.next();
354 String uri = sqc.getSystemId();
355 if (uri != null && uri.equals(systemId)) {
356 return sqc;
357 }
358 }
359 return null;
360 }
361
362 /**
363 * Get an iterator over all the query library modules (does not include the main module)
364 *
365 * @return an iterator whose returned items are instances of {@link QueryModule}
366 */
367
368 public Iterator getQueryLibraryModules() {
369 if (queryLibraryModules == null) {
370 return Collections.EMPTY_LIST.iterator();
371 } else {
372 List<QueryModule> modules = new ArrayList<>();
373 for (List<QueryModule> queryModules : queryLibraryModules.values()) {
374 modules.addAll(queryModules);
375 }
376 return modules.iterator();
377 }
378 }
379
380 /**
381 * Add a name to the list of query module location hints that have been
382 * processed during the construction of this executable
383 *
384 * @param uri the name to be added (the location URI as it appears in the
385 * "import module" declaration, expanded to an absolute URI by resolving against
386 * the base URI, but before passing to the Module Resolver)
387 */
388
389 public void addQueryLocationHintProcessed(String uri) {
390 if (queryLocationHintsProcessed == null) {
391 queryLocationHintsProcessed = new HashSet<>();
392 }
393 queryLocationHintsProcessed.add(uri);
394 }
395
396 /**
397 * Ask whether a query module location hint has already been processed
398 *
399 * @param uri the query location hint (the location URI as it appears in the
400 * "import module" declaration, expanded to an absolute URI by resolving against
401 * the base URI, but before passing to the Module Resolver)
402 * @return true if the location hint has already been processed
403 */
404
405 public boolean isQueryLocationHintProcessed(String uri) {
406 return queryLocationHintsProcessed != null && queryLocationHintsProcessed.contains(uri);
407 }
408
409
410 /**
411 * Fix up global variables and functions in all query modules. This is done right at the end, because
412 * recursive imports are permitted
413 *
414 * @param main the main query module
415 * @throws net.sf.saxon.trans.XPathException
416 * if an error occurs
417 */
418
419 public void fixupQueryModules(QueryModule main) throws XPathException {
420
421 // Bind any previously unbound variables (forwards references)
422
423 main.bindUnboundVariables();
424
425 if (queryLibraryModules != null) {
426 for (List<QueryModule> queryModules : queryLibraryModules.values()) {
427 for (QueryModule env : queryModules) {
428 env.bindUnboundVariables();
429 }
430 }
431 }
432
433 List<GlobalVariable> varDefinitions = main.fixupGlobalVariables(main.getGlobalStackFrameMap() /*, contextItemVar */);
434
435 main.bindUnboundFunctionCalls();
436
437 if (queryLibraryModules != null) {
438 for (List<QueryModule> queryModules : queryLibraryModules.values()) {
439 for (QueryModule env : queryModules) {
440 env.bindUnboundFunctionCalls();
441 }
442 }
443 }
444
445 // Note: the checks for circularities between variables and functions have to happen
446 // before functions are compiled and optimized, as the optimization can involve function
447 // inlining which eliminates the circularities (tests K-InternalVariablesWith-17, errata8-002)
448
449 main.checkForCircularities(varDefinitions, main.getGlobalFunctionLibrary());
450 main.fixupGlobalFunctions();
451
452 // if (checkForCycles) {
453 // Iterator miter = getQueryLibraryModules();
454 // while (miter.hasNext()) {
455 // QueryModule module = (QueryModule) miter.next();
456 // module.lookForModuleCycles(new Stack<QueryModule>(), 1);
457 // }
458 // }
459
460 main.typeCheckGlobalVariables(varDefinitions);
461 main.optimizeGlobalFunctions();
462 }
463
464 /**
465 * Explain (that is, output an expression tree) the global variables
466 *
467 * @param presenter the destination for the explanation of the global variables
468 */
469
470 public void explainGlobalVariables(ExpressionPresenter presenter) throws XPathException {
471 presenter.startElement("globalVariables");
472 for (PackageData pack : getPackages()) {
473 for (GlobalVariable var : pack.getGlobalVariableList()) {
474 var.export(presenter);
475 }
476 }
477 presenter.endElement();
478 }
479
480 /**
481 * Register a global parameter
482 *
483 * @param param the stylesheet parameter (XSLT) or external variable (XQuery) to be registered
484 */
485
486 public void registerGlobalParameter(GlobalParam param) {
487 globalParams.put(param.getVariableQName(), param);
488 }
489
490 /**
491 * Get all the registered global parameters
492 * @return a list of all the stylesheet parameters (XSLT) or external variables (XQuery)
493 */
494
495 public Map<StructuredQName, GlobalParam> getGlobalParameters() {
496 return globalParams;
497 }
498
499 /**
500 * Get the global parameter with a given name, if there is one
501 * @param name the parameter name
502 * @return the global parameter with this name, if it exists, or null otherwise
503 */
504
505 public GlobalParam getGlobalParameter(StructuredQName name) {
506 return globalParams.get(name);
507 }
508
509 /**
510 * Check the supplied parameters. Checks that all required parameters have been supplied, and that
511 * no parameters supplied at run-time are declared static in the stylesheet, or were supplied
512 * eagerly at compile-time.
513 *
514 * <p>Used in XSLT only.</p>
515 *
516 * @param params the set of parameters that have been supplied (null represents an empty set)
517 * @throws XPathException if there is a required parameter for which no value has been supplied
518 */
519
520 public void checkSuppliedParameters(GlobalParameterSet params) throws XPathException {
521
522 }
523
524
525 /**
526 * Set whether this executable represents a stylesheet that uses xsl:result-document
527 * to create secondary output documents
528 *
529 * @param flag true if the executable uses xsl:result-document
530 */
531
532 public void setCreatesSecondaryResult(boolean flag) {
533 createsSecondaryResult = flag;
534 }
535
536 /**
537 * Ask whether this executable represents a stylesheet that uses xsl:result-document
538 * to create secondary output documents
539 *
540 * @return true if the executable uses xsl:result-document
541 */
542
543 public boolean createsSecondaryResult() {
544 return createsSecondaryResult;
545 }
546
547 /**
548 * Set the accumulators declared on xsl:global-context-item
549 * @param requirement the requirements on the global context item
550 */
551
552 public void setGlobalContextRequirement(GlobalContextRequirement requirement) {
553 globalContextRequirement = requirement;
554 }
555
556 /**
557 * Get the constraints on the initial global context item
558 * @return the declared initial global context item requirements
559 */
560
561 public GlobalContextRequirement getGlobalContextRequirement() {
562 return globalContextRequirement;
563 }
564
565 /**
566 * Check that the supplied global context item meets all requirements, and perform any required
567 * conversions or defaulting
568 * @param contextItem the supplied context item
569 * @param context a context for evaluation (in which the context item will be absent)
570 * @return a new/converted context item, or null if the global context item is to be absent
571 * @throws XPathException if the supplied item does not meet requirements, for example if it is the
572 * wrong type.
573 */
574
575 public Item checkInitialContextItem(Item contextItem, XPathContext context) throws XPathException {
576 if (globalContextRequirement == null) {
577 return contextItem;
578 }
579 if (contextItem != null && globalContextRequirement.isAbsentFocus()) {
580 throw new XPathException("The global context item is required to be absent", "XPDY0002");
581 }
582 TypeHierarchy th = config.getTypeHierarchy();
583 if (contextItem == null) {
584 if (!globalContextRequirement.isMayBeOmitted()) {
585 // Bug 30173 allocates an error code
586 throw new XPathException("A global context item is required, but none has been supplied", "XTDE3086");
587 }
588 if (globalContextRequirement.getDefaultValue() != null) {
589 // XQuery only
590 try {
591 contextItem = globalContextRequirement.getDefaultValue().evaluateItem(context);
592 } catch (XPathException e) {
593 // XPDY0002 here means there is no context item, which means the default value
594 // of the context item depends on the context item: a circularity.
595 if ("XPDY0002".equals(e.getErrorCodeLocalPart())) {
596 if (e.getMessage().contains("last()") || e.getMessage().contains("position()")) {
597 // no action
598 } else {
599 e.setErrorCode("XQDY0054");
600 }
601 }
602 throw e;
603 }
604 if (contextItem == null) {
605 throw new XPathException("The context item cannot be initialized to an empty sequence", "XPTY0004");
606 }
607 for (ItemType type : globalContextRequirement.getRequiredItemTypes()) {
608 if (!type.matches(contextItem, th)) {
609 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.MISC, "defaulted global context item", 0);
610 String s = role.composeErrorMessage(type, contextItem, th);
611 throw new XPathException(s, "XPTY0004");
612 }
613 }
614 }
615 } else {
616 for (ItemType type : globalContextRequirement.getRequiredItemTypes()) {
617 if (!type.matches(contextItem, config.getTypeHierarchy())) {
618 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.MISC, "supplied global context item", 0);
619 String s = role.composeErrorMessage(type, contextItem, th);
620 throw new XPathException(s, getHostLanguage() == Configuration.XSLT ? "XTTE0590" : "XPTY0004");
621 }
622 }
623 }
624 return contextItem;
625 }
626
627 /**
628 * Set whether this executable is schema-aware. The initial value is false; it is set to true
629 * at compile time if the query or transformation imports a schema. If the value is false, then
630 * all documents used at run-time must be untyped
631 *
632 * @param aware true if the executable is schema-aware
633 * @throws IllegalArgumentException if schema-aware processing is requested in a Configuration
634 * that is not schema-aware
635 */
636
637 public void setSchemaAware(boolean aware) {
638 // if (aware) {
639 // config.checkLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION,
640 // "schema-aware processing", getTopLevelPackage().getLocalLicenseId());
641 // }
642 schemaAware = aware;
643 }
644
645 /**
646 * Ask whether this executable is schema-aware, that is, whether the query or transformation
647 * imports a schema.
648 *
649 * @return true if the executable is schema-aware, false if not.
650 */
651
652 public boolean isSchemaAware() {
653 return schemaAware;
654 }
655
656 }
657