Debian Codegraph @

net/sf/saxon/query/QueryModule.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.query;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.instruct.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.functions.FunctionLibrary;
15 import net.sf.saxon.functions.FunctionLibraryList;
16 import net.sf.saxon.functions.ResolveURI;
17 import net.sf.saxon.functions.registry.BuiltInFunctionSet;
18 import net.sf.saxon.functions.registry.ConstructorFunctionLibrary;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.lib.Validation;
21 import net.sf.saxon.om.NamespaceBinding;
22 import net.sf.saxon.om.NamespaceResolver;
23 import net.sf.saxon.om.QNameParser;
24 import net.sf.saxon.om.StructuredQName;
25 import net.sf.saxon.trace.ExpressionPresenter;
26 import net.sf.saxon.trace.TraceCodeInjector;
27 import net.sf.saxon.trans.DecimalFormatManager;
28 import net.sf.saxon.trans.KeyManager;
29 import net.sf.saxon.trans.XPathException;
30 import net.sf.saxon.type.AnyItemType;
31 import net.sf.saxon.type.ItemType;
32 import net.sf.saxon.type.SchemaType;
33
34 import java.net.URI;
35 import java.net.URISyntaxException;
36 import java.util.*;
37
38 /**
39 * This class represents a query module, and includes information about the static context of the query module.
40 * The class is intended for internal Saxon use. User settings that affect the static context are made in the
41 * StaticQueryContext object, and those settings are copied to each QueryModule when the query module is compiled.
42 */
43
44 public class QueryModule implements StaticContext {
45 private boolean isMainModule;
46 private final Configuration config;
47 private StaticQueryContext userQueryContext;
48 private final QueryModule topModule;
49 private URI locationURI;
50 private String baseURI;
51 private String moduleNamespace; // null only if isMainModule is false
52 private HashMap<String, String> explicitPrologNamespaces;
53 private Stack<ActiveNamespace> activeNamespaces;
54 private HashMap<StructuredQName, GlobalVariable> variables;
55 // global variables declared in this module
56 private HashMap<StructuredQName, GlobalVariable> libraryVariables;
57 // all global variables defined in library modules
58 // defined only on the top-level module
59 private HashMap<StructuredQName, UndeclaredVariable> undeclaredVariables;
60 private HashSet<String> importedSchemata; // The schema target namespaces imported into this module
61 private HashMap<String, HashSet<String>> loadedSchemata;
62 // For the top-level module only, all imported schemas for all modules,
63 // Key is the targetNamespace, value is the set of absolutized location URIs
64 private Executable executable;
65 private List<QueryModule> importers; // A list of QueryModule objects representing the modules that import this one,
66 // Null for the main module
67 // This is needed *only* to implement the rules banning cyclic imports
68 private FunctionLibraryList functionLibraryList;
69 private XQueryFunctionLibrary globalFunctionLibrary; // used only on a top-level module
70 private int localFunctionLibraryNr;
71 private int importedFunctionLibraryNr;
72 private int unboundFunctionLibraryNr;
73 private Set<String> importedModuleNamespaces;
74 private boolean inheritNamespaces = true;
75 private boolean preserveNamespaces = true;
76 private int constructionMode = Validation.PRESERVE;
77 private String defaultFunctionNamespace;
78 private String defaultElementNamespace;
79 private boolean preserveSpace = false;
80 private boolean defaultEmptyLeast = true;
81 private String defaultCollationName;
82 private int revalidationMode = Validation.SKIP;
83 private boolean isUpdating = false;
84 private ItemType requiredContextItemType = AnyItemType.getInstance(); // must be the same for all modules
85 private DecimalFormatManager decimalFormatManager = null; // used only in XQuery 3.0
86 private CodeInjector codeInjector;
87 private PackageData packageData;
88 private RetainedStaticContext moduleStaticContext = null;
89 private Location moduleLocation;
90 private OptimizerOptions optimizerOptions;
91
92 /**
93 * Create a QueryModule for a main module, copying the data that has been set up in a
94 * StaticQueryContext object
95 *
96 * @param sqc the StaticQueryContext object from which this module is initialized
97 * @throws XPathException if information supplied is invalid
98 */
99
100 public QueryModule(/*@NotNull*/ StaticQueryContext sqc) throws XPathException {
101 config = sqc.getConfiguration();
102 isMainModule = true;
103 topModule = this;
104 activeNamespaces = new Stack<>();
105 baseURI = sqc.getBaseURI();
106 defaultCollationName = sqc.getDefaultCollationName();
107 try {
108 locationURI = baseURI == null ? null : new URI(baseURI);
109 } catch (URISyntaxException err) {
110 throw new XPathException("Invalid location URI: " + baseURI);
111 }
112 executable = sqc.makeExecutable();
113 importers = null;
114 init(sqc);
115
116 PackageData pd = new PackageData(config);
117 pd.setHostLanguage(Configuration.XQUERY);
118 pd.setSchemaAware(isSchemaAware());
119 packageData = pd;
120
121 for (Iterator<GlobalVariable> vars = sqc.iterateDeclaredGlobalVariables(); vars.hasNext(); ) {
122 GlobalVariable var = vars.next();
123 declareVariable(var);
124 pd.addGlobalVariable(var);
125 var.setPackageData(pd);
126 }
127
128
129 executable.setTopLevelPackage(pd);
130 executable.addPackage(pd);
131
132 if (sqc.getModuleLocation() == null) {
133 moduleLocation = new ExplicitLocation(sqc.getSystemId(), 1, -1);
134 } else {
135 moduleLocation = sqc.getModuleLocation();
136 }
137 optimizerOptions = sqc.getOptimizerOptions();
138 }
139
140 /**
141 * Create a QueryModule for a library module.
142 *
143 * @param config the Saxon configuration
144 * @param importer the module that imported this module. This may be null, in the case where
145 * the library module is being imported into an XSLT stylesheet
146 */
147
148 public QueryModule(Configuration config, /*@Nullable*/ QueryModule importer) {
149 this.config = config;
150 importers = null;
151 if (importer == null) {
152 topModule = this;
153 } else {
154 topModule = importer.topModule;
155 userQueryContext = importer.userQueryContext;
156 importers = new ArrayList<>(2);
157 importers.add(importer);
158 }
159 init(userQueryContext);
160 packageData = importer.getPackageData();
161 activeNamespaces = new Stack<>();
162 executable = null;
163 optimizerOptions = importer.optimizerOptions;
164 }
165
166 /**
167 * Initialize data from a user-supplied StaticQueryContext object
168 *
169 * @param sqc the user-supplied StaticQueryContext. Null if this is a library module imported
170 * into XSLT.
171 */
172
173 private void init(/*@Nullable*/ StaticQueryContext sqc) {
174 //reset();
175 userQueryContext = sqc;
176 variables = new HashMap<>(10);
177 undeclaredVariables = new HashMap<>(5);
178 if (isTopLevelModule()) {
179 libraryVariables = new HashMap<>(10);
180 }
181 importedSchemata = new HashSet<>(5);
182 //importedSchemata.add(NamespaceConstant.JSON);
183 importedModuleNamespaces = new HashSet<>(5);
184 moduleNamespace = null;
185 activeNamespaces = new Stack<>();
186
187 explicitPrologNamespaces = new HashMap<>(10);
188 if (sqc != null) {
189 //executable = sqc.getExecutable();
190 inheritNamespaces = sqc.isInheritNamespaces();
191 preserveNamespaces = sqc.isPreserveNamespaces();
192 preserveSpace = sqc.isPreserveBoundarySpace();
193 defaultEmptyLeast = sqc.isEmptyLeast();
194 defaultFunctionNamespace = sqc.getDefaultFunctionNamespace();
195 defaultElementNamespace = sqc.getDefaultElementNamespace();
196 defaultCollationName = sqc.getDefaultCollationName();
197 constructionMode = sqc.getConstructionMode();
198 if (constructionMode == Validation.PRESERVE && !sqc.isSchemaAware()) {
199 // if not schema-aware, generate untyped output by default
200 constructionMode = Validation.STRIP;
201 }
202 requiredContextItemType = sqc.getRequiredContextItemType();
203 isUpdating = sqc.isUpdatingEnabled();
204 codeInjector = sqc.getCodeInjector();
205 optimizerOptions = sqc.getOptimizerOptions();
206 }
207 initializeFunctionLibraries(sqc);
208 }
209
210 /**
211 * Supporting method to load an imported library module.
212 * Used also by saxon:import-query in XSLT.
213 * <p>This method is intended for internal use only.</p>
214 *
215 * @param baseURI The base URI and location URI of the module
216 * @param executable The Executable
217 * @param importer The importing query module (used to check for cycles). This is null
218 * when loading a query module from XSLT.
219 * @param query The text of the query, after decoding and normalizing line endings
220 * @param namespaceURI namespace of the query module to be loaded
221 * @return The StaticQueryContext representing the loaded query module
222 * @throws XPathException if an error occurs
223 */
224
225 /*@NotNull*/
226 public static QueryModule makeQueryModule(
227 String baseURI, /*@NotNull*/ Executable executable, /*@NotNull*/ QueryModule importer,
228 String query, String namespaceURI) throws XPathException {
229 Configuration config = executable.getConfiguration();
230 QueryModule module = new QueryModule(config, importer);
231 try {
232 module.setLocationURI(new URI(baseURI));
233 } catch (URISyntaxException e) {
234 throw new XPathException("Invalid location URI " + baseURI, e);
235 }
236 module.setBaseURI(baseURI);
237 module.setExecutable(executable);
238 module.setModuleNamespace(namespaceURI);
239
240 executable.addQueryLibraryModule(module);
241 XQueryParser qp = (XQueryParser) config.newExpressionParser(
242 "XQ", importer.isUpdating(), 31);
243 if (importer.getCodeInjector() != null) {
244 qp.setCodeInjector(importer.getCodeInjector());
245 } else if (config.isCompileWithTracing()) {
246 qp.setCodeInjector(new TraceCodeInjector());
247 }
248 QNameParser qnp = new QNameParser(module.getLiveNamespaceResolver());
249 qnp.setAcceptEQName(importer.getXPathVersion() >= 30);
250 qnp.setUnescaper(new XQueryParser.Unescaper(config.getValidCharacterChecker()));
251 qp.setQNameParser(qnp);
252
253 qp.parseLibraryModule(query, module);
254
255 String namespace = module.getModuleNamespace();
256 if (namespace == null) {
257 XPathException err = new XPathException("Imported module must be a library module");
258 err.setErrorCode("XQST0059");
259 err.setIsStaticError(true);
260 throw err;
261 }
262 if (!namespace.equals(namespaceURI)) {
263 XPathException err = new XPathException("Imported module's namespace does not match requested namespace");
264 err.setErrorCode("XQST0059");
265 err.setIsStaticError(true);
266 throw err;
267 }
268
269 return module;
270 }
271
272 /**
273 * Reset function libraries
274 *
275 * @param sqc The static query context set up by the caller
276 */
277
278 private void initializeFunctionLibraries(/*@Nullable*/ StaticQueryContext sqc) {
279 Configuration config = getConfiguration();
280 if (isTopLevelModule()) {
281 globalFunctionLibrary = new XQueryFunctionLibrary(config);
282 }
283
284 functionLibraryList = new FunctionLibraryList();
285 functionLibraryList.addFunctionLibrary(getBuiltInFunctionSet());
286 functionLibraryList.addFunctionLibrary(config.getBuiltInExtensionLibraryList());
287 functionLibraryList.addFunctionLibrary(new ConstructorFunctionLibrary(config));
288
289 localFunctionLibraryNr = functionLibraryList.addFunctionLibrary(
290 new XQueryFunctionLibrary(config));
291
292 importedFunctionLibraryNr = functionLibraryList.addFunctionLibrary(
293 new ImportedFunctionLibrary(this, getTopLevelModule().getGlobalFunctionLibrary()));
294
295 if (sqc != null && sqc.getExtensionFunctionLibrary() != null) {
296 functionLibraryList.addFunctionLibrary(sqc.getExtensionFunctionLibrary());
297 }
298
299 functionLibraryList.addFunctionLibrary(config.getIntegratedFunctionLibrary());
300 config.addExtensionBinders(functionLibraryList);
301
302 unboundFunctionLibraryNr = functionLibraryList.addFunctionLibrary(
303 new UnboundFunctionLibrary());
304 }
305
306 public BuiltInFunctionSet getBuiltInFunctionSet() {
307 if (isUpdating()) {
308 return config.getXQueryUpdateFunctionSet();
309 } else {
310 return config.getXPath31FunctionSet();
311 }
312 }
313
314 /**
315 * Get the Saxon Configuration
316 *
317 * @return the Saxon Configuration
318 */
319
320 public Configuration getConfiguration() {
321 return config;
322 }
323
324 /**
325 * Get package data. This is a small data object containing information about the unit
326 * of compilation, which in the case of XQuery is a query module
327 *
328 * @return data about this query module
329 */
330
331 public PackageData getPackageData() {
332 return packageData;
333 }
334
335 /**
336 * Set the package data. This method is used when we want the QueryModule to share the same
337 * package data as another module: notably when fn:load-query-module creates a "dummy" main
338 * module to go with the dynamic library module
339 * @param packageData the package information
340 */
341
342 public void setPackageData(PackageData packageData) {
343 this.packageData = packageData;
344 }
345
346 /**
347 * Test whether this is a "top-level" module. This is true for a main module and also for a
348 * module directly imported into an XSLT stylesheet. It may also be true in future for independently-compiled
349 * modules
350 *
351 * @return true if this is top-level module
352 */
353
354 public boolean isTopLevelModule() {
355 return this == topModule;
356 }
357
358 /**
359 * Set whether this is a "Main" module, in the sense of the XQuery language specification
360 *
361 * @param main true if this is a main module, false if it is a library module
362 */
363
364 public void setIsMainModule(boolean main) {
365 isMainModule = main;
366 }
367
368 /**
369 * Ask whether this is a "main" module, in the sense of the XQuery language specification
370 *
371 * @return true if this is a main module, false if it is a library model
372 */
373
374 public boolean isMainModule() {
375 return isMainModule;
376 }
377
378 /**
379 * Check whether this module is allowed to import a module with namespace N. Note that before
380 * calling this we have already handled the exception case where a module imports another in the same
381 * namespace (this is the only case where cycles are allowed, though as a late change to the spec they
382 * are no longer useful, since they cannot depend on each other cyclically)
383 *
384 * @param namespace the namespace to be tested
385 * @return true if the import is permitted
386 */
387
388 public boolean mayImportModule(/*@NotNull*/ String namespace) {
389 if (namespace.equals(moduleNamespace)) {
390 return false;
391 }
392 if (importers == null) {
393 return true;
394 }
395 for (QueryModule importer : importers) {
396 if (!importer.mayImportModule(namespace)) {
397 return false;
398 }
399 }
400 return true;
401 }
402
403 /**
404 * Ask whether expressions compiled under this static context are schema-aware.
405 * They must be schema-aware if the expression is to handle typed (validated) nodes
406 *
407 * @return true if expressions are schema-aware
408 */
409 public boolean isSchemaAware() {
410 return executable.isSchemaAware();
411 }
412
413 /**
414 * Get the optimization options in use. By default these are taken from the
415 * {@link Configuration}
416 *
417 * @return the optimization options in use
418 */
419
420 @Override
421 public OptimizerOptions getOptimizerOptions() {
422 return optimizerOptions;
423 }
424
425 /**
426 * Construct a RetainedStaticContext, which extracts information from this StaticContext
427 * to provide the subset of static context information that is potentially needed
428 * during expression evaluation
429 *
430 * @return a RetainedStaticContext object: either a newly created one, or one that is
431 * reused from a previous invocation.
432 */
433 public RetainedStaticContext makeRetainedStaticContext() {
434 // The only part of the RetainedStaticContext that can change as the query module is parsed is the
435 // "activeNamespaces", that is, namespaces declared on direct element constructors. If this is empty,
436 // we can reuse the top-level static context on each request.
437 if (activeNamespaces.empty()) {
438 if (moduleStaticContext == null) {
439 moduleStaticContext = new RetainedStaticContext(this);
440 }
441 return moduleStaticContext;
442 } else {
443 return new RetainedStaticContext(this);
444 }
445 }
446
447
448 /**
449 * Set the namespace inheritance mode
450 *
451 * @param inherit true if namespaces are inherited, false if not
452 * @since 8.4
453 */
454
455 public void setInheritNamespaces(boolean inherit) {
456 inheritNamespaces = inherit;
457 }
458
459 /**
460 * Get the namespace inheritance mode
461 *
462 * @return true if namespaces are inherited, false if not
463 * @since 8.4
464 */
465
466 public boolean isInheritNamespaces() {
467 return inheritNamespaces;
468 }
469
470 /**
471 * Set the namespace copy mode
472 *
473 * @param inherit true if namespaces are preserved, false if not
474 */
475
476 public void setPreserveNamespaces(boolean inherit) {
477 preserveNamespaces = inherit;
478 }
479
480 /**
481 * Get the namespace copy mode
482 *
483 * @return true if namespaces are preserved, false if not
484 */
485
486 public boolean isPreserveNamespaces() {
487 return preserveNamespaces;
488 }
489
490 /**
491 * Set the construction mode for this module
492 *
493 * @param mode one of {@link net.sf.saxon.lib.Validation#STRIP}, {@link net.sf.saxon.lib.Validation#PRESERVE}
494 */
495
496 public void setConstructionMode(int mode) {
497 constructionMode = mode;
498 }
499
500 /**
501 * Get the current construction mode
502 *
503 * @return one of {@link net.sf.saxon.lib.Validation#STRIP}, {@link net.sf.saxon.lib.Validation#PRESERVE}
504 */
505
506 public int getConstructionMode() {
507 return constructionMode;
508 }
509
510 /**
511 * Set the policy for preserving boundary space
512 *
513 * @param preserve true if boundary space is to be preserved, false if it is to be stripped
514 */
515
516 public void setPreserveBoundarySpace(boolean preserve) {
517 preserveSpace = preserve;
518 }
519
520 /**
521 * Ask whether the policy for boundary space is "preserve" or "strip"
522 *
523 * @return true if the policy is to preserve boundary space, false if it is to strip it
524 */
525
526 public boolean isPreserveBoundarySpace() {
527 return preserveSpace;
528 }
529
530 /**
531 * Set the option for where an empty sequence appears in the collation order, if not otherwise
532 * specified in the "order by" clause
533 *
534 * @param least true if the empty sequence is considered less than any other value (the default),
535 * false if it is considered greater than any other value
536 */
537
538 public void setEmptyLeast(boolean least) {
539 defaultEmptyLeast = least;
540 }
541
542 /**
543 * Ask what is the option for where an empty sequence appears in the collation order, if not otherwise
544 * specified in the "order by" clause
545 *
546 * @return true if the empty sequence is considered less than any other value (the default),
547 * false if it is considered greater than any other value
548 */
549
550 public boolean isEmptyLeast() {
551 return defaultEmptyLeast;
552 }
553
554
555 /**
556 * Get the function library object that holds details of global functions
557 *
558 * @return the library of global functions
559 */
560
561 public XQueryFunctionLibrary getGlobalFunctionLibrary() {
562 return globalFunctionLibrary;
563 }
564
565 /**
566 * Get the function library object that holds details of imported functions
567 *
568 * @return the library of imported functions
569 */
570
571 /*@NotNull*/
572 public ImportedFunctionLibrary getImportedFunctionLibrary() {
573 return (ImportedFunctionLibrary) functionLibraryList.get(importedFunctionLibraryNr);
574 }
575
576 /**
577 * Register that this module imports a particular module namespace
578 * <p>This method is intended for internal use.</p>
579 *
580 * @param uri the URI of the imported namespace.
581 */
582
583 public void addImportedNamespace(String uri) {
584 if (importedModuleNamespaces == null) {
585 importedModuleNamespaces = new HashSet<>(5);
586 }
587 importedModuleNamespaces.add(uri);
588 getImportedFunctionLibrary().addImportedNamespace(uri);
589 }
590
591 /**
592 * Ask whether this module directly imports a particular namespace
593 * <p>This method is intended for internal use.</p>
594 *
595 * @param uri the URI of the possibly-imported namespace.
596 * @return true if the schema for the namespace has been imported
597 */
598
599 public boolean importsNamespace(String uri) {
600 return importedModuleNamespaces != null &&
601 importedModuleNamespaces.contains(uri);
602 }
603
604 /**
605 * Get the QueryModule for the top-level module. This will normally be a main module,
606 * but in the case of saxon:import-query it will be the library module that is imported into
607 * the stylesheet
608 *
609 * @return the StaticQueryContext object associated with the top level module
610 */
611
612 public QueryModule getTopLevelModule() {
613 return topModule;
614 }
615
616 /**
617 * Get the Executable, an object representing the compiled query and its environment.
618 * <p>This method is intended for internal use only.</p>
619 *
620 * @return the Executable
621 */
622
623 /*@Nullable*/
624 public Executable getExecutable() {
625 return executable;
626 }
627
628 /**
629 * Set the executable.
630 * <p>This method is intended for internal use only.</p>
631 *
632 * @param executable the Executable
633 */
634
635 public void setExecutable(Executable executable) {
636 this.executable = executable;
637 // if (!executable.isSchemaAware()) {
638 // constructionMode = Validation.STRIP;
639 // }
640 }
641
642 /**
643 * Get the StaticQueryContext object containing options set up by the user
644 *
645 * @return the user-created StaticQueryContext object
646 */
647
648 /*@Nullable*/
649 public StaticQueryContext getUserQueryContext() {
650 return userQueryContext;
651 }
652
653 /**
654 * Get the LocationMap, an data structure used to identify the location of compiled expressions within
655 * the query source text.
656 * <p>This method is intended for internal use only.</p>
657 *
658 * @return the LocationMap
659 */
660
661 public Location getContainingLocation() {
662 return moduleLocation;
663 }
664
665 /**
666 * Set the namespace for a library module.
667 * <p>This method is for internal use only.</p>
668 *
669 * @param uri the module namespace URI of the library module. Null is allowed only
670 * for a main module, not for a library module.
671 */
672
673 public void setModuleNamespace(/*@Nullable*/ String uri) {
674 moduleNamespace = uri;
675 }
676
677 /**
678 * Get the namespace of the current library module.
679 * <p>This method is intended primarily for internal use.</p>
680 *
681 * @return the module namespace, or null if this is a main module
682 */
683
684 /*@Nullable*/
685 public String getModuleNamespace() {
686 return moduleNamespace;
687 }
688
689 /**
690 * Set the location URI for a module
691 *
692 * @param uri the location URI
693 */
694
695 public void setLocationURI(URI uri) {
696 locationURI = uri;
697 moduleLocation = new ExplicitLocation(locationURI.toString(), 1, -1);
698 }
699
700 /**
701 * Get the location URI for a module
702 *
703 * @return the location URI
704 */
705
706 /*@Nullable*/
707 public URI getLocationURI() {
708 return locationURI;
709 }
710
711 /**
712 * Get the System ID for a module
713 *
714 * @return the location URI
715 */
716
717 /*@Nullable*/
718 public String getSystemId() {
719 return locationURI == null ? null : locationURI.toString();
720 }
721
722 /**
723 * Set the base URI for a module
724 *
725 * @param uri the base URI
726 */
727
728 public void setBaseURI(String uri) {
729 baseURI = uri;
730 }
731
732 /**
733 * Get the base URI for a module
734 *
735 * @return the base URI
736 */
737
738 public String getStaticBaseURI() {
739 return baseURI;
740 }
741
742
743 /**
744 * Get the stack frame map for global variables.
745 * <p>This method is intended for internal use.</p>
746 *
747 * @return the stack frame map (a SlotManager) for global variables.
748 */
749
750 public SlotManager getGlobalStackFrameMap() {
751 return getPackageData().getGlobalSlotManager();
752 }
753
754 /**
755 * Declare a global variable. A variable must normally be declared before an expression referring
756 * to it is compiled, but there are exceptions where a set of modules in the same namespace
757 * import each other cyclically. Global variables are normally declared in the Query Prolog, but
758 * they can also be predeclared using the Java API. All global variables are held in the QueryModule
759 * for the main module. The fact that a global variable is present therefore does not mean that it
760 * is visible: there are two additional conditions (a) the module namespace must be imported into the
761 * module where the reference appears, and (b) the declaration must not be in the same module and textually
762 * after the reference.
763 * <p>Note that the same VariableDeclaration object cannot be used with more than one query. This is because
764 * the VariableDeclaration is modified internally to hold a list of references to all the places where
765 * the variable is used.</p>
766 *
767 * @param var the Variable declaration being declared
768 * @throws XPathException if a static error is detected
769 */
770
771 public void declareVariable(/*@NotNull*/ GlobalVariable var) throws XPathException {
772 StructuredQName key = var.getVariableQName();
773 if (variables.get(key) != null) {
774 GlobalVariable old = variables.get(key);
775 if (old == var || old.getUltimateOriginalVariable() == var.getUltimateOriginalVariable()) {
776 // do nothing
777 } else {
778 String oldloc = " (see line " + old.getLineNumber();
779 String oldSysId = old.getSystemId();
780 if (oldSysId != null &&
781 !oldSysId.equals(var.getSystemId())) {
782 oldloc += " in module " + old.getSystemId();
783 }
784 oldloc += ")";
785 XPathException err = new XPathException("Duplicate definition of global variable "
786 + var.getVariableQName().getDisplayName()
787 + oldloc);
788 err.setErrorCode("XQST0049");
789 err.setIsStaticError(true);
790 err.setLocation(var);
791 throw err;
792 }
793 }
794 variables.put(key, var);
795 getPackageData().addGlobalVariable(var);
796
797 final HashMap<StructuredQName, GlobalVariable> libVars = getTopLevelModule().libraryVariables;
798 GlobalVariable old = libVars.get(key);
799 if (old == null || old == var) {
800 // do nothing
801 } else {
802 XPathException err = new XPathException("Duplicate definition of global variable "
803 + var.getVariableQName().getDisplayName()
804 + " (see line " + old.getLineNumber() + " in module " + old.getSystemId() + ')');
805 err.setErrorCode("XQST0049");
806 err.setIsStaticError(true);
807 err.setLocation(var);
808 throw err;
809 }
810
811 if (!isMainModule()) {
812 libVars.put(key, var);
813 }
814 }
815
816 /**
817 * Get all global variables imported into this module
818 *
819 * @return a collection of global variables.
820 * In the case of a main module, this includes only variables imported into this module,
821 * it does not include variables declared within this module. In the case of a library module,
822 * it includes both locally declared and imported variables. Blame history.
823 */
824
825 public Iterable<GlobalVariable> getGlobalVariables() {
826 return libraryVariables.values();
827 }
828
829 /**
830 * Fixup all references to global variables.
831 * <p>This method is for internal use by the Query Parser only.</p>
832 *
833 * @param globalVariableMap a SlotManager that holds details of the assignment of slots to global variables.
834 * @return a list containing the global variable definitions.
835 * @throws XPathException if compiling a global variable definition fails
836 */
837
838 public List<GlobalVariable> fixupGlobalVariables(SlotManager globalVariableMap) throws XPathException {
839 List<GlobalVariable> varDefinitions = new ArrayList<>(20);
840 List<Iterator<GlobalVariable>> iters = new ArrayList<>();
841 iters.add(variables.values().iterator());
842 iters.add(libraryVariables.values().iterator());
843
844
845 for (Iterator<GlobalVariable> iter : iters) {
846 while (iter.hasNext()) {
847 GlobalVariable var = iter.next();
848 if (!varDefinitions.contains(var)) {
849 int slot = globalVariableMap.allocateSlotNumber(var.getVariableQName());
850 var.compile(getExecutable(), slot);
851 varDefinitions.add(var);
852 }
853 }
854 }
855 return varDefinitions;
856 }
857
858 /**
859 * Look for module cycles. This is a restriction introduced in the PR specification because of
860 * difficulties in defining the formal semantics.
861 * <p>[Definition: A module M1 directly depends on another module M2 (different from M1) if a
862 * variable or function declared in M1 depends on a variable or function declared in M2.]
863 * It is a static error [err:XQST0093] to import a module M1 if there exists a sequence
864 * of modules M1 ... Mi ... M1 such that each module directly depends on the next module
865 * in the sequence (informally, if M1 depends on itself through some chain of module dependencies.)</p>
866 *
867 * @param referees a Stack containing the chain of module import references leading to this
868 * module
869 * @param lineNumber used for diagnostics
870 * @throws net.sf.saxon.trans.XPathException
871 * if cycles are found
872 */
873
874 public void lookForModuleCycles(/*@NotNull*/ Stack<QueryModule> referees, int lineNumber) throws XPathException {
875 if (referees.contains(this)) {
876 int s = referees.indexOf(this);
877 referees.push(this);
878 StringBuilder message = new StringBuilder("Circular dependency between modules. ");
879 for (int i = s; i < referees.size() - 1; i++) {
880 QueryModule next = referees.get(i + 1);
881 if (i == s) {
882 message.append("Module ").append(getSystemId()).append(" references module ").append(next.getSystemId());
883 } else {
884 message.append(", which references module ").append(next.getSystemId());
885 }
886 }
887 message.append('.');
888 XPathException err = new XPathException(message.toString());
889 err.setErrorCode("XQST0093");
890 err.setIsStaticError(true);
891 ExplicitLocation loc = new ExplicitLocation(getSystemId(), lineNumber, -1);
892 err.setLocator(loc);
893 throw err;
894 } else {
895 referees.push(this);
896 Iterator<GlobalVariable> viter = getModuleVariables();
897 while (viter.hasNext()) {
898 GlobalVariable gv = viter.next();
899 //GlobalVariable gvc = gv.getCompiledVariable(); // will be null if the global variable is unreferenced
900 Expression select = gv.getSelectExpression();
901 if (select != null) {
902 List<Binding> list = new ArrayList<>(10);
903 ExpressionTool.gatherReferencedVariables(select, list);
904 for (Binding b : list) {
905 if (b instanceof GlobalVariable) {
906 String uri = ((GlobalVariable) b).getSystemId();
907 StructuredQName qName = b.getVariableQName();
908 boolean synthetic = qName.hasURI(NamespaceConstant.SAXON_GENERATED_VARIABLE);
909 if (!synthetic && uri != null && !uri.equals(getSystemId())) {
910 QueryModule sqc = executable.getQueryModuleWithSystemId(uri, topModule);
911 if (sqc != null) {
912 sqc.lookForModuleCycles(referees, ((GlobalVariable) b).getLineNumber());
913 }
914 }
915 }
916 }
917 List<UserFunction> fList = new ArrayList<>(5);
918 ExpressionTool.gatherCalledFunctions(select, fList);
919 for (UserFunction f : fList) {
920 String uri = f.getSystemId();
921 if (uri != null && !uri.equals(getSystemId())) {
922 QueryModule sqc = executable.getQueryModuleWithSystemId(uri, topModule);
923 if (sqc != null) {
924 sqc.lookForModuleCycles(referees, f.getLineNumber());
925 }
926 }
927 }
928 }
929 }
930 Iterator<XQueryFunction> fiter = getLocalFunctionLibrary().getFunctionDefinitions();
931 while (fiter.hasNext()) {
932 XQueryFunction gf = fiter.next();
933
934 Expression body = gf.getUserFunction().getBody();
935 if (body != null) {
936 List<Binding> vList = new ArrayList<>(10);
937 ExpressionTool.gatherReferencedVariables(body, vList);
938 for (Binding b : vList) {
939 if (b instanceof GlobalVariable) {
940 String uri = ((GlobalVariable) b).getSystemId();
941 StructuredQName qName = b.getVariableQName();
942 boolean synthetic = qName.hasURI(NamespaceConstant.SAXON) && "gg".equals(qName.getPrefix());
943 if (!synthetic && uri != null && !uri.equals(getSystemId())) {
944 QueryModule sqc = executable.getQueryModuleWithSystemId(uri, topModule);
945 if (sqc != null) {
946 sqc.lookForModuleCycles(referees, ((GlobalVariable) b).getLineNumber());
947 }
948 }
949 }
950 }
951 List<UserFunction> fList = new ArrayList<>(10);
952 ExpressionTool.gatherCalledFunctions(body, fList);
953 for (UserFunction f : fList) {
954 String uri = f.getSystemId();
955 if (uri != null && !uri.equals(getSystemId())) {
956 QueryModule sqc = executable.getQueryModuleWithSystemId(uri, topModule);
957 if (sqc != null) {
958 sqc.lookForModuleCycles(referees, f.getLineNumber());
959 }
960 }
961 }
962 }
963 }
964 referees.pop();
965 }
966 }
967
968 /**
969 * Get global variables declared in this module
970 *
971 * @return an Iterator whose items are GlobalVariable objects
972 */
973
974 public Iterator<GlobalVariable> getModuleVariables() {
975 return variables.values().iterator();
976 }
977
978 /**
979 * Check for circular definitions of global variables.
980 * <p>This method is intended for internal use</p>
981 *
982 * @param compiledVars a list of {@link GlobalVariable} objects to be checked
983 * @param globalFunctionLibrary the library of global functions
984 * @throws net.sf.saxon.trans.XPathException
985 * if a circularity is found
986 */
987
988 public void checkForCircularities(/*@NotNull*/ List<GlobalVariable> compiledVars, /*@NotNull*/ XQueryFunctionLibrary globalFunctionLibrary) throws XPathException {
989 Iterator<GlobalVariable> iter = compiledVars.iterator();
990 Stack<Object> stack = null;
991 while (iter.hasNext()) {
992 if (stack == null) {
993 stack = new Stack<>();
994 }
995 GlobalVariable gv = iter.next();
996 if (gv != null) {
997 gv.lookForCycles(stack, globalFunctionLibrary);
998 }
999 }
1000 }
1001
1002
1003 /**
1004 * Perform type checking on global variables.
1005 * <p>This method is intended for internal use</p>
1006 *
1007 * @param compiledVars a list of {@link GlobalVariable} objects to be checked
1008 * @throws net.sf.saxon.trans.XPathException
1009 * if a type error occurs
1010 */
1011
1012 public void typeCheckGlobalVariables(/*@NotNull*/ List<GlobalVariable> compiledVars) throws XPathException {
1013 ExpressionVisitor visitor = ExpressionVisitor.make(this);
1014 for (GlobalVariable compiledVar : compiledVars) {
1015 compiledVar.typeCheck(visitor);
1016 }
1017 if (isMainModule()) {
1018 GlobalContextRequirement gcr = executable.getGlobalContextRequirement();
1019 if (gcr != null && gcr.getDefaultValue() != null) {
1020 ContextItemStaticInfo info = getConfiguration().makeContextItemStaticInfo(AnyItemType.getInstance(), true);
1021 gcr.setDefaultValue(gcr.getDefaultValue().typeCheck(visitor, info));
1022 }
1023 }
1024 }
1025
1026 /**
1027 * Bind a variable used in a query to the expression in which it is declared.
1028 * <p>This method is provided for use by the XQuery parser, and it should not be called by the user of
1029 * the API, or overridden, unless variables are to be declared using a mechanism other than the
1030 * declareVariable method of this class.</p>
1031 *
1032 * @param qName the name of the variable to be bound
1033 * @return a VariableReference object representing a reference to a variable on the abstract syntac rtee of
1034 * the query.
1035 */
1036
1037 /*@NotNull*/
1038 public Expression bindVariable(/*@NotNull*/ StructuredQName qName) throws XPathException {
1039 GlobalVariable var = variables.get(qName);
1040 if (var == null) {
1041 String uri = qName.getURI();
1042 if ((uri.equals("") && isMainModule()) || uri.equals(moduleNamespace) || importsNamespace(uri)) {
1043 QueryModule main = getTopLevelModule();
1044 var = main.libraryVariables.get(qName);
1045 if (var == null) {
1046 // If the namespace has been imported there's the possibility that
1047 // the variable declaration hasn't yet been read, because of the limited provision
1048 // for cyclic imports. In XQuery 3.0 forwards references are more generally allowed.
1049 //if (getLanguageVersion() >= 30) {
1050 UndeclaredVariable uvar = undeclaredVariables.get(qName);
1051 if (uvar != null) {
1052 // second or subsequent reference to the as-yet-undeclared variable
1053 GlobalVariableReference ref = new GlobalVariableReference(qName);
1054 uvar.registerReference(ref);
1055 return ref;
1056 } else {
1057 // first reference to the as-yet-undeclared variable
1058 uvar = new UndeclaredVariable();
1059 uvar.setPackageData(main.getPackageData());
1060 uvar.setVariableQName(qName);
1061 GlobalVariableReference ref = new GlobalVariableReference(qName);
1062 uvar.registerReference(ref);
1063 undeclaredVariables.put(qName, uvar);
1064 return ref;
1065 }
1066 // } else {
1067 // XPathException err = new XPathException("Variable $" + qName.getDisplayName() + " has not been declared");
1068 // err.setErrorCode("XPST0008");
1069 // err.setIsStaticError(true);
1070 // throw err;
1071 // }
1072 } else {
1073 if (var.isPrivate()) {
1074 XPathException err = new XPathException("Variable $" + qName.getDisplayName() + " is private");
1075 err.setErrorCode("XPST0008");
1076 err.setIsStaticError(true);
1077 throw err;
1078 }
1079 }
1080 } else {
1081 // If the namespace hasn't been imported then we might as well throw the error right away
1082 XPathException err = new XPathException("Variable $" + qName.getDisplayName() + " has not been declared");
1083 err.setErrorCode("XPST0008");
1084 err.setIsStaticError(true);
1085 throw err;
1086 }
1087 } else {
1088 if (var.isPrivate() && (var.getSystemId() == null || !var.getSystemId().equals(getSystemId()))) {
1089 String message = "Variable $" + qName.getDisplayName() + " is private";
1090 if (var.getSystemId() == null) {
1091 message += " (no base URI known)";
1092 }
1093 XPathException err = new XPathException(message, "XPST0008");
1094 err.setIsStaticError(true);
1095 throw err;
1096 }
1097 }
1098 GlobalVariableReference vref = new GlobalVariableReference(qName);
1099 var.registerReference(vref);
1100 return vref;
1101 }
1102
1103 /**
1104 * Get the function library containing all the in-scope functions available in this static
1105 * context (that is, the functions available in this query module).
1106 * <p>This method is provided for use by advanced applications.
1107 * The details of the interface are subject to change.</p>
1108 *
1109 * @return the FunctionLibrary used. For XQuery, this will always be a FunctionLibraryList.
1110 * @see net.sf.saxon.functions.FunctionLibraryList
1111 */
1112
1113 public FunctionLibrary getFunctionLibrary() {
1114 return functionLibraryList;
1115 }
1116
1117 /**
1118 * Get the functions declared locally within this module
1119 *
1120 * @return a FunctionLibrary object containing the function declarations
1121 */
1122
1123 /*@NotNull*/
1124 public XQueryFunctionLibrary getLocalFunctionLibrary() {
1125 return (XQueryFunctionLibrary) functionLibraryList.get(localFunctionLibraryNr);
1126 }
1127
1128 /**
1129 * Register a user-defined XQuery function.
1130 * <p>This method is intended for internal use only.</p>
1131 *
1132 * @param function the function being declared
1133 * @throws net.sf.saxon.trans.XPathException
1134 * if an error occurs, for example
1135 * a duplicate function name
1136 */
1137
1138 public void declareFunction(/*@NotNull*/ XQueryFunction function) throws XPathException {
1139 Configuration config = getConfiguration();
1140 if (function.getNumberOfArguments() == 1) {
1141 StructuredQName name = function.getFunctionName();
1142 SchemaType t = config.getSchemaType(name);
1143 if (t != null && t.isAtomicType()) {
1144 XPathException err = new XPathException("Function name " + function.getDisplayName() +
1145 " clashes with the name of the constructor function for an atomic type");
1146 err.setErrorCode("XQST0034");
1147 err.setIsStaticError(true);
1148 throw err;
1149 }
1150 }
1151 XQueryFunctionLibrary local = getLocalFunctionLibrary();
1152 local.declareFunction(function);
1153 //if (!function.isPrivate()) {
1154 QueryModule main = getTopLevelModule();
1155 main.globalFunctionLibrary.declareFunction(function);
1156 //}
1157 }
1158
1159 /**
1160 * Bind function calls that could not be bound when first encountered. These
1161 * will either be forwards references to functions declared later in the same query module,
1162 * or in modules that are being imported recursively, or errors.
1163 * <p>This method is for internal use only.</p>
1164 *
1165 * @throws net.sf.saxon.trans.XPathException
1166 * if a function call refers to a function that has
1167 * not been declared
1168 */
1169
1170 public void bindUnboundFunctionCalls() throws XPathException {
1171 UnboundFunctionLibrary lib = (UnboundFunctionLibrary) functionLibraryList.get(unboundFunctionLibraryNr);
1172 lib.bindUnboundFunctionReferences(functionLibraryList, getConfiguration());
1173 }
1174
1175 /**
1176 * Fixup all references to global functions. This method is called
1177 * on completion of query parsing. Each XQueryFunction is required to
1178 * bind all references to that function to the object representing the run-time
1179 * executable code of the function.
1180 * <p>This method is for internal use only. It is called only on the StaticQueryContext for the main
1181 * query body (not for library modules).</p>
1182 *
1183 * @throws net.sf.saxon.trans.XPathException
1184 * if an error occurs
1185 */
1186
1187 public void fixupGlobalFunctions() throws XPathException {
1188 globalFunctionLibrary.fixupGlobalFunctions(this);
1189 }
1190
1191 /**
1192 * Optimize the body of all global functions.
1193 * <p>This method is for internal use only. It is called only on the StaticQueryContext for the main
1194 * query body (not for library modules).</p>
1195 *
1196 * @throws net.sf.saxon.trans.XPathException
1197 * if an error occurs during optimization
1198 */
1199
1200 public void optimizeGlobalFunctions() throws XPathException {
1201 globalFunctionLibrary.optimizeGlobalFunctions(this);
1202 }
1203
1204
1205 /**
1206 * Output "explain" information about each declared function.
1207 * <p>This method is intended primarily for internal use.</p>
1208 *
1209 * @param out the expression presenter used to display the output
1210 */
1211
1212 public void explainGlobalFunctions(ExpressionPresenter out) throws XPathException{
1213 globalFunctionLibrary.explainGlobalFunctions(out);
1214 }
1215
1216 /**
1217 * Get the function with a given name and arity. This method is provided so that XQuery functions
1218 * can be called directly from a Java application. Note that there is no type checking or conversion
1219 * of arguments when this is done: the arguments must be provided in exactly the form that the function
1220 * signature declares them.
1221 *
1222 * @param uri the uri of the function name
1223 * @param localName the local part of the function name
1224 * @param arity the number of arguments.
1225 * @return the user-defined function, or null if no function with the given name and arity can be located
1226 * @since 8.4
1227 */
1228
1229 public UserFunction getUserDefinedFunction(String uri, String localName, int arity) {
1230 return globalFunctionLibrary.getUserDefinedFunction(uri, localName, arity);
1231 }
1232
1233 /**
1234 * Bind unbound variables (these are typically variables that reference another module
1235 * participating in a same-namespace cycle, since local forwards references are not allowed)
1236 *
1237 * @throws net.sf.saxon.trans.XPathException
1238 * if an error occurs, for example if the
1239 * variable reference cannot be resolved or if the variable is private
1240 */
1241
1242 public void bindUnboundVariables() throws XPathException {
1243 for (UndeclaredVariable uv : undeclaredVariables.values()) {
1244 StructuredQName qName = uv.getVariableQName();
1245 GlobalVariable var = variables.get(qName);
1246 if (var == null) {
1247 String uri = qName.getURI();
1248 if (importsNamespace(uri)) {
1249 QueryModule main = getTopLevelModule();
1250 var = main.libraryVariables.get(qName);
1251 }
1252 }
1253 if (var == null) {
1254 XPathException err = new XPathException("Unresolved reference to variable $" +
1255 uv.getVariableQName().getDisplayName());
1256 err.setErrorCode("XPST0008");
1257 err.setIsStaticError(true);
1258 throw err;
1259 } else if (var.isPrivate() && !var.getSystemId().equals(getSystemId())) {
1260 XPathException err = new XPathException("Cannot reference a private variable in a different module");
1261 err.setErrorCode("XPST0008");
1262 err.setIsStaticError(true);
1263 throw err;
1264 } else {
1265 uv.transferReferences(var);
1266 }
1267 }
1268 }
1269
1270 /**
1271 * Add an imported schema to this static context. A query module can reference
1272 * types in a schema provided two conditions are satisfied: the schema containing those
1273 * types has been loaded into the Configuration, and the target namespace has been imported
1274 * by this query module. This method achieves the second of these conditions. It does not
1275 * cause the schema to be loaded.
1276 *
1277 * @param targetNamespace The target namespace of the schema to be added
1278 * @param baseURI The base URI against which the locationURIs are to be absolutized
1279 * @param locationURIs a list of strings containing the absolutized URIs of the "location hints" supplied
1280 * for this schema
1281 * @since 8.4
1282 */
1283
1284 public void addImportedSchema(String targetNamespace, String baseURI, /*@NotNull*/ List<String> locationURIs) {
1285 if (importedSchemata == null) {
1286 importedSchemata = new HashSet<>(5);
1287 }
1288 importedSchemata.add(targetNamespace);
1289 HashMap<String, HashSet<String>> loadedSchemata = getTopLevelModule().loadedSchemata;
1290 if (loadedSchemata == null) {
1291 loadedSchemata = new HashMap<>(5);
1292 getTopLevelModule().loadedSchemata = loadedSchemata;
1293 }
1294 HashSet<String> entries = loadedSchemata.get(targetNamespace);
1295 if (entries == null) {
1296 entries = new HashSet<>(locationURIs.size());
1297 loadedSchemata.put(targetNamespace, entries);
1298 }
1299 for (String relative : locationURIs) {
1300 try {
1301 URI abs = ResolveURI.makeAbsolute(relative, baseURI);
1302 entries.add(abs.toString());
1303 } catch (URISyntaxException e) {
1304 // ignore the URI if it's not valid
1305 }
1306 }
1307 }
1308
1309 /**
1310 * Ask whether a given schema target namespace has been imported
1311 *
1312 * @param namespace The namespace of the required schema. Supply "" for
1313 * a no-namespace schema.
1314 * @return The schema if found, or null if not found.
1315 * @since 8.4
1316 */
1317
1318 public boolean isImportedSchema(String namespace) {
1319 return importedSchemata != null && importedSchemata.contains(namespace);
1320 }
1321
1322 /**
1323 * Get the set of imported schemas
1324 *
1325 * @return a Set, the set of URIs representing the names of imported schemas
1326 */
1327
1328 /*@Nullable*/
1329 public Set<String> getImportedSchemaNamespaces() {
1330 if (importedSchemata == null) {
1331 return Collections.emptySet();
1332 } else {
1333 return importedSchemata;
1334 }
1335 }
1336
1337 /**
1338 * Report a static error in the query (via the registered ErrorListener)
1339 *
1340 * @param err the error to be signalled
1341 */
1342
1343 public void reportStaticError(/*@NotNull*/ XPathException err) {
1344 if (!err.hasBeenReported()) {
1345 if (userQueryContext == null) {
1346 config.getErrorListener().fatalError(err);
1347 } else {
1348 userQueryContext.getErrorListener().fatalError(err);
1349 }
1350 err.setHasBeenReported(true);
1351 }
1352 }
1353
1354 /**
1355 * Construct a dynamic context for early evaluation of constant subexpressions
1356 *
1357 * @return a dynamic context object
1358 */
1359
1360 /*@NotNull*/
1361 public XPathContext makeEarlyEvaluationContext() {
1362 return new EarlyEvaluationContext(getConfiguration());
1363 }
1364
1365
1366 /**
1367 * Get the name of the default collation.
1368 *
1369 * @return the name of the default collation; or the name of the codepoint collation
1370 * if no default collation has been defined
1371 */
1372
1373 /*@Nullable*/
1374 public String getDefaultCollationName() {
1375 if (defaultCollationName == null) {
1376 defaultCollationName = NamespaceConstant.CODEPOINT_COLLATION_URI;
1377 }
1378 return defaultCollationName;
1379 }
1380
1381 /**
1382 * Set the name of the default collation
1383 * @param collation the URI of the default collation
1384 */
1385
1386 public void setDefaultCollationName(String collation) {
1387 defaultCollationName = collation;
1388 }
1389
1390 /**
1391 * Register a namespace that is explicitly declared in the prolog of the query module.
1392 *
1393 * @param prefix The namespace prefix. Must not be null.
1394 * @param uri The namespace URI. Must not be null. The value "" (zero-length string) is used
1395 * to undeclare a namespace; it is not an error if there is no existing binding for
1396 * the namespace prefix.
1397 * @throws net.sf.saxon.trans.XPathException
1398 * if the declaration is invalid
1399 */
1400
1401 public void declarePrologNamespace(/*@Nullable*/ String prefix, /*@Nullable*/ String uri) throws XPathException {
1402 if (prefix == null) {
1403 throw new NullPointerException("Null prefix supplied to declarePrologNamespace()");
1404 }
1405 if (uri == null) {
1406 throw new NullPointerException("Null namespace URI supplied to declarePrologNamespace()");
1407 }
1408 if (prefix.equals("xml") != uri.equals(NamespaceConstant.XML)) {
1409 XPathException err = new XPathException("Invalid declaration of the XML namespace");
1410 err.setErrorCode("XQST0070");
1411 err.setIsStaticError(true);
1412 throw err;
1413 }
1414 if (explicitPrologNamespaces.get(prefix) != null) {
1415 XPathException err = new XPathException("Duplicate declaration of namespace prefix \"" + prefix + '"');
1416 err.setErrorCode("XQST0033");
1417 err.setIsStaticError(true);
1418 throw err;
1419 } else {
1420 explicitPrologNamespaces.put(prefix, uri);
1421 }
1422 }
1423
1424 /**
1425 * Declare an active namespace, that is, a namespace which as well as affecting the static
1426 * context of the query, will also be copied to the result tree when element constructors
1427 * are evaluated. When searching for a prefix-URI binding, active namespaces are searched
1428 * first, then passive namespaces. Active namespaces are later undeclared (in reverse sequence)
1429 * using {@link #undeclareNamespace()}.
1430 * <p>This method is intended for internal use only.</p>
1431 *
1432 * @param prefix the namespace prefix
1433 * @param uri the namespace URI
1434 */
1435
1436 public void declareActiveNamespace(/*@Nullable*/ String prefix, /*@Nullable*/ String uri) {
1437 if (prefix == null) {
1438 throw new NullPointerException("Null prefix supplied to declareActiveNamespace()");
1439 }
1440 if (uri == null) {
1441 throw new NullPointerException("Null namespace URI supplied to declareActiveNamespace()");
1442 }
1443
1444 ActiveNamespace entry = new ActiveNamespace();
1445 entry.prefix = prefix;
1446 entry.uri = uri;
1447 activeNamespaces.push(entry);
1448
1449 // if (prefix.length() == 0) {
1450 // defaultElementNamespace = uri;
1451 // }
1452
1453 }
1454
1455 /**
1456 * Undeclare the most recently-declared active namespace. This method is called
1457 * when a namespace declaration goes out of scope (while processing an element end tag).
1458 * It is NOT called when an XML 1.1-style namespace undeclaration is encountered.
1459 * <p>This method is intended for internal use only.</p>
1460 *
1461 * @see #declareActiveNamespace(String, String)
1462 */
1463
1464 public void undeclareNamespace() {
1465 activeNamespaces.pop();
1466 }
1467
1468 /**
1469 * Return a NamespaceResolver which is "live" in the sense that, as the parse proceeeds,
1470 * it always uses the namespaces declarations in scope at the relevant time
1471 * @return a live NamespaceResolver
1472 */
1473
1474 public NamespaceResolver getLiveNamespaceResolver() {
1475 return new NamespaceResolver() {
1476 /**
1477 * Get the namespace URI corresponding to a given prefix. Return null
1478 * if the prefix is not in scope.
1479 *
1480 * @param prefix the namespace prefix. May be the zero-length string, indicating
1481 * that there is no prefix. This indicates either the default namespace or the
1482 * null namespace, depending on the value of useDefault.
1483 * @param useDefault true if the default namespace is to be used when the
1484 * prefix is "". If false, the method returns "" when the prefix is "". The default
1485 * namespace is a property of the NamespaceResolver; in general it corresponds to
1486 * the "default namespace for elements and types", but that cannot be assumed.
1487 * @return the uri for the namespace, or null if the prefix is not in scope.
1488 * The "null namespace" is represented by the pseudo-URI "".
1489 */
1490 public String getURIForPrefix(String prefix, boolean useDefault) {
1491 return checkURIForPrefix(prefix);
1492 }
1493
1494 /**
1495 * Get an iterator over all the prefixes declared in this namespace context. This will include
1496 * the default namespace (prefix="") and the XML namespace where appropriate
1497 *
1498 * @return an iterator over all the prefixes for which a namespace binding exists, including
1499 * the zero-length string to represent the null/absent prefix if it is bound
1500 */
1501 public Iterator<String> iteratePrefixes() {
1502 return getNamespaceResolver().iteratePrefixes();
1503 }
1504 };
1505 }
1506
1507
1508 /**
1509 * Get the URI for a prefix if there is one, return null if not.
1510 * This method is used by the XQuery parser to resolve namespace prefixes.
1511 * <p>This method is intended primarily for internal use.</p>
1512 *
1513 * @param prefix The prefix. Supply "" to obtain the default namespace for elements and types.
1514 * @return the corresponding namespace URI, or null if the prefix has not
1515 * been declared. If the prefix is "" and the default namespace is the non-namespace,
1516 * return "".
1517 */
1518
1519 /*@Nullable*/
1520 public String checkURIForPrefix(/*@NotNull*/ String prefix) {
1521 // Search the active namespaces first, then the passive ones.
1522 if (activeNamespaces != null) {
1523 for (int i = activeNamespaces.size() - 1; i >= 0; i--) {
1524 if (activeNamespaces.get(i).prefix.equals(prefix)) {
1525 String uri = activeNamespaces.get(i).uri;
1526 if (uri.equals("") && !prefix.equals("")) {
1527 // the namespace is undeclared
1528 return null;
1529 }
1530 return uri;
1531 }
1532 }
1533 }
1534 if (prefix.isEmpty()) {
1535 return defaultElementNamespace;
1536 }
1537 String uri = explicitPrologNamespaces.get(prefix);
1538 if (uri != null) {
1539 // A zero-length URI means the prefix was undeclared in the prolog, and we mustn't look elsewhere
1540 return uri.isEmpty() ? null : uri;
1541 }
1542
1543 if (userQueryContext != null) {
1544 uri = userQueryContext.getNamespaceForPrefix(prefix);
1545 if (uri != null) {
1546 return uri;
1547 }
1548 NamespaceResolver externalResolver = userQueryContext.getExternalNamespaceResolver();
1549 if (externalResolver != null) {
1550 return externalResolver.getURIForPrefix(prefix, true);
1551 }
1552 }
1553 return null;
1554 }
1555
1556
1557 /**
1558 * Get the default XPath namespace for elements and types. Note that this is not necessarily
1559 * the default namespace declared in the query prolog; within an expression, it may change in response
1560 * to namespace declarations on element constructors.
1561 *
1562 * @return the default namespace, or {@link NamespaceConstant#NULL} for the non-namespace
1563 */
1564
1565 /*@Nullable*/
1566 public String getDefaultElementNamespace() {
1567 return checkURIForPrefix("");
1568 }
1569
1570 /**
1571 * Set the default element namespace as declared in the query prolog
1572 *
1573 * @param uri the default namespace for elements and types
1574 */
1575
1576 public void setDefaultElementNamespace(String uri) {
1577 defaultElementNamespace = uri;
1578 }
1579
1580 /**
1581 * Get the default function namespace
1582 *
1583 * @return the default namespace for function names
1584 */
1585
1586 public String getDefaultFunctionNamespace() {
1587 return defaultFunctionNamespace;
1588 }
1589
1590 /**
1591 * Set the default function namespace
1592 *
1593 * @param uri the default namespace for functions
1594 */
1595
1596 public void setDefaultFunctionNamespace(String uri) {
1597 defaultFunctionNamespace = uri;
1598 }
1599
1600 /**
1601 * Set the revalidation mode. This is used only if XQuery Updates are in use, in other cases
1602 * the value is ignored.
1603 *
1604 * @param mode the revalidation mode. This must be one of {@link Validation#STRICT},
1605 * {@link Validation#LAX}, or {@link Validation#SKIP}
1606 */
1607
1608 public void setRevalidationMode(int mode) {
1609 if (mode == Validation.STRICT || mode == Validation.LAX || mode == Validation.SKIP) {
1610 revalidationMode = mode;
1611 } else {
1612 throw new IllegalArgumentException("Invalid mode " + mode);
1613 }
1614 }
1615
1616 /**
1617 * Get the revalidation mode. This is used only if XQuery Updates are in use, in other cases
1618 * the value is ignored.
1619 *
1620 * @return the revalidation mode. This will be one of {@link Validation#STRICT},
1621 * {@link Validation#LAX}, or {@link Validation#SKIP}
1622 */
1623
1624 public int getRevalidationMode() {
1625 return revalidationMode;
1626 }
1627
1628 /**
1629 * Get an array containing the namespace codes of all active namespaces.
1630 * <p>This method is for internal use only.</p>
1631 *
1632 * @return an array of namespace bindings (prefix/uri pairs).
1633 */
1634
1635 /*@NotNull*/
1636 public NamespaceBinding[] getActiveNamespaceCodes() {
1637 if (activeNamespaces == null) {
1638 return NamespaceBinding.EMPTY_ARRAY;
1639 }
1640 NamespaceBinding[] nsBindings = new NamespaceBinding[activeNamespaces.size()];
1641 int used = 0;
1642 HashSet<String> prefixes = new HashSet<>(10);
1643 for (int n = activeNamespaces.size() - 1; n >= 0; n--) {
1644 ActiveNamespace an = activeNamespaces.get(n);
1645 if (!prefixes.contains(an.prefix)) {
1646 prefixes.add(an.prefix);
1647 nsBindings[used++] = new NamespaceBinding(an.prefix, an.uri);
1648 }
1649 }
1650 if (used < nsBindings.length) {
1651 nsBindings = Arrays.copyOf(nsBindings, used);
1652 }
1653 return nsBindings;
1654 }
1655
1656 /**
1657 * Get a copy of the Namespace Context. This method is used internally
1658 * by the query parser when a construct is encountered that needs
1659 * to save the namespace context for use at run-time. Note that unlike other implementations of
1660 * StaticContext, the state of the QueryModule changes as the query is parsed, with different namespaces
1661 * in scope at different times. It's therefore necessary to compute the whole namespace context each time.
1662 * <p>This method is for internal use only.</p>
1663 */
1664
1665 /*@NotNull*/
1666 public NamespaceResolver getNamespaceResolver() {
1667 List<NamespaceBinding> externalNamespaceCodes = null;
1668 NamespaceResolver externalResolver = userQueryContext.getExternalNamespaceResolver();
1669 if (externalResolver != null) {
1670 externalNamespaceCodes = new ArrayList<>();
1671 Iterator iter = externalResolver.iteratePrefixes();
1672 while (iter.hasNext()) {
1673 String prefix = (String) iter.next();
1674 String uri = externalResolver.getURIForPrefix(prefix, true);
1675 NamespaceBinding nscode = new NamespaceBinding(prefix, uri);
1676 externalNamespaceCodes.add(nscode);
1677 }
1678 }
1679 HashMap<String, String> userDeclaredNamespaces = userQueryContext.getUserDeclaredNamespaces();
1680 List<NamespaceBinding> nsBindings = new ArrayList<>();
1681
1682 for (Map.Entry<String, String> e : userDeclaredNamespaces.entrySet()) {
1683 nsBindings.add(new NamespaceBinding(e.getKey(), e.getValue()));
1684 }
1685 for (Map.Entry<String, String> e : explicitPrologNamespaces.entrySet()) {
1686 nsBindings.add(new NamespaceBinding(e.getKey(), e.getValue()));
1687 }
1688 if (!defaultElementNamespace.isEmpty()) {
1689 nsBindings.add(new NamespaceBinding("", defaultElementNamespace));
1690 }
1691 nsBindings.addAll(Arrays.asList(getActiveNamespaceCodes()));
1692
1693 if (externalNamespaceCodes != null) {
1694 nsBindings.addAll(externalNamespaceCodes);
1695 }
1696
1697 return new SavedNamespaceContext(nsBindings);
1698 }
1699
1700 /**
1701 * Get the required type of the context item. If no type has been explicitly declared for the context
1702 * item, an instance of AnyItemType (representing the type item()) is returned.
1703 *
1704 * @return the required type of the context item. Note that this is the same for all modules.
1705 * @since 9.3
1706 */
1707
1708 public ItemType getRequiredContextItemType() {
1709 return requiredContextItemType;
1710 }
1711
1712 /**
1713 * Get a DecimalFormatManager to resolve the names of decimal formats used in calls
1714 * to the format-number() function.
1715 *
1716 * @return the decimal format manager for this static context, or null if named decimal
1717 * formats are not supported in this environment.
1718 */
1719
1720 /*@Nullable*/
1721 public DecimalFormatManager getDecimalFormatManager() {
1722 if (decimalFormatManager == null) {
1723 decimalFormatManager = new DecimalFormatManager(Configuration.XQUERY, getXPathVersion());
1724 }
1725 return decimalFormatManager;
1726 }
1727
1728 /**
1729 * Issue a compile-time warning. This method is used during XQuery expression compilation to
1730 * output warning conditions.
1731 * <p>This method is intended for internal use only.</p>
1732 */
1733
1734 public void issueWarning(String s, Location locator) {
1735 XPathException err = new XPathException(s);
1736 err.setLocator(locator);
1737 if (userQueryContext != null) {
1738 userQueryContext.getErrorListener().warning(err);
1739 } else {
1740 getConfiguration().getErrorListener().warning(err);
1741 }
1742 }
1743
1744 /**
1745 * Determine whether Backwards Compatible Mode is used
1746 *
1747 * @return false; XPath 1.0 compatibility mode is not supported in XQuery
1748 * @since 8.4
1749 */
1750
1751 public boolean isInBackwardsCompatibleMode() {
1752 return false;
1753 }
1754
1755 /**
1756 * Ask whether the query module is allowed to be updating
1757 *
1758 * @return true if the query module is allowed to use the XQuery Update facility
1759 * @since 9.1
1760 */
1761
1762 public boolean isUpdating() {
1763 return isUpdating;
1764 }
1765
1766 /**
1767 * Get the XPath language level supported, as an integer (being the actual version
1768 * number times ten). In Saxon 9.9 the only value supported for XQuery is 3.1
1769 *
1770 * @return the XPath language level; the return value will be 31
1771 * @since 9.7
1772 */
1773
1774 public int getXPathVersion() {
1775 return 31;
1776 }
1777
1778 /**
1779 * Get the CodeInjector if one is in use
1780 *
1781 * @return the code injector if there is one
1782 */
1783
1784 public CodeInjector getCodeInjector() {
1785 return codeInjector;
1786 }
1787
1788 /**
1789 * Get the KeyManager, containing definitions of keys available for use.
1790 *
1791 * @return the KeyManager. This is used to resolve key names, both explicit calls
1792 * on key() used in XSLT, and system-generated calls on key() which may
1793 * also appear in XQuery and XPath
1794 */
1795 public KeyManager getKeyManager() {
1796 return packageData.getKeyManager();
1797 }
1798
1799 /**
1800 * Get type alias. This is a Saxon extension. A type alias is a QName which can
1801 * be used as a shorthand for an itemtype, using the syntax ~typename anywhere that
1802 * an item type is permitted.
1803 *
1804 * @param typeName the name of the type alias
1805 * @return the corresponding item type, if the name is recognised; otherwise null.
1806 */
1807
1808 @Override
1809 public ItemType resolveTypeAlias(StructuredQName typeName) {
1810 return getPackageData().obtainTypeAliasManager().getItemType(typeName);
1811 }
1812
1813 /**
1814 * Inner class containing information about an active namespace entry
1815 */
1816
1817 private static class ActiveNamespace {
1818 /*@Nullable*/ public String prefix;
1819 /*@Nullable*/ public String uri;
1820 }
1821 }
1822