Debian Codegraph @

net/sf/saxon/style/UseWhenFilter.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.Controller;
11 import net.sf.saxon.event.ProxyReceiver;
12 import net.sf.saxon.event.Receiver;
13 import net.sf.saxon.event.StartTagBuffer;
14 import net.sf.saxon.expr.Expression;
15 import net.sf.saxon.expr.XPathContext;
16 import net.sf.saxon.expr.XPathContextMajor;
17 import net.sf.saxon.expr.instruct.SlotManager;
18 import net.sf.saxon.expr.parser.*;
19 import net.sf.saxon.functions.DocumentFn;
20 import net.sf.saxon.functions.ElementAvailable;
21 import net.sf.saxon.functions.FunctionLibraryList;
22 import net.sf.saxon.lib.Feature;
23 import net.sf.saxon.lib.NamespaceConstant;
24 import net.sf.saxon.om.*;
25 import net.sf.saxon.trans.XPathException;
26 import net.sf.saxon.trans.packages.UsePack;
27 import net.sf.saxon.tree.AttributeLocation;
28 import net.sf.saxon.tree.linked.DocumentImpl;
29 import net.sf.saxon.tree.util.AttributeCollectionImpl;
30 import net.sf.saxon.type.*;
31 import net.sf.saxon.value.*;
32
33 import javax.xml.transform.Source;
34 import javax.xml.transform.TransformerException;
35 import javax.xml.transform.URIResolver;
36 import java.io.File;
37 import java.math.BigDecimal;
38 import java.net.URI;
39 import java.net.URISyntaxException;
40 import java.util.Map;
41 import java.util.Stack;
42
43 /**
44 * This is a filter inserted into the input pipeline for processing stylesheet modules, whose
45 * task is to evaluate use-when expressions and discard those parts of the stylesheet module
46 * for which the use-when attribute evaluates to false.
47 *
48 * <p>Originally, with XSLT 2.0, this class did use-when filtering and very little else.
49 * In XSLT 3.0 its role has expanded: it evaluates shadow attributes and static variables,
50 * and collects information about package dependencies.</p>
51 */
52
53 public class UseWhenFilter extends ProxyReceiver {
54
55 private StartTagBuffer startTag;
56 private int depthOfHole = 0;
57 private boolean emptyStylesheetElement = false;
58 private Stack<String> defaultNamespaceStack = new Stack<>();
59 private Stack<Integer> versionStack = new Stack<>();
60 private DateTimeValue currentDateTime = DateTimeValue.getCurrentDateTime(null);
61 private Compilation compilation;
62 private Stack<String> systemIdStack = new Stack<>();
63 private Stack<URI> baseUriStack = new Stack<>();
64 private NestedIntegerValue precedence;
65 private int importCount = 0;
66 private boolean dropUnderscoredAttributes;
67
68
69
70 /**
71 * Create a UseWhenFilter
72 *
73 * @param compilation the compilation episode
74 * @param next the next receiver in the pipeline
75 * @param precedence the import precedence expressed as a dotted-decimal integer, e.g. 1.4.6
76 */
77
78 public UseWhenFilter(Compilation compilation, Receiver next, NestedIntegerValue precedence) {
79 super(next);
80 this.compilation = compilation;
81 this.precedence = precedence;
82 }
83
84 /**
85 * Set the start tag buffer
86 *
87 * @param startTag a preceding filter on the pipeline that buffers the attributes of a start tag
88 */
89
90 public void setStartTagBuffer(StartTagBuffer startTag) {
91 this.startTag = startTag;
92 }
93
94 /**
95 * Start of document
96 */
97
98 public void open() throws XPathException {
99 nextReceiver.open();
100
101 String sysId = getSystemId();
102 if (sysId == null) {
103 sysId = "";
104 }
105 systemIdStack.push(sysId);
106 try {
107 baseUriStack.push(new URI(sysId));
108 } catch (URISyntaxException e) {
109 try {
110 baseUriStack.push(new File(sysId).toURI());
111 } catch (Exception ex) {
112 //throw new XPathException("Invalid URI for stylesheet: " + getSystemId());
113 }
114
115 }
116
117 }
118
119 /**
120 * Notify the start of an element.
121 * @param elemName the name of the element.
122 * @param typeCode integer code identifying the element's type within the name pool.
123 * @param location location where the event originated
124 * @param properties bit-significant properties of the element node
125 */
126
127 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
128 boolean inXsltNamespace = elemName.hasURI(NamespaceConstant.XSLT);
129 String stdAttUri = inXsltNamespace ? "" : NamespaceConstant.XSLT;
130 defaultNamespaceStack.push(startTag.getAttribute(stdAttUri, "xpath-default-namespace"));
131 if (emptyStylesheetElement) {
132 depthOfHole++;
133 return;
134 }
135 if (depthOfHole == 0) {
136 URI baseUri = processBaseUri(location);
137
138 boolean ignore = false;
139 int fp = -1;
140 if (inXsltNamespace) {
141 fp = elemName.obtainFingerprint(getNamePool());
142 }
143
144 int version = Integer.MIN_VALUE;
145 if (inXsltNamespace) {
146 if (fp != StandardNames.XSL_OUTPUT) {
147 String versionAtt = startTag.getAttribute("", "version");
148 version = processVersionAttribute(versionAtt);
149 }
150 } else {
151 // simplified stylesheet: look for xsl:version attribute
152 String versionAtt = startTag.getAttribute(NamespaceConstant.XSLT, "version");
153 version = processVersionAttribute(versionAtt);
154 }
155
156 if (version == Integer.MIN_VALUE) {
157 version = versionStack.isEmpty() ? 30 : versionStack.peek();
158 }
159 versionStack.push(version);
160
161 if (inXsltNamespace && defaultNamespaceStack.size() == 2
162 && version > 30 && !ElementAvailable.isXslt30Element(fp)) {
163 // top level unknown XSLT element is ignored in forwards-compatibility mode
164 ignore = true;
165 }
166
167 if (inXsltNamespace && !ignore) {
168 processShadowAttributes(elemName, location, baseUri);
169 }
170
171 boolean isStylesheetElement = inXsltNamespace &&
172 (elemName.getLocalPart().equals("stylesheet") || elemName.getLocalPart().equals("transform") || elemName.getLocalPart().equals("package"));
173
174 if (!ignore) {
175 String useWhen = startTag.getAttribute(stdAttUri, "use-when");
176
177 if (useWhen != null) {
178 AttributeCollection allAtts = startTag.getAllAttributes();
179 NodeName attName = allAtts.getNodeName(allAtts.getIndex(stdAttUri, "use-when"));
180 AttributeLocation attLoc = new AttributeLocation(elemName.getStructuredQName(), attName.getStructuredQName(), location);
181 boolean use = evaluateUseWhen(useWhen, attLoc, baseUri.toString());
182 ignore = !use;
183 }
184
185 if (ignore) {
186 if (isStylesheetElement) {
187 emptyStylesheetElement = true;
188 } else {
189 depthOfHole = 1;
190 return;
191 }
192 }
193 }
194
195 if (inXsltNamespace) {
196
197 // Handle static variables and parameters
198
199 boolean isVariable = elemName.getLocalPart().equals("variable");
200 boolean isParam = elemName.getLocalPart().equals("param");
201
202 // Note, the general policy here is to ignore errors on this initial pass through the stylesheet,
203 // if they will be checked and reported more thoroughly later on.
204
205 String staticStr = Whitespace.trim(startTag.getAttribute("", "static"));
206 if ((isVariable || isParam) &&
207 defaultNamespaceStack.size() == 2 && StyleElement.isYes(staticStr)) {
208
209 processStaticVariable(elemName, location, baseUri, precedence);
210 }
211
212 // Handle xsl:include and xsl:import
213
214 boolean isInclude = elemName.getLocalPart().equals("include");
215 boolean isImport = elemName.getLocalPart().equals("import");
216 if ((isInclude || isImport) && defaultNamespaceStack.size() == 2) {
217 // We need to process the included/imported stylesheet now, because its static variables
218 // can be used later in this module
219 processIncludeImport(elemName, location, baseUri, isImport);
220 }
221
222 // Handle xsl:import-schema
223
224 if (elemName.getLocalPart().equals("import-schema") && defaultNamespaceStack.size() == 2) {
225 compilation.setSchemaAware(true); // bug 3105
226 }
227
228 // Handle xsl:use-package
229
230 if (elemName.getLocalPart().equals("use-package") && defaultNamespaceStack.size() == 2) {
231 if (precedence.getDepth() > 1) {
232 throw new XPathException("xsl:use-package cannot appear in an imported stylesheet", "XTSE3008");
233 }
234 AttributeCollection atts = startTag.getAllAttributes();
235 String name = atts.getValue("", "name");
236 String pversion = atts.getValue("", "package-version");
237 if (name != null) {
238 try {
239 UsePack use = new UsePack(name, pversion, location.saveLocation());
240 compilation.registerPackageDependency(use);
241 } catch (XPathException err) {
242 // No action, error will be reported later.
243 }
244
245 }
246 }
247 }
248 dropUnderscoredAttributes = inXsltNamespace;
249 nextReceiver.startElement(elemName, typeCode, location, properties);
250 } else {
251 depthOfHole++;
252 }
253 }
254
255 private void processIncludeImport(NodeName elemName, Location location, URI baseUri, boolean isImport) throws XPathException {
256 String href = Whitespace.trim(startTag.getAttribute("", "href"));
257 if (href == null) {
258 throw new XPathException("Missing href attribute on " + elemName.getDisplayName(), "XTSE0010");
259 }
260
261 URIResolver resolver = compilation.getCompilerInfo().getURIResolver();
262 String baseUriStr = baseUri.toString();
263 DocumentURI key = DocumentFn.computeDocumentKey(href, baseUriStr, compilation.getPackageData(), resolver, false);
264 Map<DocumentURI, TreeInfo> map = compilation.getStylesheetModules();
265 if (map.containsKey(key)) {
266 // No action needed
267 } else {
268 Source source;
269 try {
270 source = resolver.resolve(href, baseUriStr);
271 } catch (TransformerException e) {
272 throw XPathException.makeXPathException(e);
273 }
274 if (source == null) {
275 source = getConfiguration().getSystemURIResolver().resolve(href, baseUriStr);
276 }
277 NestedIntegerValue newPrecedence = precedence;
278 if (isImport) {
279 newPrecedence = precedence.getStem().append(precedence.getLeaf() - 1).append(2 * ++importCount);
280 }
281 try {
282 DocumentImpl includedDoc = StylesheetModule.loadStylesheetModule(source, false, compilation, newPrecedence);
283 map.put(key, includedDoc);
284 } catch (XPathException e) {
285 e.setLocation(location);
286 e.maybeSetErrorCode("XTSE0165");
287 if ("XTSE0180".equals(e.getErrorCodeLocalPart())) {
288 if (isImport) {
289 e.setErrorCode("XTSE0210");
290 }
291 }
292 if (!e.hasBeenReported()) {
293 compilation.reportError(e);
294 }
295 throw e;
296 }
297 }
298 }
299
300 private void processStaticVariable(NodeName elemName, Location location, URI baseUri, NestedIntegerValue precedence) throws XPathException {
301 String nameStr = startTag.getAttribute("", "name");
302 String asStr = startTag.getAttribute("", "as");
303 String requiredStr = Whitespace.trim(startTag.getAttribute("", "required"));
304 boolean isRequired = StyleElement.isYes(requiredStr);
305
306
307 UseWhenStaticContext staticContext = new UseWhenStaticContext(compilation, startTag);
308 staticContext.setBaseURI(baseUri.toString());
309 staticContext.setContainingLocation(
310 new AttributeLocation(elemName.getStructuredQName(), new StructuredQName("", "", "as"), location));
311 SequenceType requiredType = SequenceType.ANY_SEQUENCE;
312
313 int languageLevel = compilation.getConfiguration().getConfigurationProperty(Feature.XPATH_VERSION_FOR_XSLT);
314 if (languageLevel == 30) {
315 languageLevel = 305; // XPath 3.0 + XSLT extensions
316 }
317 if (asStr != null) {
318 XPathParser parser = compilation.getConfiguration().newExpressionParser("XP", false, languageLevel);
319 requiredType = parser.parseSequenceType(asStr, staticContext);
320 }
321
322 StructuredQName varName;
323 try {
324 varName = StructuredQName.fromLexicalQName(nameStr, false, true, startTag);
325 } catch (XPathException err) {
326 throw createXPathException(
327 "Invalid variable name:" + nameStr + ". " + err.getMessage(),
328 err.getErrorCodeLocalPart(), location);
329 }
330
331 boolean isVariable = elemName.getLocalPart().equals("variable");
332 boolean isParam = elemName.getLocalPart().equals("param");
333 boolean isSupplied = isParam && compilation.getParameters().containsKey(varName);
334 AttributeLocation attLoc =
335 new AttributeLocation(elemName.getStructuredQName(), new StructuredQName("", "", "select"), location);
336
337 if (isParam) {
338 if (isRequired && !isSupplied) {
339 String selectStr = startTag.getAttribute("", "select");
340 if (selectStr != null) {
341 throw createXPathException("Cannot supply a default value when required='yes'", "XTSE0010", attLoc);
342 } else {
343 throw createXPathException(
344 "No value was supplied for the required static parameter $" + varName.getDisplayName(),
345 "XTDE0050", location);
346 }
347 }
348
349 if (isSupplied) {
350 Sequence<?> suppliedValue = compilation.getParameters()
351 .convertParameterValue(varName, requiredType, true, staticContext.makeEarlyEvaluationContext());
352
353 compilation.declareStaticVariable(varName, suppliedValue.materialize(), precedence, isParam);
354 }
355 }
356
357 if (isVariable || !isSupplied) {
358 String selectStr = startTag.getAttribute("", "select");
359 GroundedValue<?> value;
360 if (selectStr == null) {
361 if (isVariable) {
362 throw createXPathException(
363 "The select attribute is required for a static global variable",
364 "XTSE0010", location);
365 } else if (!Cardinality.allowsZero(requiredType.getCardinality())) {
366 throw createXPathException("The parameter is implicitly required because it does not accept an "
367 + "empty sequence, but no value has been supplied", "XTDE0700", location);
368 } else {
369 value = asStr == null ? StringValue.EMPTY_STRING : EmptySequence.getInstance();
370 compilation.declareStaticVariable(varName, value, precedence, isParam);
371 }
372
373 } else {
374 try {
375 staticContext.setContainingLocation(attLoc);
376 Sequence<?> seq = evaluateStatic(selectStr, location, staticContext);
377 value = seq.materialize();
378 } catch (XPathException e) {
379 throw createXPathException("Error in " + elemName.getLocalPart() + " expression. " + e.getMessage(),
380 e.getErrorCodeLocalPart(), attLoc);
381 }
382 }
383 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, varName.getDisplayName(), 0);
384 role.setErrorCode("XTDE0050");
385 TypeHierarchy th = getConfiguration().getTypeHierarchy();
386 Sequence<?> seq = th.applyFunctionConversionRules(value, requiredType, role, attLoc);
387 value = seq.materialize();
388 try {
389 compilation.declareStaticVariable(varName, value, precedence, isParam);
390 } catch (XPathException e) {
391 throw createXPathException(e.getMessage(), e.getErrorCodeLocalPart(), attLoc);
392 }
393 }
394 }
395
396 private void processShadowAttributes(NodeName elemName, Location location, URI baseUri) throws XPathException {
397 AttributeCollection atts = startTag.getAllAttributes();
398 for (int a=0; a<atts.getLength(); a++) {
399 String local = atts.getLocalName(a);
400 String uri = atts.getURI(a);
401 if (local.startsWith("_") && (uri.isEmpty() || uri.equals(NamespaceConstant.SAXON)) && local.length() >= 2) {
402 String value = atts.getValue(a);
403 AttributeLocation attLocation = new AttributeLocation(elemName.getStructuredQName(), atts.getNodeName(a).getStructuredQName(), location);
404 String newValue = processShadowAttribute(value, baseUri.toString(), attLocation);
405 String plainName = local.substring(1);
406 NodeName newName = uri.isEmpty() ?
407 new NoNamespaceName(plainName) : new FingerprintedQName(atts.getPrefix(a), NamespaceConstant.SAXON, plainName);
408 // if a corresponding attribute exists with no underscore, overwrite it. The attribute()
409 // method ensures that the shadow attribute won't be passed down the pipeline.
410 // Otherwise overwrite the shadow attribute itself.
411 int index = atts.getIndex("", plainName);
412 if (index == -1) {
413 index = a;
414 }
415 ((AttributeCollectionImpl)atts).setAttribute(
416 index, newName, BuiltInAtomicType.UNTYPED_ATOMIC, newValue, atts.getLocation(a), 0);
417 }
418 }
419 }
420
421 private URI processBaseUri(Location location) throws XPathException {
422 String systemId = location.getSystemId();
423 if (systemId == null) {
424 systemId = getSystemId();
425 }
426 URI baseUri;
427 if (systemId == null || systemId.equals(systemIdStack.peek())) {
428 baseUri = baseUriStack.peek();
429 } else {
430 try {
431 baseUri = new URI(systemId);
432 } catch (URISyntaxException e) {
433 throw new XPathException("Invalid URI for stylesheet entity: " + systemId);
434 }
435 }
436 String baseUriAtt = startTag.getAttribute(NamespaceConstant.XML, "base");
437 if (baseUriAtt != null) {
438 try {
439 baseUri = baseUri.resolve(baseUriAtt);
440 } catch (IllegalArgumentException iae) {
441 throw new XPathException("Invalid URI in xml:base attribute: " + baseUriAtt + ". " + iae.getMessage());
442 }
443 }
444 baseUriStack.push(baseUri);
445 systemIdStack.push(systemId);
446 return baseUri;
447 }
448
449 private int processVersionAttribute(String version) throws XPathException {
450 if (version != null) {
451 ConversionResult cr = BigDecimalValue.makeDecimalValue(version, true);
452 if (cr instanceof ValidationFailure) {
453 throw new XPathException("Invalid version number: " + version, "XTSE0110");
454 }
455 BigDecimalValue d = (BigDecimalValue)cr.asAtomic();
456 return d.getDecimalValue().multiply(BigDecimal.TEN).intValue();
457 } else {
458 return Integer.MIN_VALUE;
459 }
460 }
461
462 private String processShadowAttribute(String expression, String baseUri, AttributeLocation loc) throws XPathException {
463 UseWhenStaticContext staticContext = new UseWhenStaticContext(compilation, startTag);
464 staticContext.setBaseURI(baseUri);
465 staticContext.setContainingLocation(loc);
466 setNamespaceBindings(staticContext);
467 Expression expr = AttributeValueTemplate.make(expression, staticContext);
468 expr = typeCheck(expr, staticContext);
469 SlotManager stackFrameMap = allocateSlots(expression, expr);
470 XPathContext dynamicContext = makeDynamicContext(staticContext);
471 ((XPathContextMajor) dynamicContext).openStackFrame(stackFrameMap);
472 return expr.evaluateAsString(dynamicContext).toString();
473 }
474
475 public XPathException createXPathException(String message, String errorCode, Location location) {
476 XPathException err = new XPathException(message);
477 err.setErrorCode(errorCode);
478 err.setIsStaticError(true);
479 err.setLocator(location.saveLocation());
480 getPipelineConfiguration().getErrorListener().fatalError(err);
481 err.setHasBeenReported(true);
482 return err;
483 }
484
485 /**
486 * Notify a namespace. Namespaces are notified <b>after</b> the startElement event, and before
487 * any children for the element. The namespaces that are reported are only required
488 * to include those that are different from the parent element; however, duplicates may be reported.
489 * A namespace must not conflict with any namespaces already used for element or attribute names.
490 *
491 * @param namespaceBindings the namespace to be notified
492 * @throws IllegalStateException: attempt to output a namespace when there is no open element
493 * start tag
494 */
495
496 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
497 if (depthOfHole == 0) {
498 nextReceiver.namespace(namespaceBindings, properties);
499 }
500 }
501
502 /**
503 * Notify an attribute. Attributes are notified after the startElement event, and before any
504 * children. Namespaces and attributes may be intermingled.
505 *
506 * @param attName The name of the attribute
507 * @param typeCode The type of the attribute
508 * @param locationId the location of the node in the source, or of the instruction that created it
509 * @param properties Bit significant value. The following bits are defined:
510 * <dl>
511 * <dd>DISABLE_ESCAPING</dd> <dt>Disable escaping for this attribute</dt>
512 * <dd>NO_SPECIAL_CHARACTERS</dd> <dt>Attribute value contains no special characters</dt>
513 * </dl>
514 * @throws IllegalStateException: attempt to output an attribute when there is no open element
515 * start tag
516 */
517
518 public void attribute(NodeName attName, SimpleType typeCode, CharSequence value, Location locationId, int properties) throws XPathException {
519 if (depthOfHole == 0 && (!dropUnderscoredAttributes || !(attName.getLocalPart().startsWith("_") && attName.hasURI("")))) {
520 nextReceiver.attribute(attName, typeCode, value, locationId, properties);
521 }
522 }
523
524 /**
525 * Notify the start of the content, that is, the completion of all attributes and namespaces.
526 * Note that the initial receiver of output from XSLT instructions will not receive this event,
527 * it has to detect it itself. Note that this event is reported for every element even if it has
528 * no attributes, no namespaces, and no content.
529 */
530
531 public void startContent() throws XPathException {
532 if (depthOfHole == 0) {
533 nextReceiver.startContent();
534 }
535 dropUnderscoredAttributes = false;
536 }
537
538 /**
539 * End of element
540 */
541
542 public void endElement() throws XPathException {
543 defaultNamespaceStack.pop();
544 if (depthOfHole > 0) {
545 depthOfHole--;
546 } else {
547 systemIdStack.pop();
548 baseUriStack.pop();
549 versionStack.pop();
550 nextReceiver.endElement();
551 }
552 }
553
554 /**
555 * Character data
556 */
557
558 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
559 if (depthOfHole == 0) {
560 nextReceiver.characters(chars, locationId, properties);
561 }
562 }
563
564 /**
565 * Processing Instruction
566 */
567
568 public void processingInstruction(String target, CharSequence data, Location locationId, int properties) {
569 // these are ignored in a stylesheet
570 }
571
572 /**
573 * Output a comment
574 */
575
576 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
577 // these are ignored in a stylesheet
578 }
579
580 /**
581 * Evaluate a use-when attribute
582 *
583 * @param expression the expression to be evaluated
584 * @param location identifies the location of the expression in case error need to be reported
585 * @param baseUri the base URI of the element containing the expression
586 * @return the effective boolean value of the result of evaluating the expression
587 * @throws XPathException if evaluation of the expression fails
588 */
589
590 public boolean evaluateUseWhen(String expression, AttributeLocation location, String baseUri) throws XPathException {
591 UseWhenStaticContext staticContext = new UseWhenStaticContext(compilation, startTag);
592 staticContext.setBaseURI(baseUri);
593 staticContext.setContainingLocation(location);
594 setNamespaceBindings(staticContext);
595 Expression expr = ExpressionTool.make(expression, staticContext,
596 0, Token.EOF, null);
597 expr.setRetainedStaticContext(staticContext.makeRetainedStaticContext());
598 expr = typeCheck(expr, staticContext);
599 SlotManager stackFrameMap = allocateSlots(expression, expr);
600 XPathContext dynamicContext = makeDynamicContext(staticContext);
601 //dynamicContext.getController().getExecutable().setFunctionLibrary((FunctionLibraryList)staticContext.getFunctionLibrary());
602 ((XPathContextMajor) dynamicContext).openStackFrame(stackFrameMap);
603 return expr.effectiveBooleanValue(dynamicContext);
604 }
605
606 private SlotManager allocateSlots(String expression, Expression expr) {
607 SlotManager stackFrameMap = getPipelineConfiguration().getConfiguration().makeSlotManager();
608 if (expression.indexOf('$') >= 0) {
609 ExpressionTool.allocateSlots(expr, stackFrameMap.getNumberOfVariables(), stackFrameMap);
610 }
611 return stackFrameMap;
612 }
613
614
615 private void setNamespaceBindings(UseWhenStaticContext staticContext) {
616 staticContext.setDefaultElementNamespace(NamespaceConstant.NULL);
617 for (int i = defaultNamespaceStack.size() - 1; i >= 0; i--) {
618 String uri = defaultNamespaceStack.get(i);
619 if (uri != null) {
620 staticContext.setDefaultElementNamespace(uri);
621 break;
622 }
623 }
624 }
625
626 private Expression typeCheck(Expression expr, UseWhenStaticContext staticContext) throws XPathException {
627 ItemType contextItemType = Type.ITEM_TYPE;
628 ContextItemStaticInfo cit = getConfiguration().makeContextItemStaticInfo(contextItemType, true);
629 ExpressionVisitor visitor = ExpressionVisitor.make(staticContext);
630 return expr.typeCheck(visitor, cit);
631 }
632
633 private XPathContext makeDynamicContext(UseWhenStaticContext staticContext) throws XPathException {
634 Controller controller = new Controller(getConfiguration());
635 controller.getExecutable().setFunctionLibrary((FunctionLibraryList) staticContext.getFunctionLibrary());
636 if (staticContext.getXPathVersion() < 30) {
637 controller.setURIResolver(new URIPreventer());
638 }
639 controller.setCurrentDateTime(currentDateTime);
640 // this is to ensure that all use-when expressions in a module use the same date and time
641 XPathContext dynamicContext = controller.newXPathContext();
642 dynamicContext = dynamicContext.newCleanContext();
643 return dynamicContext;
644 }
645
646
647 /**
648 * Evaluate a static expression (to initialize a static variable)
649 *
650 * @param expression the expression to be evaluated
651 * @param locationId identifies the location of the expression in case error need to be reported
652 * @param staticContext the static context for evaluation of the expression
653 * @return the effective boolean value of the result of evaluating the expression
654 * @throws XPathException if evaluation of the expression fails
655 */
656
657 public Sequence<?> evaluateStatic(String expression, Location locationId, UseWhenStaticContext staticContext) throws XPathException {
658 setNamespaceBindings(staticContext);
659 Expression expr = ExpressionTool.make(expression, staticContext,
660 0, Token.EOF, null);
661 expr = typeCheck(expr, staticContext);
662 SlotManager stackFrameMap = getPipelineConfiguration().getConfiguration().makeSlotManager();
663 ExpressionTool.allocateSlots(expr, stackFrameMap.getNumberOfVariables(), stackFrameMap);
664 XPathContext dynamicContext = makeDynamicContext(staticContext);
665 ((XPathContextMajor) dynamicContext).openStackFrame(stackFrameMap);
666 return expr.iterate(dynamicContext).materialize();
667 }
668
669
670
671 /**
672 * Define a URIResolver that disallows all URIs
673 */
674
675 private static class URIPreventer implements URIResolver {
676 /**
677 * Called by the processor when it encounters
678 * an xsl:include, xsl:import, or document() function.
679 *
680 * @param href An href attribute, which may be relative or absolute.
681 * @param base The base URI against which the first argument will be made
682 * absolute if the absolute URI is required.
683 * @return A Source object, or null if the href cannot be resolved,
684 * and the processor should try to resolve the URI itself.
685 * @throws XPathException if an error occurs when trying to
686 * resolve the URI.
687 */
688 /*@NotNull*/
689 public Source resolve(String href, String base) throws XPathException {
690 throw new XPathException("No external documents are available within an [xsl]use-when expression");
691 }
692 }
693
694
695 }
696