Debian Codegraph @

net/sf/saxon/query/StaticQueryContext.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.Literal;
12 import net.sf.saxon.expr.instruct.Executable;
13 import net.sf.saxon.expr.instruct.GlobalParam;
14 import net.sf.saxon.expr.instruct.GlobalVariable;
15 import net.sf.saxon.expr.parser.CodeInjector;
16 import net.sf.saxon.expr.parser.Location;
17 import net.sf.saxon.expr.parser.OptimizerOptions;
18 import net.sf.saxon.expr.sort.SimpleCollation;
19 import net.sf.saxon.functions.FunctionLibrary;
20 import net.sf.saxon.lib.*;
21 import net.sf.saxon.om.*;
22 import net.sf.saxon.trace.TraceCodeInjector;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.type.AnyItemType;
25 import net.sf.saxon.type.ItemType;
26 import net.sf.saxon.value.SequenceType;
27
28 import javax.xml.transform.ErrorListener;
29 import javax.xml.transform.Source;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.Reader;
33 import java.util.*;
34
35 /**
36 * StaticQueryContext contains information used to build a StaticContext for use when processing XQuery
37 * expressions.
38 * <p>Despite its name, <code>StaticQueryContext</code> no longer implements the <code>StaticContext</code>
39 * interface, which means it cannot be used directly by Saxon when parsing a query. Instead it is first copied
40 * to create a <code>QueryModule</code> object, which does implement the <code>StaticContext</code> interface.</p>
41 * <p>The application constructs a StaticQueryContext
42 * and initializes it with information about the context, for example, default namespaces, base URI, and so on.
43 * When a query is compiled using this StaticQueryContext, the query parser makes a copy of the StaticQueryContext
44 * and uses this internally, modifying it with information obtained from the query prolog, as well as information
45 * such as namespace and variable declarations that can occur at any point in the query. The query parser does
46 * not modify the original StaticQueryContext supplied by the calling application, which may therefore be used
47 * for compiling multiple queries, serially or even in multiple threads.</p>
48 * <p>This class forms part of Saxon's published XQuery API. Methods that
49 * are considered stable are labelled with the JavaDoc "since" tag.
50 * The value 8.4 indicates a method introduced at or before Saxon 8.4; other
51 * values indicate the version at which the method was introduced.</p>
52 * <p>In the longer term, this entire API may at some stage be superseded by a proposed
53 * standard Java API for XQuery.</p>
54 *
55 * @since 8.4
56 */
57
58 public class StaticQueryContext {
59
60 private Configuration config;
61 private NamePool namePool;
62 private String baseURI;
63 private HashMap<String, String> userDeclaredNamespaces;
64 /*@Nullable*/ private Set<GlobalVariable> userDeclaredVariables;
65 private boolean inheritNamespaces = true;
66 private boolean preserveNamespaces = true;
67 private int constructionMode = Validation.PRESERVE;
68 /*@Nullable*/ private NamespaceResolver externalNamespaceResolver = null;
69 private String defaultFunctionNamespace = NamespaceConstant.FN;
70 /*@Nullable*/ private String defaultElementNamespace = NamespaceConstant.NULL;
71 private ItemType requiredContextItemType = AnyItemType.getInstance();
72 private boolean preserveSpace = false;
73 private boolean defaultEmptyLeast = true;
74 /*@Nullable*/ private ModuleURIResolver moduleURIResolver;
75 private UnfailingErrorListener errorListener;
76 /*@Nullable*/ private CodeInjector codeInjector;
77 private boolean isUpdating = false;
78 private int languageVersion = 30;
79 private String defaultCollationName;
80 private Location moduleLocation;
81 private OptimizerOptions optimizerOptions;
82
83
84
85 /**
86 * Private constructor used when copying a context
87 */
88
89 protected StaticQueryContext() {
90 }
91
92 /**
93 * Create a StaticQueryContext using a given Configuration. This creates a StaticQueryContext for a main module
94 * (that is, a module that is not a library module). The static query context is initialized from the
95 * default static query context held in the configuration.
96 *
97 * @param config the Saxon Configuration
98 * @since 8.4
99 */
100
101 public StaticQueryContext(Configuration config) {
102 this(config, true);
103 }
104
105 /**
106 * Create a StaticQueryContext using a given Configuration. This creates a StaticQueryContext for a main module
107 * (that is, a module that is not a library module). The static query context is initialized from the
108 * default static query context held in the configuration only if the {@code initialize} argument is set to true.
109 *
110 * @param config the Saxon Configuration
111 * @param initialize specifies whether the static context should be initialized using defaults held in the
112 * configuration. Setting this to true has the same effect as calling the single-argument
113 * constructor. Setting it to false is typically used only when creating the default
114 * static query context held by the configuration.
115 * @since 9.9
116 */
117
118 public StaticQueryContext(Configuration config, boolean initialize) {
119 this.config = config;
120 this.namePool = config.getNamePool();
121 if (initialize) {
122 copyFrom(config.getDefaultStaticQueryContext());
123 } else {
124 userDeclaredNamespaces = new HashMap<>();
125 userDeclaredVariables = new HashSet<>();
126 optimizerOptions = config.getOptimizerOptions();
127 clearNamespaces();
128 }
129 }
130
131 /**
132 * Create a copy of a supplied StaticQueryContext
133 *
134 * @param c the StaticQueryContext to be copied
135 */
136
137 public StaticQueryContext(/*@NotNull*/ StaticQueryContext c) {
138 copyFrom(c);
139 }
140
141 /**
142 * Static method used to create the default static context: intended for internal use only
143 */
144
145 public static StaticQueryContext makeDefaultStaticQueryContext(Configuration config) {
146 StaticQueryContext sqc = new StaticQueryContext();
147 sqc.config = config;
148 sqc.namePool = config.getNamePool();
149 sqc.reset();
150 return sqc;
151 }
152
153 /**
154 * Copy details from another StaticQueryContext
155 * @param c the other StaticQueryContext
156 */
157
158 public void copyFrom(/*@NotNull*/ StaticQueryContext c) {
159 config = c.config;
160 namePool = c.namePool;
161 baseURI = c.baseURI;
162 moduleURIResolver = c.moduleURIResolver;
163 if (c.userDeclaredNamespaces != null) {
164 userDeclaredNamespaces = new HashMap<>(c.userDeclaredNamespaces);
165 }
166 if (c.userDeclaredVariables != null) {
167 userDeclaredVariables = new HashSet<>(c.userDeclaredVariables);
168 }
169 inheritNamespaces = c.inheritNamespaces;
170 preserveNamespaces = c.preserveNamespaces;
171 constructionMode = c.constructionMode;
172 externalNamespaceResolver = c.externalNamespaceResolver;
173 defaultElementNamespace = c.defaultElementNamespace;
174 defaultFunctionNamespace = c.defaultFunctionNamespace;
175 requiredContextItemType = c.requiredContextItemType;
176 preserveSpace = c.preserveSpace;
177 defaultEmptyLeast = c.defaultEmptyLeast;
178 moduleURIResolver = c.moduleURIResolver;
179 errorListener = c.errorListener;
180 codeInjector = c.codeInjector;
181 isUpdating = c.isUpdating;
182 optimizerOptions = c.optimizerOptions;
183 }
184
185
186 /**
187 * Reset the state of this StaticQueryContext to an uninitialized state
188 *
189 * @since 8.4
190 */
191
192 public void reset() {
193 userDeclaredNamespaces = new HashMap<>(10);
194 externalNamespaceResolver = null;
195 errorListener = config.getErrorListener();
196 if (errorListener instanceof StandardErrorListener) {
197 errorListener = ((StandardErrorListener) errorListener).makeAnother(Configuration.XQUERY);
198 ((StandardErrorListener) errorListener).setRecoveryPolicy(Configuration.DO_NOT_RECOVER);
199 }
200 constructionMode = getConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY) ?
201 Validation.PRESERVE : Validation.STRIP;
202 preserveSpace = false;
203 defaultEmptyLeast = true;
204 requiredContextItemType = AnyItemType.getInstance();
205 defaultFunctionNamespace = NamespaceConstant.FN;
206 defaultElementNamespace = NamespaceConstant.NULL;
207 moduleURIResolver = null;
208 defaultCollationName = config.getDefaultCollationName();
209 clearNamespaces();
210 isUpdating = false;
211 optimizerOptions = config.getOptimizerOptions();
212
213 }
214
215 /**
216 * Set the Configuration options
217 *
218 * @param config the Saxon Configuration
219 * @throws IllegalArgumentException if the configuration supplied is different from the existing
220 * configuration
221 * @since 8.4
222 */
223
224 public void setConfiguration(/*@NotNull*/ Configuration config) {
225 if (this.config != null && this.config != config) {
226 throw new IllegalArgumentException("Configuration cannot be changed dynamically");
227 }
228 this.config = config;
229 namePool = config.getNamePool();
230 }
231
232 /**
233 * Get the Configuration options
234 *
235 * @return the Saxon configuration
236 * @since 8.4
237 */
238
239 public Configuration getConfiguration() {
240 return config;
241 }
242
243 /**
244 * Get the executable containing this query
245 *
246 * @return the executable (which is newly created by this method)
247 */
248
249 /*@NotNull*/
250 public Executable makeExecutable() {
251 Executable executable = new Executable(config);
252 executable.setSchemaAware(isSchemaAware());
253 executable.setHostLanguage(Configuration.XQUERY);
254 return executable;
255 }
256
257 /**
258 * Say whether this query is schema-aware
259 *
260 * @param aware true if this query is schema-aware
261 * @since 9.2.1.2
262 */
263
264 public void setSchemaAware(boolean aware) {
265 if (aware) {
266 throw new UnsupportedOperationException("Schema-awareness requires Saxon-EE");
267 }
268 }
269
270 /**
271 * Ask whether this query is schema-aware
272 *
273 * @return true if this query is schema-aware
274 * @since 9.2.1.2
275 */
276
277 public boolean isSchemaAware() {
278 return false;
279 }
280
281 /**
282 * Say whether the query should be compiled and evaluated to use streaming.
283 * This affects subsequent calls on the compile() methods. This option requires
284 * Saxon-EE.
285 * @param option if true, the compiler will attempt to compile a query to be
286 * capable of executing in streaming mode. If the query cannot be streamed,
287 * a compile-time exception is reported. In streaming mode, the source
288 * document is supplied as a stream, and no tree is built in memory. The default
289 * is false. Setting the value to true has the side-effect of setting the required
290 * context item type to "document node"; this is to ensure that expresions such as
291 * //BOOK are streamable.
292 * @since 9.6
293 */
294
295 public void setStreaming(boolean option) {
296 if (option) {
297 throw new UnsupportedOperationException("Streaming requires Saxon-EE");
298 }
299 }
300
301 /**
302 * Ask whether the streaming option has been set, that is, whether
303 * subsequent calls on compile() will compile queries to be capable
304 * of executing in streaming mode.
305 * @return true if the streaming option has been set.
306 * @since 9.6
307 */
308
309 public boolean isStreaming() {
310 return false;
311 }
312
313
314 /**
315 * Set the Base URI of the query
316 *
317 * @param baseURI the base URI of the query, or null to indicate that no base URI is available
318 * @since 8.4
319 */
320
321 public void setBaseURI(String baseURI) {
322 this.baseURI = baseURI;
323 }
324
325 /**
326 * Convenience method for building Saxon's internal representation of a source XML
327 * document. The document will be built using Configuration (and NamePool) associated
328 * with this StaticQueryContext.
329 * <p>This method is retained for backwards compatibility; however, it is merely a wrapper
330 * around the method {@link Configuration#buildDocumentTree}, which should be called in preference.</p>
331 *
332 * @param source Any javax.xml.transform.Source object representing the document against
333 * which queries will be executed. Note that a Saxon {@link net.sf.saxon.om.NodeInfo}
334 * can be used as a Source. To use a third-party DOM Document as a source, create an instance of
335 * {@link javax.xml.transform.dom.DOMSource} to wrap it.
336 * <p>For additional control over the way in which the source document is processed,
337 * supply an {@link net.sf.saxon.lib.AugmentedSource} object and set appropriate
338 * options on the object.</p>
339 * @return the DocumentInfo representing the root node of the resulting document object.
340 * @throws XPathException if building the document fails
341 * @since 8.4
342 * @deprecated since 9.2: use {@link Configuration#buildDocumentTree(javax.xml.transform.Source)}
343 */
344
345 /*@NotNull*/
346 public TreeInfo buildDocument(Source source) throws XPathException {
347 return config.buildDocumentTree(source);
348 }
349
350 /**
351 * Set the language version.
352 *
353 * @param version The XQuery language version. Must be 10 (="1.0") or 30 (="3.0") or 31 (="3.1").
354 * @since 9.2; changed in 9.3 to expect a DecimalValue rather than a string. Changed in 9.7 to
355 * accept an int (30 = "3.0") and to allow "3.1". From 9.8.0.3 the supplied value is ignored
356 * and the language version is always set to "3.1".
357 */
358
359 public void setLanguageVersion(int version) {
360 if (version==10 || version==30 || version==31) {
361 // value is ignored
362 } else {
363 throw new IllegalArgumentException("languageVersion = " + version);
364 }
365 }
366
367 /**
368 * Get the language version
369 *
370 * @return the language version. Either "1.0" or "1.1". Default is "1.0".
371 * @since 9.2; changed in 9.3 to return a DecimalValue rather than a string;
372 * changed in 9.7 to return an int (30 = "3.0" and so on). Changed in 9.8.0.3 to
373 * always return 31.
374 */
375
376 public int getLanguageVersion() {
377 return 31;
378 }
379
380 /**
381 * Get any extension function library that was previously set.
382 *
383 * @return the extension function library, or null if none has been set. The result will always be null if called
384 * in Saxon-HE; setting an extension function library requires the Saxon-PE or Saxon-EE versions of this class.
385 * @since 9.4
386 */
387
388
389 /*@Nullable*/
390 public FunctionLibrary getExtensionFunctionLibrary() {
391 return null;
392 }
393
394
395 /**
396 * Ask whether compile-time generation of trace code was requested
397 *
398 * @return true if compile-time generation of code was requested
399 * @since 9.0
400 */
401
402 public boolean isCompileWithTracing() {
403 return codeInjector instanceof TraceCodeInjector;
404 }
405
406 /**
407 * Request compile-time generation of trace code (or not)
408 *
409 * @param trace true if compile-time generation of trace code is required
410 * @since 9.0
411 */
412
413 public void setCompileWithTracing(boolean trace) {
414 if (trace) {
415 codeInjector = new TraceCodeInjector();
416 } else {
417 codeInjector = null;
418 }
419 }
420
421 /**
422 * Request that the parser should insert custom code into the expression tree
423 * by calling a supplied CodeInjector to process each expression as it is parsed,
424 * for example for tracing or performance measurement
425 *
426 * @param injector the CodeInjector to be used. May be null, in which case
427 * no code is injected
428 * @since 9.4
429 */
430
431 public void setCodeInjector( /*@Nullable*/ CodeInjector injector) {
432 this.codeInjector = injector;
433 }
434
435 /**
436 * Get any CodeInjector that has been registered
437 *
438 * @return the registered CodeInjector, or null
439 * @since 9.4
440 */
441
442 /*@Nullable*/
443 public CodeInjector getCodeInjector() {
444 return codeInjector;
445 }
446
447 /**
448 * Ask whether XQuery Update is allowed
449 *
450 * @return true if XQuery update is supported by queries using this context
451 */
452
453 public boolean isUpdating() {
454 return isUpdating;
455 }
456
457 /**
458 * Set the namespace inheritance mode
459 *
460 * @param inherit true if namespaces are inherited, false if not
461 * @since 8.4
462 */
463
464 public void setInheritNamespaces(boolean inherit) {
465 inheritNamespaces = inherit;
466 }
467
468 /**
469 * Get the namespace inheritance mode
470 *
471 * @return true if namespaces are inherited, false if not
472 * @since 8.4
473 */
474
475 public boolean isInheritNamespaces() {
476 return inheritNamespaces;
477 }
478
479 /**
480 * Set the namespace copy mode
481 *
482 * @param inherit true if namespaces are preserved, false if not
483 * @since 8.4
484 */
485
486 public void setPreserveNamespaces(boolean inherit) {
487 preserveNamespaces = inherit;
488 }
489
490 /**
491 * Get the namespace copy mode
492 *
493 * @return true if namespaces are preserved, false if not
494 * @since 8.4
495 */
496
497 public boolean isPreserveNamespaces() {
498 return preserveNamespaces;
499 }
500
501 /**
502 * Set the construction mode for this module
503 *
504 * @param mode one of {@link net.sf.saxon.lib.Validation#STRIP}, {@link net.sf.saxon.lib.Validation#PRESERVE}
505 * @since 8.4
506 */
507
508 public void setConstructionMode(int mode) {
509 constructionMode = mode;
510 }
511
512 /**
513 * Get the current construction mode
514 *
515 * @return one of {@link net.sf.saxon.lib.Validation#STRIP}, {@link net.sf.saxon.lib.Validation#PRESERVE}
516 * @since 8.4
517 */
518
519 public int getConstructionMode() {
520 return constructionMode;
521 }
522
523 /**
524 * Set the module location. Normally the module location is assumed to be line 1, column 1 of the
525 * resource identified by the base URI. But a different location can be set, for example if the query
526 * is embedded in an XML document, and this information will be available in diagnostics.
527 * @param location the module location
528 * @since 9.7
529 */
530
531 public void setModuleLocation(Location location) {
532 this.moduleLocation = location;
533 }
534
535 /**
536 * Get the module location. Normally the module location is assumed to be line 1, column 1 of the
537 * resource identified by the base URI. But a different location can be set, for example if the query
538 * is embedded in an XML document, and this information will be available in diagnostics.
539 * @return the module location
540 * @since 9.7
541 */
542
543 public Location getModuleLocation() {
544 return moduleLocation;
545 }
546
547 /**
548 * Set the optimizer options to be used for compiling queries that use this static context.
549 * By default the optimizer options set in the {@link Configuration} are used.
550 *
551 * @param options the optimizer options to be used
552 */
553
554 public void setOptimizerOptions(OptimizerOptions options) {
555 this.optimizerOptions = options;
556 }
557
558 /**
559 * Get the optimizer options being used for compiling queries that use this static context.
560 * By default the optimizer options set in the {@link Configuration} are used.
561 *
562 * @return the optimizer options being used
563 */
564
565 public OptimizerOptions getOptimizerOptions() {
566 return this.optimizerOptions;
567 }
568
569
570 /**
571 * Prepare an XQuery query for subsequent evaluation. The source text of the query
572 * is supplied as a String. The base URI of the query is taken from the static context,
573 * and defaults to the current working directory.
574 * <p>Note that this interface makes the caller responsible for decoding the query and
575 * presenting it as a string of characters. This means it is likely that any encoding
576 * specified in the query prolog will be ignored.</p>
577 *
578 * @param query The XQuery query to be evaluated, supplied as a string.
579 * @return an XQueryExpression object representing the prepared expression
580 * @throws net.sf.saxon.trans.XPathException
581 * if the syntax of the expression is wrong,
582 * or if it references namespaces, variables, or functions that have not been declared,
583 * or contains other static errors.
584 * @since 8.4
585 */
586
587 /*@NotNull*/
588 public XQueryExpression compileQuery(/*@NotNull*/ String query) throws XPathException {
589 XQueryParser qp = (XQueryParser) config.newExpressionParser("XQ", isUpdating, 31);
590 if (codeInjector != null) {
591 qp.setCodeInjector(codeInjector);
592 } else if (config.isCompileWithTracing()) {
593 qp.setCodeInjector(new TraceCodeInjector());
594 }
595 qp.setStreaming(isStreaming());
596 QueryModule mainModule = new QueryModule(this);
597 return qp.makeXQueryExpression(query, mainModule, config);
598 }
599
600 /**
601 * Prepare an XQuery query for subsequent evaluation. The Query is supplied
602 * in the form of a Reader. The base URI of the query is taken from the static context,
603 * and defaults to the current working directory.
604 * <p>Note that this interface makes the Reader responsible for decoding the query and
605 * presenting it as a stream of characters. This means it is likely that any encoding
606 * specified in the query prolog will be ignored. Also, some implementations of Reader
607 * cannot handle a byte order mark.</p>
608 *
609 * @param source A Reader giving access to the text of the XQuery query to be compiled.
610 * @return an XPathExpression object representing the prepared expression.
611 * @throws net.sf.saxon.trans.XPathException
612 * if the syntax of the expression is wrong, or if it references namespaces,
613 * variables, or functions that have not been declared, or any other static error is reported.
614 * @throws java.io.IOException if a failure occurs reading the supplied input.
615 * @since 8.4
616 */
617
618 /*@Nullable*/
619 public synchronized XQueryExpression compileQuery(/*@NotNull*/ Reader source)
620 throws XPathException, IOException {
621 char[] buffer = new char[4096];
622 StringBuilder sb = new StringBuilder(4096);
623 while (true) {
624 int n = source.read(buffer);
625 if (n > 0) {
626 sb.append(buffer, 0, n);
627 } else {
628 break;
629 }
630 }
631 return compileQuery(sb.toString());
632 }
633
634 /**
635 * Prepare an XQuery query for subsequent evaluation. The Query is supplied
636 * in the form of a InputStream, with an optional encoding. If the encoding is not specified,
637 * the query parser attempts to obtain the encoding by inspecting the input stream: it looks specifically
638 * for a byte order mark, and for the encoding option in the version declaration of an XQuery prolog.
639 * The encoding defaults to UTF-8.
640 * The base URI of the query is taken from the static context,
641 * and defaults to the current working directory.
642 *
643 * @param source An InputStream giving access to the text of the XQuery query to be compiled, as a stream
644 * of octets
645 * @param encoding The encoding used to translate characters to octets in the query source. The parameter
646 * may be null: in this case the query parser attempts to infer the encoding by inspecting the source,
647 * and if that fails, it assumes UTF-8 encoding
648 * @return an XPathExpression object representing the prepared expression.
649 * @throws net.sf.saxon.trans.XPathException
650 * if the syntax of the expression is wrong, or if it references namespaces,
651 * variables, or functions that have not been declared, or any other static error is reported.
652 * @since 8.5
653 */
654 /*@Nullable*/
655 public synchronized XQueryExpression compileQuery(/*@NotNull*/ InputStream source, /*@Nullable*/ String encoding)
656 throws XPathException {
657 String query = QueryReader.readInputStream(source, encoding, config.getValidCharacterChecker());
658 return compileQuery(query);
659 }
660
661 /**
662 * Compile an XQuery library module for subsequent evaluation. This method is supported
663 * only in Saxon-EE
664 *
665 * @param query the content of the module, as a string
666 * @throws XPathException if a static error exists in the query
667 * @throws UnsupportedOperationException if not using Saxon-EE
668 * @since 9.2 (changed in 9.3 to return void)
669 */
670
671 public void compileLibrary(String query) throws XPathException {
672 throw new XPathException("Separate compilation of query libraries requires Saxon-EE");
673 }
674
675 /**
676 * Prepare an XQuery library module for subsequent evaluation. This method is supported
677 * only in Saxon-EE. The effect of the method is that subsequent query compilations using this static
678 * context can import the module URI without specifying a location hint; the import then takes effect
679 * without requiring the module to be compiled each time it is imported.
680 *
681 * @param source the content of the module, as a Reader which supplies the source code
682 * @throws XPathException if a static error exists in the query
683 * @throws IOException if the input cannot be read
684 * @throws UnsupportedOperationException if not using Saxon-EE
685 * @since 9.2 (changed in 9.3 to return void)
686 */
687
688 public void compileLibrary(Reader source)
689 throws XPathException, IOException {
690 throw new XPathException("Separate compilation of query libraries requires Saxon-EE");
691 }
692
693 /**
694 * Prepare an XQuery library module for subsequent evaluation. This method is supported
695 * only in Saxon-EE. The effect of the method is that subsequent query compilations using this static
696 * context can import the module URI without specifying a location hint; the import then takes effect
697 * without requiring the module to be compiled each time it is imported.
698 *
699 * @param source the content of the module, as an InputStream which supplies the source code
700 * @param encoding the character encoding of the input stream. May be null, in which case the encoding
701 * is inferred, for example by looking at the query declaration
702 * @throws XPathException if a static error exists in the query
703 * @throws IOException if the input cannot be read
704 * @throws UnsupportedOperationException if not using Saxon-EE
705 * @since 9.2 (changed in 9.3 to return void)
706 */
707
708 public void compileLibrary(InputStream source, /*@Nullable*/ String encoding)
709 throws XPathException, IOException {
710 throw new UnsupportedOperationException("Separate compilation of query libraries requires Saxon-EE");
711 }
712
713 /**
714 * Get a previously compiled library module
715 *
716 * @param namespace the module namespace
717 * @return the QueryLibrary if a module with this namespace has been compiled as a library module;
718 * otherwise null. Always null when not using Saxon-EE.
719 * @since 9.3
720 */
721
722 /*@Nullable*/
723 public QueryLibrary getCompiledLibrary(String namespace) {
724 return null;
725 }
726
727 public Collection<QueryLibrary> getCompiledLibraries() {
728 return Collections.emptySet();
729 }
730
731
732 /**
733 * Declare a namespace whose prefix can be used in expressions. This is
734 * equivalent to declaring a prefix in the Query prolog.
735 * Any namespace declared in the Query prolog overrides a namespace declared using
736 * this API.
737 *
738 * @param prefix The namespace prefix. Must not be null. Setting this to "" means that the
739 * namespace will be used as the default namespace for elements and types.
740 * @param uri The namespace URI. Must not be null. The value "" (zero-length string) is used
741 * to undeclare a namespace; it is not an error if there is no existing binding for
742 * the namespace prefix.
743 * @throws NullPointerException if either the prefix or URI is null
744 * @throws IllegalArgumentException if the prefix is "xml" and the namespace is not the XML namespace, or vice
745 * versa; or if the prefix is "xmlns", or the URI is "http://www.w3.org/2000/xmlns/"
746 * @since 9.0
747 */
748
749 public void declareNamespace( /*@Nullable*/ String prefix, /*@Nullable*/ String uri) {
750 if (prefix == null) {
751 throw new NullPointerException("Null prefix supplied to declareNamespace()");
752 }
753 if (uri == null) {
754 throw new NullPointerException("Null namespace URI supplied to declareNamespace()");
755 }
756 if (prefix.equals("xml") != uri.equals(NamespaceConstant.XML)) {
757 throw new IllegalArgumentException("Misdeclaration of XML namespace");
758 }
759 if (prefix.equals("xmlns") || uri.equals(NamespaceConstant.XMLNS)) {
760 throw new IllegalArgumentException("Misdeclaration of xmlns namespace");
761 }
762 if (prefix.isEmpty()) {
763 defaultElementNamespace = uri;
764 }
765 if (uri.isEmpty()) {
766 userDeclaredNamespaces.remove(prefix);
767 } else {
768 userDeclaredNamespaces.put(prefix, uri);
769 }
770
771 }
772
773 /**
774 * Clear all the user-declared namespaces
775 *
776 * @since 9.0
777 */
778
779 public void clearNamespaces() {
780 userDeclaredNamespaces.clear();
781 declareNamespace("xml", NamespaceConstant.XML);
782 declareNamespace("xs", NamespaceConstant.SCHEMA);
783 declareNamespace("xsi", NamespaceConstant.SCHEMA_INSTANCE);
784 declareNamespace("fn", NamespaceConstant.FN);
785 declareNamespace("local", NamespaceConstant.LOCAL);
786 declareNamespace("err", NamespaceConstant.ERR);
787 declareNamespace("saxon", NamespaceConstant.SAXON);
788 declareNamespace("", "");
789
790 }
791
792 /**
793 * Get the map of user-declared namespaces
794 *
795 * @return the user-declared namespaces
796 */
797
798 protected HashMap<String, String> getUserDeclaredNamespaces() {
799 return userDeclaredNamespaces;
800 }
801
802 /**
803 * Get the namespace prefixes that have been declared using the method {@link #declareNamespace}
804 *
805 * @return an iterator that returns the namespace prefixes that have been explicitly declared, as
806 * strings. The default namespace for elements and types will be included, using the prefix "".
807 * @since 9.0
808 */
809
810 public Iterator<String> iterateDeclaredPrefixes() {
811 return userDeclaredNamespaces.keySet().iterator();
812 }
813
814 /**
815 * Get the namespace URI for a given prefix, which must have been declared using the method
816 * {@link #declareNamespace}. Note that this method will not call the external namespace resolver
817 * to resolve the prefix.
818 *
819 * @param prefix the namespace prefix, or "" to represent the null prefix
820 * @return the namespace URI. Returns "" to represent the non-namespace,
821 * null to indicate that the prefix has not been declared
822 */
823
824 public String getNamespaceForPrefix(String prefix) {
825 return userDeclaredNamespaces.get(prefix);
826 }
827
828 /**
829 * Set an external namespace resolver. If a namespace prefix cannot be resolved using any
830 * other mechanism, then as a last resort the external namespace resolver is called to
831 * obtain a URI for the given prefix.
832 * <p><i>Changed in Saxon 9.0 so that the namespaces resolved by the external namespace resolver
833 * are available at run-time, just like namespaces declared in the query prolog. In consequence,
834 * the supplied NamespaceResolver must now implement the
835 * {@link net.sf.saxon.om.NamespaceResolver#iteratePrefixes()} method.</i></p>
836 *
837 * @param resolver the external namespace resolver
838 */
839
840 public void setExternalNamespaceResolver(NamespaceResolver resolver) {
841 externalNamespaceResolver = resolver;
842 }
843
844 /**
845 * Get the external namespace resolver that has been registered using
846 * setExternalNamespaceResolver(), if any.
847 *
848 * @return the external namespace resolver
849 */
850
851 /*@Nullable*/
852 public NamespaceResolver getExternalNamespaceResolver() {
853 return externalNamespaceResolver;
854 }
855
856 /**
857 * Get the default function namespace
858 *
859 * @return the default function namespace (defaults to the fn: namespace)
860 * @since 8.4
861 */
862
863 public String getDefaultFunctionNamespace() {
864 return defaultFunctionNamespace;
865 }
866
867 /**
868 * Set the default function namespace
869 *
870 * @param defaultFunctionNamespace The namespace to be used for unprefixed function calls
871 * @since 8.4
872 */
873
874 public void setDefaultFunctionNamespace(String defaultFunctionNamespace) {
875 this.defaultFunctionNamespace = defaultFunctionNamespace;
876 }
877
878 /**
879 * Set the default element namespace
880 *
881 * @param uri the namespace URI to be used as the default namespace for elements and types
882 * @since 8.4
883 */
884
885 public void setDefaultElementNamespace(String uri) {
886 defaultElementNamespace = uri;
887 declareNamespace("", uri);
888 }
889
890 /**
891 * Get the default namespace for elements and types
892 *
893 * @return the namespace URI to be used as the default namespace for elements and types
894 * @since 8.9 Modified in 8.9 to return the namespace URI as a string rather than an integer code
895 */
896
897 /*@Nullable*/
898 public String getDefaultElementNamespace() {
899 return defaultElementNamespace;
900 }
901
902 /**
903 * Declare a global variable. This has the same effect as including a global variable declaration
904 * in the Query Prolog of the main query module. A static error occurs when compiling the query if the
905 * query prolog contains a declaration of the same variable.
906 *
907 * @param qName the qualified name of the variable
908 * @param type the declared type of the variable
909 * @param value the initial value of the variable. May be null if the variable is external.
910 * @param external true if the variable is external, that is, if its value may be set at run-time.
911 * @throws NullPointerException if the value is null, unless the variable is external
912 * @throws XPathException if the value of the variable is not consistent with its type.
913 * @since 9.1
914 */
915
916 public void declareGlobalVariable(
917 StructuredQName qName, SequenceType type, Sequence<?> value, boolean external)
918 throws XPathException {
919 if (value == null && !external) {
920 throw new NullPointerException("No initial value for declared variable");
921 }
922 if (value != null && !type.matches(value, getConfiguration().getTypeHierarchy())) {
923 throw new XPathException("Value of declared variable does not match its type");
924 }
925 GlobalVariable var = external ? new GlobalParam() : new GlobalVariable();
926
927 var.setVariableQName(qName);
928 var.setRequiredType(type);
929 if (value != null) {
930 var.setSelectExpression(Literal.makeLiteral(value.materialize()));
931 }
932 if (userDeclaredVariables == null) {
933 userDeclaredVariables = new HashSet<>();
934 }
935 userDeclaredVariables.add(var);
936 }
937
938 /**
939 * Iterate over all the declared global variables
940 *
941 * @return an iterator over all the global variables that have been declared. They are returned
942 * as instances of class {@link GlobalVariable}
943 * @since 9.1
944 */
945
946 public Iterator<GlobalVariable> iterateDeclaredGlobalVariables() {
947 if (userDeclaredVariables == null) {
948 List<GlobalVariable> empty = Collections.emptyList();
949 return empty.iterator();
950 } else {
951 return userDeclaredVariables.iterator();
952 }
953 }
954
955 /**
956 * Clear all declared global variables
957 *
958 * @since 9.1
959 */
960
961 public void clearDeclaredGlobalVariables() {
962 userDeclaredVariables = null;
963 }
964
965 /**
966 * Set a user-defined ModuleURIResolver for resolving URIs used in "import module"
967 * declarations in the XQuery prolog.
968 * This will be used for resolving URIs in XQuery "import module" declarations, overriding
969 * any ModuleURIResolver that was specified as part of the configuration.
970 *
971 * @param resolver the ModuleURIResolver to be used
972 */
973
974 public void setModuleURIResolver(ModuleURIResolver resolver) {
975 moduleURIResolver = resolver;
976 }
977
978 /**
979 * Get the user-defined ModuleURIResolver for resolving URIs used in "import module"
980 * declarations in the XQuery prolog; returns null if none has been explicitly set either
981 * on the StaticQueryContext or on the Configuration.
982 *
983 * @return the registered ModuleURIResolver
984 */
985
986 /*@Nullable*/
987 public ModuleURIResolver getModuleURIResolver() {
988 return moduleURIResolver;
989 }
990
991
992 /**
993 * Declare a named collation. Collations are only available in a query if this method
994 * has been called externally to declare the collation and associate it with an
995 * implementation, in the form of a Java Comparator. The default collation is the
996 * Unicode codepoint collation, unless otherwise specified.
997 *
998 * @param name The name of the collation (technically, a URI)
999 * @param comparator The Java Comparator used to implement the collating sequence
1000 * @since 8.4.
1001 * @deprecated since 9.6. All collations are now registered at the level of the
1002 * Configuration. If this method is called, the effect is that the supplied collation
1003 * is registered with the configuration
1004 */
1005
1006 public void declareCollation(String name, Comparator comparator) {
1007 getConfiguration().registerCollation(name, new SimpleCollation(name, comparator));
1008 }
1009
1010
1011 /**
1012 * Declare a named collation. Collations are only available in a query if this method
1013 * has been called externally to declare the collation and associate it with an
1014 * implementation, in the form of a Java StringCollator. The default collation is the
1015 * Unicode codepoint collation, unless otherwise specified.
1016 *
1017 * @param name The name of the collation (technically, a URI)
1018 * @param collation The Java Comparator used to implement the collating sequence
1019 * @since 8.9.
1020 * @deprecated since 9.6. All collations are now registered at the level of the
1021 * Configuration. If this method is called, the effect is that the supplied collation
1022 * is registered with the configuration
1023 */
1024
1025 public void declareCollation(String name, StringCollator collation) {
1026 getConfiguration().registerCollation(name, collation);
1027 }
1028
1029 /**
1030 * Set the default collation.
1031 *
1032 * @param name The collation name, as specified in the query prolog. Must be the name
1033 * of a known registered collation.
1034 * @throws NullPointerException if the supplied value is null
1035 * @throws IllegalStateException if the supplied value is not a known collation URI registered with the
1036 * configuration.
1037 * @since 8.4. Changed in 9.7.0.15 so that it validates the collation name: see bug 3121.
1038 */
1039
1040 public void declareDefaultCollation(String name) {
1041 if (name == null) {
1042 throw new NullPointerException();
1043 }
1044 StringCollator c;
1045 try {
1046 c = getConfiguration().getCollation(name);
1047 } catch (XPathException e) {
1048 c = null;
1049 }
1050 if (c == null) {
1051 throw new IllegalStateException("Unknown collation " + name);
1052 }
1053 this.defaultCollationName = name;
1054 }
1055
1056 /**
1057 * Get a named collation.
1058 *
1059 * @param name the name of the collation, as an absolute URI
1060 * @return the collation identified by the given name, as set previously using declareCollation.
1061 * If no collation with this name has been declared, the method calls the CollationURIResolver
1062 * to locate a collation with this name.
1063 * Return null if no collation with this name is found.
1064 * @throws NullPointerException if the collation name argument is null.
1065 * @since 8.4
1066 * @deprecated since 9.6. Collations are now all held globally at the level of the
1067 * Configuration. Calling this method will get the relevant collation held in the Configuration.
1068 */
1069
1070 public StringCollator getCollation(String name) {
1071 try {
1072 return getConfiguration().getCollation(name);
1073 } catch (XPathException e) {
1074 getErrorListener().warning(e);
1075 return null;
1076 }
1077 }
1078
1079 /**
1080 * Get the name of the default collation.
1081 *
1082 * @return the name of the default collation; or the name of the codepoint collation
1083 * if no default collation has been defined. The name is returned in the form
1084 * it was specified; that is, it is not yet resolved against the base URI. (This
1085 * is because the base URI declaration can follow the default collation declaration
1086 * in the query prolog.) If no default collation has been specified, the "default default"
1087 * (that is, the Unicode codepoint collation) is returned.
1088 * @since 8.4
1089 */
1090
1091 /*@Nullable*/
1092 public String getDefaultCollationName() {
1093 return defaultCollationName;
1094 }
1095
1096 /**
1097 * Declare the static type of the context item. If this type is declared, and if a context item
1098 * is supplied when the query is invoked, then the context item must conform to this type (no
1099 * type conversion will take place to force it into this type).
1100 *
1101 * @param type the required type of the context item
1102 */
1103
1104 public void setRequiredContextItemType(ItemType type) {
1105 requiredContextItemType = type;
1106 }
1107
1108 /**
1109 * Get the required type of the context item. If no type has been explicitly declared for the context
1110 * item, an instance of AnyItemType (representing the type item()) is returned.
1111 *
1112 * @return the required type of the context item
1113 */
1114
1115 public ItemType getRequiredContextItemType() {
1116 return requiredContextItemType;
1117 }
1118
1119 /**
1120 * Get the NamePool used for compiling expressions
1121 *
1122 * @return the name pool
1123 * @since 8.4
1124 */
1125
1126 public NamePool getNamePool() {
1127 return namePool;
1128 }
1129
1130 /**
1131 * Get the system ID of the container of the expression. Used to construct error messages.
1132 * Note that the systemID and the Base URI are currently identical, but they might be distinguished
1133 * in the future.
1134 *
1135 * @return the Base URI
1136 * @since 8.4
1137 */
1138
1139 public String getSystemId() {
1140 return baseURI;
1141 }
1142
1143 /**
1144 * Get the Base URI of the query, for resolving any relative URI's used
1145 * in the expression.
1146 * Note that the systemID and the Base URI are currently identical, but they might be distinguished
1147 * in the future.
1148 * Used by the document() function.
1149 *
1150 * @return the base URI of the query
1151 * @since 8.4
1152 */
1153
1154 public String getBaseURI() {
1155 return baseURI;
1156 }
1157
1158 /**
1159 * Set the policy for preserving boundary space
1160 *
1161 * @param preserve true if boundary space is to be preserved, false if it is to be stripped
1162 * @since 9.0
1163 */
1164
1165 public void setPreserveBoundarySpace(boolean preserve) {
1166 preserveSpace = preserve;
1167 }
1168
1169 /**
1170 * Ask whether the policy for boundary space is "preserve" or "strip"
1171 *
1172 * @return true if the policy is to preserve boundary space, false if it is to strip it
1173 * @since 9.0
1174 */
1175
1176 public boolean isPreserveBoundarySpace() {
1177 return preserveSpace;
1178 }
1179
1180 /**
1181 * Set the option for where an empty sequence appears in the collation order, if not otherwise
1182 * specified in the "order by" clause
1183 *
1184 * @param least true if the empty sequence is considered less than any other value (the default),
1185 * false if it is considered greater than any other value
1186 * @since 9.0
1187 */
1188
1189 public void setEmptyLeast(boolean least) {
1190 defaultEmptyLeast = least;
1191 }
1192
1193 /**
1194 * Ask where an empty sequence should appear in the collation order, if not otherwise
1195 * specified in the "order by" clause
1196 *
1197 * @return true if the empty sequence is considered less than any other value (the default),
1198 * false if it is considered greater than any other value
1199 * @since 9.0
1200 */
1201
1202 public boolean isEmptyLeast() {
1203 return defaultEmptyLeast;
1204 }
1205
1206 /**
1207 * Set the ErrorListener to be used to report compile-time errors in a query. This will also
1208 * be the default for the run-time error listener used to report dynamic errors.
1209 * <p>If the supplied listener is a StandardErrorListener, then a new copy will be made
1210 * using {@link StandardErrorListener#makeAnother(int)}</p>
1211 * <p>If the supplied listener is not an {@link UnfailingErrorListener}, then it will be wrapped
1212 * in a {@link DelegatingErrorListener}.</p>
1213 *
1214 * @param listener the ErrorListener to be used
1215 */
1216
1217 public void setErrorListener(ErrorListener listener) {
1218 if (listener instanceof StandardErrorListener) {
1219 errorListener = ((StandardErrorListener) listener).makeAnother(Configuration.XQUERY);
1220 ((StandardErrorListener) errorListener).setRecoveryPolicy(Configuration.DO_NOT_RECOVER);
1221 } else if (listener instanceof UnfailingErrorListener) {
1222 errorListener = (UnfailingErrorListener) listener;
1223 } else {
1224 errorListener = new DelegatingErrorListener(listener);
1225 }
1226 }
1227
1228 /**
1229 * Get the ErrorListener in use for this static context
1230 *
1231 * @return the registered ErrorListener
1232 */
1233
1234 public UnfailingErrorListener getErrorListener() {
1235 if (errorListener == null) {
1236 errorListener = config.getErrorListener();
1237 }
1238 return errorListener;
1239 }
1240
1241 /**
1242 * Say whether the query is allowed to be updating. XQuery update syntax will be rejected
1243 * during query compilation unless this flag is set.
1244 *
1245 * @param updating true if the query is allowed to use the XQuery Update facility
1246 * (requires Saxon-EE). If set to false, the query must not be an updating query. If set
1247 * to true, it may be either an updating or a non-updating query.
1248 * @since 9.1
1249 */
1250
1251 public void setUpdatingEnabled(boolean updating) {
1252 isUpdating = updating;
1253 }
1254
1255 /**
1256 * Ask whether the query is allowed to be updating
1257 *
1258 * @return true if the query is allowed to use the XQuery Update facility. Note that this
1259 * does not necessarily mean that the query is an updating query; but if the value is false,
1260 * the it must definitely be non-updating.
1261 * @since 9.1
1262 */
1263
1264 public boolean isUpdatingEnabled() {
1265 return isUpdating;
1266 }
1267
1268 }
1269