Debian Codegraph @

net/sf/saxon/sxpath/IndependentContext.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.sxpath;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.Expression;
12 import net.sf.saxon.expr.LocalVariableReference;
13 import net.sf.saxon.expr.PackageData;
14 import net.sf.saxon.expr.instruct.Executable;
15 import net.sf.saxon.expr.instruct.SlotManager;
16 import net.sf.saxon.expr.parser.OptimizerOptions;
17 import net.sf.saxon.expr.parser.RetainedStaticContext;
18 import net.sf.saxon.functions.FunctionLibraryList;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.om.AxisInfo;
21 import net.sf.saxon.om.NamespaceResolver;
22 import net.sf.saxon.om.NodeInfo;
23 import net.sf.saxon.om.StructuredQName;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.tree.iter.AxisIterator;
26 import net.sf.saxon.type.AnyItemType;
27 import net.sf.saxon.type.ItemType;
28 import net.sf.saxon.type.Type;
29 import net.sf.saxon.value.QNameValue;
30
31 import java.util.*;
32
33 /**
34 * An IndependentContext provides a context for parsing an XPath expression appearing
35 * in a context other than a stylesheet.
36 * <p>This class is used in a number of places where freestanding XPath expressions occur.
37 * These include the native Saxon XPath API, the .NET XPath API, XPath expressions used
38 * in XML Schema identity constraints, and XPath expressions supplied to saxon:evaluate().
39 * It is not used by the JAXP XPath API (though it shares code with that API through
40 * the common superclass AbstractStaticContext).</p>
41 * <p>This class currently provides no mechanism for binding user-defined functions.</p>
42 */
43
44 public class IndependentContext extends AbstractStaticContext
45 implements XPathStaticContext, NamespaceResolver {
46
47 protected HashMap<String, String> namespaces = new HashMap<String, String>(10);
48 protected HashMap<StructuredQName, XPathVariable> variables = new HashMap<StructuredQName, XPathVariable>(20);
49 protected NamespaceResolver externalResolver = null;
50 protected ItemType requiredContextItemType = AnyItemType.getInstance();
51 protected Set<String> importedSchemaNamespaces = new HashSet<String>();
52 protected boolean autoDeclare = false;
53 protected Executable executable;
54 protected RetainedStaticContext retainedStaticContext;
55 protected OptimizerOptions optimizerOptions;
56
57
58 /**
59 * Create an IndependentContext along with a new (non-schema-aware) Saxon Configuration
60 */
61
62 public IndependentContext() {
63 this(new Configuration());
64 }
65
66 /**
67 * Create an IndependentContext using a specific Configuration
68 *
69 * @param config the Saxon configuration to be used
70 */
71
72 public IndependentContext(Configuration config) {
73 setConfiguration(config);
74 clearNamespaces();
75 setDefaultFunctionLibrary(31);
76 usingDefaultFunctionLibrary = true;
77 setDefaultCollationName(config.getDefaultCollationName());
78 setOptimizerOptions(config.getOptimizerOptions());
79 PackageData pd = new PackageData(config);
80 pd.setHostLanguage(Configuration.XPATH);
81 pd.setSchemaAware(false);
82 setPackageData(pd);
83 }
84
85 /**
86 * Create a IndependentContext as a copy of another IndependentContext
87 *
88 * @param ic the IndependentContext to be copied
89 */
90
91 public IndependentContext(IndependentContext ic) {
92 this(ic.getConfiguration());
93 setPackageData(ic.getPackageData());
94 setBaseURI(ic.getStaticBaseURI());
95 setContainingLocation(ic.getContainingLocation());
96 setDefaultElementNamespace(ic.getDefaultElementNamespace());
97 setDefaultFunctionNamespace(ic.getDefaultFunctionNamespace());
98 setBackwardsCompatibilityMode(ic.isInBackwardsCompatibleMode());
99 namespaces = new HashMap<String, String>(ic.namespaces);
100 variables = new HashMap<StructuredQName, XPathVariable>(10);
101 FunctionLibraryList libList = (FunctionLibraryList) ic.getFunctionLibrary();
102 if (libList != null) {
103 setFunctionLibrary((FunctionLibraryList) libList.copy());
104 }
105 setImportedSchemaNamespaces(ic.importedSchemaNamespaces);
106 externalResolver = ic.externalResolver;
107 autoDeclare = ic.autoDeclare;
108 setXPathLanguageLevel(ic.getXPathVersion());
109 requiredContextItemType = ic.requiredContextItemType;
110 setExecutable(ic.getExecutable());
111 }
112
113 /**
114 * Construct a RetainedStaticContext, which extracts information from this StaticContext
115 * to provide the subset of static context information that is potentially needed
116 * during expression evaluation.
117 *
118 * This implementation returns the same RetainedStaticContext object each time, which relies
119 * on the information in the static context being effectively immutable while the IndependentContext
120 * object remains in use.
121 *
122 * @return a RetainedStaticContext object: either a newly created one, or one that is
123 * reused from a previous invocation.
124 */
125 @Override
126 public RetainedStaticContext makeRetainedStaticContext() {
127 if (retainedStaticContext == null) {
128 retainedStaticContext = new RetainedStaticContext(this);
129 }
130 return retainedStaticContext;
131 }
132
133 /**
134 * Declare a namespace whose prefix can be used in expressions
135 *
136 * @param prefix The namespace prefix. Must not be null. Supplying "" sets the
137 * default element namespace.
138 * @param uri The namespace URI. Must not be null.
139 */
140
141 public void declareNamespace(String prefix, String uri) {
142 if (prefix == null) {
143 throw new NullPointerException("Null prefix supplied to declareNamespace()");
144 }
145 if (uri == null) {
146 throw new NullPointerException("Null namespace URI supplied to declareNamespace()");
147 }
148 if ("".equals(prefix)) {
149 setDefaultElementNamespace(uri);
150 } else {
151 namespaces.put(prefix, uri);
152 }
153 }
154
155 /**
156 * Set the default namespace for elements and types
157 *
158 * @param uri the namespace to be used for unprefixed element and type names.
159 * The value "" (or NamespaceConstant.NULL) represents the non-namespace
160 */
161
162 @Override
163 public void setDefaultElementNamespace(String uri) {
164 if (uri == null) {
165 uri = "";
166 }
167 super.setDefaultElementNamespace(uri);
168 namespaces.put("", uri);
169 }
170
171 /**
172 * Clear all the declared namespaces, except for the standard ones (xml, xsl, saxon).
173 * This also resets the default element namespace to the "null" namespace
174 */
175
176 public void clearNamespaces() {
177 namespaces.clear();
178 declareNamespace("xml", NamespaceConstant.XML);
179 declareNamespace("xsl", NamespaceConstant.XSLT);
180 declareNamespace("saxon", NamespaceConstant.SAXON);
181 declareNamespace("xs", NamespaceConstant.SCHEMA);
182 declareNamespace("", "");
183 }
184
185 /**
186 * Clear all the declared namespaces, including the standard ones (xml, xslt, saxon).
187 * Leave only the XML namespace and the default namespace (xmlns="").
188 * This also resets the default element namespace to the "null" namespace.
189 */
190
191 public void clearAllNamespaces() {
192 namespaces.clear();
193 declareNamespace("xml", NamespaceConstant.XML);
194 declareNamespace("", "");
195 }
196
197 /**
198 * Declares all the namespaces that are in-scope for a given node, removing all previous
199 * namespace declarations.
200 * In addition, the standard namespaces (xml, xslt, saxon) are declared. This method also
201 * sets the default element namespace to be the same as the default namespace for this node.
202 *
203 * @param node The node whose in-scope namespaces are to be used as the context namespaces.
204 * If the node is an attribute, text node, etc, then the namespaces of its parent element are used.
205 */
206
207 public void setNamespaces(NodeInfo node) {
208 namespaces.clear();
209 int kind = node.getNodeKind();
210 if (kind == Type.ATTRIBUTE || kind == Type.TEXT ||
211 kind == Type.COMMENT || kind == Type.PROCESSING_INSTRUCTION ||
212 kind == Type.NAMESPACE) {
213 node = node.getParent();
214 }
215 if (node == null) {
216 return;
217 }
218
219 AxisIterator iter = node.iterateAxis(AxisInfo.NAMESPACE);
220 while (true) {
221 NodeInfo ns = iter.next();
222 if (ns == null) {
223 return;
224 }
225 String prefix = ns.getLocalPart();
226 if ("".equals(prefix)) {
227 setDefaultElementNamespace(ns.getStringValue());
228 } else {
229 declareNamespace(ns.getLocalPart(), ns.getStringValue());
230 }
231 }
232 }
233
234 /**
235 * Set an external namespace resolver. If this is set, then all resolution of namespace
236 * prefixes is delegated to the external namespace resolver, and namespaces declared
237 * individually on this IndependentContext object are ignored.
238 *
239 * @param resolver the external NamespaceResolver
240 */
241
242 public void setNamespaceResolver(NamespaceResolver resolver) {
243 externalResolver = resolver;
244 }
245
246 /**
247 * Say whether undeclared variables are allowed. By default, they are not allowed. When
248 * undeclared variables are allowed, it is not necessary to predeclare the variables that
249 * may be used in the XPath expression; instead, a variable is automatically declared when a reference
250 * to the variable is encountered within the expression.
251 *
252 * @param allow true if undeclared variables are allowed, false if they are not allowed.
253 * @since 9.2
254 */
255
256 public void setAllowUndeclaredVariables(boolean allow) {
257 autoDeclare = allow;
258 }
259
260 /**
261 * Ask whether undeclared variables are allowed. By default, they are not allowed. When
262 * undeclared variables are allowed, it is not necessary to predeclare the variables that
263 * may be used in the XPath expression; instead, a variable is automatically declared when a reference
264 * to the variable is encountered within the expression.
265 *
266 * @return true if undeclared variables are allowed, false if they are not allowed.
267 * @since 9.2
268 */
269
270 public boolean isAllowUndeclaredVariables() {
271 return autoDeclare;
272 }
273
274 /**
275 * Declare a variable. A variable must be declared before an expression referring
276 * to it is compiled. The initial value of the variable will be the empty sequence
277 *
278 * @param qname The name of the variable
279 * @return an XPathVariable object representing information about the variable that has been
280 * declared.
281 */
282
283 public XPathVariable declareVariable(QNameValue qname) {
284 return declareVariable(qname.getStructuredQName());
285 }
286
287 /**
288 * Declare a variable. A variable must be declared before an expression referring
289 * to it is compiled. The initial value of the variable will be the empty sequence
290 *
291 * @param namespaceURI The namespace URI of the name of the variable. Supply "" to represent
292 * names in no namespace (null is also accepted)
293 * @param localName The local part of the name of the variable (an NCName)
294 * @return an XPathVariable object representing information about the variable that has been
295 * declared.
296 */
297
298 public XPathVariable declareVariable(String namespaceURI, String localName) {
299 StructuredQName qName = new StructuredQName("", namespaceURI, localName);
300 return declareVariable(qName);
301 }
302
303 /**
304 * Declare a variable. A variable must be declared before an expression referring
305 * to it is compiled. The initial value of the variable will be the empty sequence
306 *
307 * @param qName the name of the variable.
308 * @return an XPathVariable object representing information about the variable that has been
309 * declared.
310 * @since 9.2
311 */
312
313
314 public XPathVariable declareVariable(StructuredQName qName) {
315 XPathVariable var = variables.get(qName);
316 if (var != null) {
317 return var;
318 } else {
319 var = XPathVariable.make(qName);
320 int slot = variables.size();
321 var.setSlotNumber(slot);
322 variables.put(qName, var);
323 return var;
324 }
325 }
326
327 /**
328 * Get an iterator over all the variables that have been declared, either explicitly by an
329 * application call on declareVariable(), or implicitly if the option <code>allowUndeclaredVariables</code>
330 * is set.
331 *
332 * @return an iterator; the objects returned by this iterator will be instances of XPathVariable
333 * @since 9.2
334 */
335
336 public Iterator<XPathVariable> iterateExternalVariables() {
337 return variables.values().iterator();
338 }
339
340 /**
341 * Get the declared variable with a given name, if there is one
342 *
343 * @param qName the name of the required variable
344 * @return the explicitly or implicitly declared variable with this name if it exists,
345 * or null otherwise
346 * @since 9.2
347 */
348
349 public XPathVariable getExternalVariable(StructuredQName qName) {
350 return variables.get(qName);
351 }
352
353 /**
354 * Get the slot number allocated to a particular variable
355 *
356 * @param qname the name of the variable
357 * @return the slot number, or -1 if the variable has not been declared
358 */
359
360 public int getSlotNumber(QNameValue qname) {
361 StructuredQName sq = qname.getStructuredQName();
362 XPathVariable var = variables.get(sq);
363 if (var == null) {
364 return -1;
365 }
366 return var.getLocalSlotNumber();
367 }
368
369 public NamespaceResolver getNamespaceResolver() {
370 if (externalResolver != null) {
371 return externalResolver;
372 } else {
373 return this;
374 }
375 }
376
377
378 /**
379 * Get the namespace URI corresponding to a given prefix. Return null
380 * if the prefix is not in scope.
381 *
382 * @param prefix the namespace prefix
383 * @param useDefault true if the default namespace is to be used when the
384 * prefix is ""
385 * @return the uri for the namespace, or null if the prefix is not in scope.
386 * Return "" if the prefix maps to the null namespace.
387 */
388
389 public String getURIForPrefix(String prefix, boolean useDefault) {
390 if (externalResolver != null) {
391 return externalResolver.getURIForPrefix(prefix, useDefault);
392 }
393 if (prefix.isEmpty()) {
394 return useDefault ? getDefaultElementNamespace() : "";
395 } else {
396 return namespaces.get(prefix);
397 }
398 }
399
400 /**
401 * Get an iterator over all the prefixes declared in this namespace context. This will include
402 * the default namespace (prefix="") and the XML namespace where appropriate
403 */
404
405 public Iterator<String> iteratePrefixes() {
406 if (externalResolver != null) {
407 return externalResolver.iteratePrefixes();
408 } else {
409 return namespaces.keySet().iterator();
410 }
411 }
412
413 /**
414 * Bind a variable used in an XPath Expression to the XSLVariable element in which it is declared.
415 * This method is provided for use by the XPath parser, and it should not be called by the user of
416 * the API, or overridden, unless variables are to be declared using a mechanism other than the
417 * declareVariable method of this class.
418 *
419 * @param qName the name of the variable
420 * @return the resulting variable reference
421 */
422
423 public Expression bindVariable(StructuredQName qName) throws XPathException {
424 XPathVariable var = variables.get(qName);
425 if (var == null) {
426 if (autoDeclare) {
427 return new LocalVariableReference(declareVariable(qName));
428 } else {
429 throw new XPathException("Undeclared variable in XPath expression: $" + qName.getClarkName(), "XPST0008");
430 }
431 } else {
432 return new LocalVariableReference(var);
433 }
434 }
435
436 /**
437 * Get a Stack Frame Map containing definitions of all the declared variables. This will return a newly
438 * created object that the caller is free to modify by adding additional variables, without affecting
439 * the static context itself.
440 */
441
442 public SlotManager getStackFrameMap() {
443 SlotManager map = getConfiguration().makeSlotManager();
444 XPathVariable[] va = new XPathVariable[variables.size()];
445
446 for (XPathVariable var : variables.values()) {
447 va[var.getLocalSlotNumber()] = var;
448 }
449 for (XPathVariable v : va) {
450 map.allocateSlotNumber(v.getVariableQName());
451 }
452 return map;
453 }
454
455 public Collection<XPathVariable> getDeclaredVariables() {
456 return variables.values();
457 }
458
459
460 public boolean isImportedSchema(String namespace) {
461 return importedSchemaNamespaces.contains(namespace);
462 }
463
464 /**
465 * Get the set of imported schemas
466 *
467 * @return a Set, the set of URIs representing the names of imported schemas
468 */
469
470 public Set<String> getImportedSchemaNamespaces() {
471 return importedSchemaNamespaces;
472 }
473
474 /**
475 * Register the set of imported schema namespaces
476 *
477 * @param namespaces the set of namespaces for which schema components are available in the
478 * static context
479 */
480
481 public void setImportedSchemaNamespaces(Set<String> namespaces) {
482 importedSchemaNamespaces = namespaces;
483 if (!namespaces.isEmpty()) {
484 setSchemaAware(true);
485 }
486 }
487
488 /**
489 * Declare the static type of the context item. If this type is declared, and if a context item
490 * is supplied when the query is invoked, then the context item must conform to this type (no
491 * type conversion will take place to force it into this type).
492 *
493 * @param type the required type of the context item
494 * @since 9.3
495 */
496
497 public void setRequiredContextItemType(ItemType type) {
498 requiredContextItemType = type;
499 }
500
501 /**
502 * Get the required type of the context item. If no type has been explicitly declared for the context
503 * item, an instance of AnyItemType (representing the type item()) is returned.
504 *
505 * @return the required type of the context item
506 * @since 9.3
507 */
508
509 public ItemType getRequiredContextItemType() {
510 return requiredContextItemType;
511 }
512
513 /**
514 * Set the optimizer options to be used for compiling expressions that use this static context.
515 * By default the optimizer options set in the {@link Configuration} are used.
516 * @param options the optimizer options to be used
517 */
518
519 public void setOptimizerOptions(OptimizerOptions options) {
520 this.optimizerOptions = options;
521 }
522
523 /**
524 * Get the optimizer options being used for compiling expressions that use this static context.
525 * By default the optimizer options set in the {@link Configuration} are used.
526 *
527 * @return the optimizer options being used
528 */
529
530 public OptimizerOptions getOptimizerOptions() {
531 return this.optimizerOptions;
532 }
533
534 public void setExecutable(Executable exec) {
535 executable = exec;
536 }
537
538 /*@Nullable*/
539 public Executable getExecutable() {
540 return executable;
541 }
542
543
544 public int getColumnNumber() {
545 return -1;
546 }
547
548 public String getPublicId() {
549 return null;
550 }
551
552 public int getLineNumber() {
553 return -1;
554 }
555
556 }
557