Debian Codegraph @

net/sf/saxon/style/ExpressionContext.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.style;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.instruct.GlobalVariable;
13 import net.sf.saxon.expr.parser.Location;
14 import net.sf.saxon.expr.parser.OptimizerOptions;
15 import net.sf.saxon.expr.parser.RetainedStaticContext;
16 import net.sf.saxon.functions.FunctionLibrary;
17 import net.sf.saxon.functions.FunctionLibraryList;
18 import net.sf.saxon.functions.SystemFunction;
19 import net.sf.saxon.functions.registry.VendorFunctionSetHE;
20 import net.sf.saxon.lib.Feature;
21 import net.sf.saxon.lib.NamespaceConstant;
22 import net.sf.saxon.om.*;
23 import net.sf.saxon.pattern.NameTest;
24 import net.sf.saxon.trans.*;
25 import net.sf.saxon.tree.AttributeLocation;
26 import net.sf.saxon.tree.iter.AxisIterator;
27 import net.sf.saxon.type.AnyItemType;
28 import net.sf.saxon.type.ItemType;
29 import net.sf.saxon.type.Type;
30
31 import java.util.Set;
32
33 /**
34 * An ExpressionContext represents the context for an XPath expression written
35 * in the stylesheet.
36 */
37
38 public class ExpressionContext implements XSLTStaticContext {
39
40 private StyleElement element;
41 private StructuredQName attributeName;
42 private Location containingLocation = null;
43 private NamespaceResolver namespaceResolver = null;
44 private RetainedStaticContext retainedStaticContext = null;
45
46
47 /**
48 * Create a static context for XPath expressions in an XSLT stylesheet
49 *
50 * @param styleElement the element on which the XPath expression appears
51 * @param attributeName the name of the attribute in which the XPath expression appears; or null
52 * if the expression appears in a text node
53 */
54
55 public ExpressionContext(StyleElement styleElement, StructuredQName attributeName) {
56 element = styleElement;
57 this.attributeName = attributeName;
58 }
59
60 /**
61 * Get the system configuration
62 */
63
64 public Configuration getConfiguration() {
65 return element.getConfiguration();
66 }
67
68 /**
69 * Get the containing XSLT package
70 * @return the containing XSLT package
71 */
72
73 public StylesheetPackage getPackageData() {
74 return element.getPackageData();
75 }
76
77 /**
78 * Ask whether expressions compiled under this static context are schema-aware.
79 * They must be schema-aware if the expression is to handle typed (validated) nodes
80 *
81 * @return true if expressions are schema-aware
82 */
83 public boolean isSchemaAware() {
84 return element.isSchemaAware();
85 }
86
87 /**
88 * Construct a dynamic context for early evaluation of constant subexpressions
89 */
90
91 public XPathContext makeEarlyEvaluationContext() {
92 return new EarlyEvaluationContext(getConfiguration());
93 }
94
95 /**
96 * Construct a RetainedStaticContext, which extracts information from this StaticContext
97 * to provide the subset of static context information that is potentially needed
98 * during expression evaluation
99 *
100 * @return a RetainedStaticContext object: either a newly created one, or one that is
101 * reused from a previous invocation.
102 */
103 public RetainedStaticContext makeRetainedStaticContext() {
104 if (retainedStaticContext == null) {
105 if (element.changesRetainedStaticContext() || !(element.getParent() instanceof StyleElement)) {
106 retainedStaticContext = new RetainedStaticContext(this);
107 } else {
108 retainedStaticContext = ((StyleElement) element.getParent()).getStaticContext().makeRetainedStaticContext();
109 }
110 }
111 return retainedStaticContext;
112 }
113
114 /**
115 * Get the containing location of an XPath expression within the stylesheet
116 *
117 * @return a Location that identifies the containing element, together with the name of the
118 * attribute holding the XPath expression in question.
119 */
120
121 public Location getContainingLocation() {
122 if (containingLocation == null) {
123 if (attributeName == null) {
124 containingLocation = element;
125 } else {
126 containingLocation = new AttributeLocation(element, attributeName);
127 }
128 }
129 return containingLocation;
130 }
131
132 /**
133 * Issue a compile-time warning
134 */
135
136 public void issueWarning(String s, Location locator) {
137 element.issueWarning(new XPathException(s, SaxonErrorCode.SXWN9000, locator));
138 }
139
140 /**
141 * Get the System ID of the entity containing the expression (used for diagnostics)
142 */
143
144 public String getSystemId() {
145 return element.getSystemId();
146 }
147
148 /**
149 * Get the Base URI of the element containing the expression, for resolving any
150 * relative URI's used in the expression.
151 * Used by the document() function.
152 */
153
154 public String getStaticBaseURI() {
155 return element.getBaseURI();
156 }
157
158 /**
159 * Get a copy of the NamespaceResolver suitable for saving in the executable code
160 *
161 * @return a NamespaceResolver
162 */
163
164
165 public NamespaceResolver getNamespaceResolver() {
166 if (namespaceResolver == null) {
167 namespaceResolver = element.makeNamespaceContext();
168 }
169 return namespaceResolver;
170 }
171
172 /**
173 * Get the required type of the context item. If no type has been explicitly declared for the context
174 * item, an instance of AnyItemType (representing the type item()) is returned.
175 *
176 * @return the required type of the context item
177 * @since 9.3
178 */
179
180 public ItemType getRequiredContextItemType() {
181 return AnyItemType.getInstance();
182 }
183
184 /**
185 * Get a DecimalFormatManager to resolve the names of decimal formats used in calls
186 * to the format-number() function.
187 *
188 * @return the decimal format manager for this static context, or null if named decimal
189 * formats are not supported in this environment.
190 */
191
192 public DecimalFormatManager getDecimalFormatManager() {
193 return element.getCompilation().getPrincipalStylesheetModule().getDecimalFormatManager();
194 }
195
196 /**
197 * Get the optimization options in use. By default these are taken from the
198 * {@link Configuration}
199 *
200 * @return the optimization options in use
201 * @since 9.9
202 */
203
204 @Override
205 public OptimizerOptions getOptimizerOptions() {
206 return element.getCompilation().getCompilerInfo().getOptimizerOptions();
207 }
208
209 /**
210 * Bind a variable to an object that can be used to refer to it
211 *
212 * @param qName the name of the variable
213 * @return a VariableDeclaration object that can be used to identify it in the Bindery,
214 * @throws XPathException if the variable has not been declared
215 */
216
217 public Expression bindVariable(StructuredQName qName) throws XPathException {
218 SourceBinding sourceBinding = element.bindVariable(qName);
219 if (sourceBinding == null) {
220 if (qName.hasURI(NamespaceConstant.XSLT) && qName.getLocalPart().equals("original")) {
221 element.getXslOriginal(StandardNames.XSL_VARIABLE);
222 return new GlobalVariableReference(qName);
223 }
224 // it might have been declared in an imported package or query
225 SymbolicName sn = new SymbolicName(StandardNames.XSL_VARIABLE, qName);
226 Component comp = element.getCompilation().getPrincipalStylesheetModule().getComponent(sn);
227 if (comp != null) { // test variable-0118
228 // See tests variable-0118 and variable-0120
229 element.iterateAxis(AxisInfo.ANCESTOR_OR_SELF).forEachOrFail(parent -> {
230 if (parent instanceof XSLGlobalVariable && ((XSLGlobalVariable) parent).getVariableQName().equals(qName)) {
231 XPathException err = new XPathException("Variable " + qName.getDisplayName() +
232 " cannot be used within its own declaration", "XPST0008");
233 err.setIsStaticError(true);
234 throw err;
235 }
236 });
237
238 GlobalVariable var = (GlobalVariable) comp.getActor();
239 GlobalVariableReference vref = new GlobalVariableReference(var);
240 vref.setStaticType(var.getRequiredType(), null, 0);
241 return vref;
242 }
243 // it might be an implicit error variable in try/catch
244 if (getXPathVersion() >= 30 && qName.hasURI(NamespaceConstant.ERR)) {
245 AxisIterator catchers = element.iterateAxis(AxisInfo.ANCESTOR_OR_SELF,
246 new NameTest(Type.ELEMENT, StandardNames.XSL_CATCH, element.getNamePool()));
247 StyleElement catcher = (StyleElement) catchers.next();
248 if (catcher != null) {
249 for (StructuredQName errorVariable : StandardNames.errorVariables) {
250 if (errorVariable.getLocalPart().equals(qName.getLocalPart())) {
251 SystemFunction f = VendorFunctionSetHE.getInstance().makeFunction("dynamic-error-info", 1);
252 return f.makeFunctionCall(new StringLiteral(qName.getLocalPart()));
253 }
254 }
255 }
256 }
257
258 XPathException err = new XPathException("Variable " + qName.getDisplayName() +
259 " has not been declared (or its declaration is not in scope)", "XPST0008");
260 err.setIsStaticError(true);
261 throw err;
262 }
263
264 VariableReference var;
265 if (sourceBinding.hasProperty(SourceBinding.IMPLICITLY_DECLARED)) {
266 // Used for the $value variable in xsl:accumulator-rule
267 SuppliedParameterReference supRef = new SuppliedParameterReference(0);
268 supRef.setSuppliedType(sourceBinding.getDeclaredType());
269 return supRef;
270 }
271 if (sourceBinding.hasProperty(SourceBinding.GLOBAL)) {
272 var = new GlobalVariableReference(qName);
273 //SourceBinding binding = ((XSLGlobalVariable) sourceBinding.getSourceElement()).sourceBinding;
274 GlobalVariable compiledVar = ((XSLGlobalVariable) sourceBinding.getSourceElement()).getCompiledVariable();
275 if (compiledVar != null && element.getCompilation().getCompilerInfo().isJustInTimeCompilation()) {
276 var.fixup(compiledVar);
277 var.setStaticType(compiledVar.getRequiredType(), sourceBinding.getConstantValue(), 0);
278 } else {
279 sourceBinding.registerReference(var);
280 }
281 return var;
282 } else {
283 var = new LocalVariableReference(qName);
284 sourceBinding.registerReference(var);
285 return var;
286 }
287
288 }
289
290 /**
291 * Get the function library containing all the in-scope functions available in this static
292 * context
293 */
294
295 public FunctionLibrary getFunctionLibrary() {
296 FunctionLibrary lib = element.getContainingPackage().getFunctionLibrary();
297 StyleElement containingOverride = element.findAncestorElement(StandardNames.XSL_OVERRIDE);
298 if (containingOverride != null) {
299 // Within xsl:override, recognize the function name xsl:original
300 FunctionLibraryList libList = new FunctionLibraryList();
301 libList.addFunctionLibrary(lib);
302 ((XSLOverride)containingOverride).addXSLOverrideFunctionLibrary(libList);
303 return libList;
304 }
305 return lib;
306 }
307
308 /**
309 * Determine if an extension element is available
310 *
311 * @throws XPathException if the name is invalid or the prefix is not declared
312 */
313
314 public boolean isElementAvailable(String qname) throws XPathException {
315 try {
316 String[] parts = NameChecker.getQNameParts(qname);
317 String uri;
318 if (parts[0].isEmpty()) {
319 uri = getDefaultElementNamespace();
320 } else {
321 uri = element.getURIForPrefix(parts[0], false);
322 }
323 return element.getCompilation().getStyleNodeFactory(true).isElementAvailable(uri, parts[1], true);
324 } catch (QNameException e) {
325 XPathException err = new XPathException("Invalid element name. " + e.getMessage());
326 err.setErrorCode("XTDE1440");
327 throw err;
328 }
329 }
330
331 /**
332 * Get the default collation. Return null if no default collation has been defined
333 */
334
335 public String getDefaultCollationName() {
336 return element.getDefaultCollationName();
337 }
338
339 /**
340 * Get the default XPath namespace for elements and types
341 * Return NamespaceConstant.NULL for the non-namespace
342 */
343
344 public String getDefaultElementNamespace() {
345 return element.getDefaultXPathNamespace();
346 }
347
348 /**
349 * Get the default function namespace
350 */
351
352 public String getDefaultFunctionNamespace() {
353 return NamespaceConstant.FN;
354 }
355
356 /**
357 * Determine whether Backwards Compatible Mode is used
358 */
359
360 public boolean isInBackwardsCompatibleMode() {
361 return element.xPath10ModeIsEnabled();
362 }
363
364 /**
365 * Get the XPath language level supported, as an integer (being the actual version
366 * number times ten). In Saxon 9.9, for XSLT, the possible values are
367 * 30 (XPath 3.0), 31 (XPath 3.1), and 305 (XPath 3.0 plus the extensions defined in XSLT 3.0).
368 *
369 * @return the XPath language level; the return value will be either 30, 305, or 31
370 * @since 9.7
371 */
372
373 public int getXPathVersion() {
374 return getConfiguration().getConfigurationProperty(Feature.XPATH_VERSION_FOR_XSLT);
375 }
376
377 /**
378 * Test whether a schema has been imported for a given namespace
379 *
380 * @param namespace the target namespace of the required schema
381 * @return true if a schema for this namespace has been imported
382 */
383
384 public boolean isImportedSchema(String namespace) {
385 //if (Configuration.USE_PACKAGE_BINDING) {
386 return element.getPrincipalStylesheetModule().isImportedSchema(namespace);
387 //} else {
388 // return getConfiguration().
389 //}
390 }
391
392 /**
393 * Get the set of imported schemas
394 *
395 * @return a Set, the set of URIs representing the names of imported schemas
396 */
397
398 public Set<String> getImportedSchemaNamespaces() {
399 return element.getPrincipalStylesheetModule().getImportedSchemaTable();
400 }
401
402 /**
403 * Get the KeyManager, containing definitions of keys available for use.
404 *
405 * @return the KeyManager. This is used to resolve key names, both explicit calls
406 * on key() used in XSLT, and system-generated calls on key() which may
407 * also appear in XQuery and XPath
408 */
409 public KeyManager getKeyManager() {
410 return element.getCompilation().getPrincipalStylesheetModule().getKeyManager();
411 }
412
413 /**
414 * Get the stylesheet element containing this XPath expression
415 *
416 * @return the element in the tree representation of the source stylesheet
417 */
418
419 public StyleElement getStyleElement() {
420 return element;
421 }
422
423 /**
424 * Get type alias. This is a Saxon extension. A type alias is a QName which can
425 * be used as a shorthand for an itemtype, using the syntax ~typename anywhere that
426 * an item type is permitted.
427 *
428 * @param typeName the name of the type alias
429 * @return the corresponding item type, if the name is recognised; otherwise null.
430 */
431 @Override
432 public ItemType resolveTypeAlias(StructuredQName typeName) {
433 return getPackageData().obtainTypeAliasManager().getItemType(typeName);
434 }
435
436
437 }
438