Debian Codegraph @

net/sf/saxon/style/StyleElement.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.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.expr.sort.SortKeyDefinition;
15 import net.sf.saxon.expr.sort.SortKeyDefinitionList;
16 import net.sf.saxon.functions.Current;
17 import net.sf.saxon.lib.Feature;
18 import net.sf.saxon.lib.NamespaceConstant;
19 import net.sf.saxon.lib.StringCollator;
20 import net.sf.saxon.lib.Validation;
21 import net.sf.saxon.om.*;
22 import net.sf.saxon.pattern.*;
23 import net.sf.saxon.trace.InstructionInfo;
24 import net.sf.saxon.trace.LocationKind;
25 import net.sf.saxon.trans.*;
26 import net.sf.saxon.tree.AttributeLocation;
27 import net.sf.saxon.tree.iter.AxisIterator;
28 import net.sf.saxon.tree.iter.ListIterator;
29 import net.sf.saxon.tree.linked.ElementImpl;
30 import net.sf.saxon.tree.linked.NodeImpl;
31 import net.sf.saxon.tree.linked.TextImpl;
32 import net.sf.saxon.tree.util.FastStringBuffer;
33 import net.sf.saxon.tree.util.NamespaceIterator;
34 import net.sf.saxon.tree.util.Navigator;
35 import net.sf.saxon.type.*;
36 import net.sf.saxon.value.BigDecimalValue;
37 import net.sf.saxon.value.SequenceType;
38 import net.sf.saxon.value.Whitespace;
39
40 import javax.xml.transform.SourceLocator;
41 import javax.xml.transform.TransformerException;
42 import java.math.BigDecimal;
43 import java.net.URI;
44 import java.net.URISyntaxException;
45 import java.util.*;
46
47
48 /**
49 * Abstract superclass for all element nodes in the stylesheet.
50 * <p>Note: this class implements Locator. The element retains information about its own location
51 * in the stylesheet, which is useful when an XSLT static error is found.</p>
52 */
53
54 public abstract class StyleElement extends ElementImpl {
55
56 /*@Nullable*/ protected String[] extensionNamespaces = null; // a list of URIs
57 private String[] excludedNamespaces = null; // a list of URIs
58 protected int version = -1; // the effective version of this element
59 protected ExpressionContext staticContext = null;
60 protected XPathException validationError = null;
61 protected int reportingCircumstances = REPORT_ALWAYS;
62 protected String defaultXPathNamespace = null;
63 protected String defaultCollationName = null;
64 protected StructuredQName defaultMode;
65 protected boolean expandText = false;
66 private boolean explaining = false; // true if saxon:explain="yes"
67 private StructuredQName objectName; // for instructions that define an XSLT named object, the name of that object
68 private String baseURI;
69 private Compilation compilation;
70 private ExplicitLocation savedLocation = null;
71 private int defaultValidation = Validation.DEFAULT;
72
73 // Conditions under which an error is to be reported
74
75 public static final int REPORT_ALWAYS = 1;
76 public static final int REPORT_UNLESS_FORWARDS_COMPATIBLE = 2;
77 public static final int REPORT_IF_INSTANTIATED = 3;
78 public static final int REPORT_STATICALLY_UNLESS_FALLBACK_AVAILABLE = 4;
79 public static final int REPORT_DYNAMICALLY_UNLESS_FALLBACK_AVAILABLE = 5;
80 public static final int IGNORED_INSTRUCTION = 6;
81
82 protected int actionsCompleted = 0;
83 public static final int ACTION_VALIDATE = 1;
84 public static final int ACTION_COMPILE = 2;
85 public static final int ACTION_TYPECHECK = 4;
86 public static final int ACTION_OPTIMIZE = 8;
87 public static final int ACTION_FIXUP = 16;
88 public static final int ACTION_PROCESS_ATTRIBUTES = 32;
89
90
91 /**
92 * Constructor
93 */
94
95 public StyleElement() {
96 }
97
98 public Compilation getCompilation() {
99 return compilation;
100 }
101
102 public void setCompilation(Compilation compilation) {
103 this.compilation = compilation;
104 }
105
106 public StylesheetPackage getPackageData() {
107 return getPrincipalStylesheetModule().getStylesheetPackage();
108 }
109
110 public Configuration getConfiguration() {
111 return compilation.getConfiguration();
112 }
113
114 /**
115 * Get the static context for expressions on this element
116 *
117 * @return the static context
118 */
119
120 public ExpressionContext getStaticContext() {
121 if (staticContext == null) {
122 staticContext = new ExpressionContext(this, null);
123 }
124 return staticContext;
125 }
126
127 public ExpressionContext getStaticContext(StructuredQName attributeName) {
128 return new ExpressionContext(this, attributeName);
129 }
130
131 /**
132 * Get the base URI of the element, which acts as the static base URI for XPath expressions defined
133 * on this element. This is an expensive operation so the result is cached
134 *
135 * @return the base URI
136 */
137
138 public String getBaseURI() {
139 if (baseURI == null) {
140 baseURI = super.getBaseURI();
141 }
142 return baseURI;
143 }
144
145 /**
146 * Make an expression visitor
147 *
148 * @return the expression visitor
149 */
150
151 public ExpressionVisitor makeExpressionVisitor() {
152 return ExpressionVisitor.make(getStaticContext());
153 }
154
155 /**
156 * Ask whether the code is compiled in schema-aware mode
157 *
158 * @return true if the compilation is schema-aware
159 */
160
161 public boolean isSchemaAware() {
162 return getCompilation().isSchemaAware();
163 }
164
165 /**
166 * Determine whether saxon:explain has been set to "yes"
167 *
168 * @return true if saxon:explain has been set to "yes" on this element
169 */
170
171 protected boolean isExplaining() {
172 return explaining;
173 }
174
175 /**
176 * Make this node a substitute for a temporary one previously added to the tree. See
177 * StyleNodeFactory for details. "A node like the other one in all things but its class".
178 * Note that at this stage, the node will not yet be known to its parent, though it will
179 * contain a reference to its parent; and it will have no children.
180 *
181 * @param temp the element which this one is substituting for
182 */
183
184 public void substituteFor(StyleElement temp) {
185 setRawParent(temp.getRawParent());
186 setAttributeList(temp.getAttributeList());
187 setNamespaceList(temp.getNamespaceList());
188 setNodeName(temp.getNodeName());
189 setRawSequenceNumber(temp.getRawSequenceNumber());
190 extensionNamespaces = temp.extensionNamespaces;
191 excludedNamespaces = temp.excludedNamespaces;
192 version = temp.version;
193 staticContext = temp.staticContext;
194 validationError = temp.validationError;
195 reportingCircumstances = temp.reportingCircumstances;
196 compilation = temp.compilation;
197 //lineNumber = temp.lineNumber;
198 }
199
200 /**
201 * Set a validation error. This is an error detected during construction of this element on the
202 * stylesheet, but which is not to be reported until later.
203 *
204 * @param reason the details of the error
205 * @param circumstances a code identifying the circumstances under which the error is to be reported
206 */
207
208 public void setValidationError(TransformerException reason,
209 int circumstances) {
210 validationError = XPathException.makeXPathException(reason);
211 reportingCircumstances = circumstances;
212 }
213
214 public void setIgnoreInstruction() {
215 reportingCircumstances = IGNORED_INSTRUCTION;
216 }
217
218 /**
219 * Ask whether this node is an instruction. The default implementation says it isn't.
220 *
221 * @return true if this element is an instruction
222 */
223
224 public boolean isInstruction() {
225 return false;
226 }
227
228 /**
229 * Ask whether this node is a declaration, that is, a permitted child of xsl:stylesheet
230 * (including xsl:include and xsl:import). The default implementation returns false
231 *
232 * @return true if the element is a permitted child of xsl:stylesheet or xsl:transform
233 */
234
235 public boolean isDeclaration() {
236 return false;
237 }
238
239 /**
240 * Get the visibility of the component. Returns the actual value of the visibility attribute,
241 * after validation, unless this is absent, in which case it returns the default value of PRIVATE.
242 * Invokes {@link #invalidAttribute(String, String)} if the value is invalid.
243 *
244 * @return the declared visibility of the component, or {@link Visibility#PRIVATE}
245 * if the visibility attribute is absent.
246 */
247
248 public Visibility getVisibility() {
249 String vis = getAttributeValue("", "visibility");
250 if (vis == null) {
251 return Visibility.PRIVATE;
252 } else {
253 return interpretVisibilityValue(vis, "");
254 }
255 }
256
257 /**
258 * Get the visibility of the component. Returns the actual value of the visibility attribute,
259 * after validation, unless this is absent, in which case it returns null.
260 *
261 * @return the declared visibility of the component, or null if the visibility attribute is absent.
262 */
263
264 public Visibility getDeclaredVisibility() {
265 String vis = getAttributeValue("", "visibility");
266 if (vis == null) {
267 return null;
268 } else {
269 return interpretVisibilityValue(vis, "");
270 }
271 }
272
273 /**
274 * Mark tail-recursive calls on templates and functions.
275 * For most instructions, this returns false.
276 *
277 * @return true if one or more tail calls were identified
278 */
279
280 protected boolean markTailCalls() {
281 return false;
282 }
283
284 /**
285 * Determine whether this type of element is allowed to contain a sequence constructor
286 *
287 * @return true if this instruction is allowed to contain a sequence constructor
288 */
289
290 protected boolean mayContainSequenceConstructor() {
291 return false;
292 }
293
294 /**
295 * Determine whether this type of element is allowed to contain an xsl:fallback
296 * instruction. Note that this is only relevant if the element is an instruction.
297 *
298 * @return true if this element is allowed to contain an xsl:fallback
299 */
300
301 protected boolean mayContainFallback() {
302 return mayContainSequenceConstructor();
303 }
304
305 /**
306 * Determine whether this type of element is allowed to contain an xsl:param element
307 *
308 * @return true if this element is allowed to contain an xsl:param
309 */
310
311 protected boolean mayContainParam() {
312 return false;
313 }
314
315 /**
316 * Get the containing XSLStylesheet or XSLPackage element
317 *
318 * @return the XSLStylesheet element representing the outermost element of the containing
319 * stylesheet module. Return null if there is no containing XSLStylesheet element
320 */
321
322 public XSLModuleRoot getContainingStylesheet() {
323 NodeInfo parent = getParent();
324 if (parent instanceof XSLModuleRoot) {
325 return (XSLModuleRoot) parent;
326 } else if (parent instanceof StyleElement) {
327 return ((StyleElement) parent).getContainingStylesheet();
328 } else {
329 // this can happen when early errors are detected in a simplified stylesheet,
330 // or when the element is part of a package outside any xsl:stylesheet
331 return null;
332 }
333 }
334
335 /**
336 * Get the effective value of the default-validation attribute
337 *
338 * @return the value of default-validation, as a constant from the {@link Validation} class,
339 * or Validation.STRIP if there is no containing element with a default-validation
340 * attribute.
341 */
342
343 public int getDefaultValidation() {
344 int v = defaultValidation;
345 NodeInfo p = this;
346 while (v == Validation.DEFAULT) {
347 p = p.getParent();
348 if (!(p instanceof StyleElement)) {
349 return Validation.STRIP;
350 }
351 v = ((StyleElement) p).defaultValidation;
352 }
353 return v;
354 }
355
356 /**
357 * Make a structured QName, using this Element as the context for namespace resolution.
358 * If the name is unprefixed, the default namespace is <b>not</b> used.
359 *
360 * @param lexicalQName The lexical QName as written, in the form "[prefix:]localname". The name must have
361 * already been validated as a syntactically-correct QName. Leading and trailing whitespace
362 * will be trimmed. If XSLT 3.0 is enabled, then the EQName syntax "Q{uri}local" is also
363 * accepted.
364 * @return the StructuredQName representation of this lexical QName
365 * @throws XPathException if the qname is not a lexically-valid QName, or if the name
366 * is in a reserved namespace.
367 */
368
369 public final StructuredQName makeQName(String lexicalQName)
370 throws XPathException {
371
372 StructuredQName qName;
373 try {
374 qName = StructuredQName.fromLexicalQName(lexicalQName, false,
375 true, this);
376 } catch (XPathException e) {
377 e.setIsStaticError(true);
378 String code = e.getErrorCodeLocalPart();
379 if ("FONS0004".equals(code)) {
380 e.setErrorCode("XTSE0280");
381 } else if ("FOCA0002".equals(code)) {
382 e.setErrorCode("XTSE0020");
383 } else if (code == null) {
384 e.setErrorCode("XTSE0020");
385 }
386 e.setLocator(this);
387 throw e;
388 }
389 if (NamespaceConstant.isReserved(qName.getURI())) {
390 if (qName.hasURI(NamespaceConstant.XSLT)) {
391 if (qName.getLocalPart().equals("initial-template")
392 && (this instanceof XSLTemplate || this instanceof XSLCallTemplate)) {
393 return qName;
394 }
395 if (qName.getLocalPart().equals("original")) {
396 // OK if within xsl:override
397 if (findAncestorElement(StandardNames.XSL_OVERRIDE) != null) {
398 return qName;
399 }
400 }
401 }
402 XPathException err = new XPathException("Namespace prefix " +
403 qName.getPrefix() + " refers to a reserved namespace");
404 err.setIsStaticError(true);
405 err.setErrorCode("XTSE0080");
406 throw err;
407 }
408 return qName;
409 }
410
411 /**
412 * Get the first ancestor element in the stylesheet tree that has a given name, supplied by
413 * fingerprint.
414 *
415 * @param fingerprint the name of the required element
416 * @return the first (innermost) ancestor with the required name, or null if none is found
417 */
418
419 public StyleElement findAncestorElement(int fingerprint) {
420 Optional<NodeInfo> ancestor = iterateAxis(AxisInfo.ANCESTOR).firstWith(
421 node -> node instanceof StyleElement && node.getFingerprint() == fingerprint);
422 return (StyleElement) ancestor.orElse(null);
423 }
424
425 /**
426 * Assuming this is an xsl:use-package element, find the package to which it refers.
427 *
428 * @return the package referenced by this xsl:use-package element; or null if this is not
429 * an xsl:use-package element
430 */
431
432 public StylesheetPackage getUsedPackage() {
433 return null;
434 }
435
436 /**
437 * Check that a reference to xsl:original appears within an xsl:override element, and that
438 * the name of the containing component matches the name of a component in the used stylesheet
439 * package; return the component in that package with matching symbolic name
440 *
441 * @param componentKind the kind of component required, e.g. StandardNames.XSL_TEMPLATE
442 * @return the component with matching name in the used stylesheet
443 * @throws XPathException if the xsl:original reference appears in an invalid context
444 */
445
446 public Actor getXslOriginal(int componentKind) throws XPathException {
447 StyleElement container = componentKind == getFingerprint() ? this : findAncestorElement(componentKind);
448 if (!(container instanceof StylesheetComponent)) {
449 throw new XPathException(
450 "A reference to xsl:original appears within the wrong kind of component: in this case" +
451 ", it must be within xsl:" + getNamePool().getLocalName(componentKind), "XTSE0650", this);
452 }
453 SymbolicName originalName = ((StylesheetComponent) container).getSymbolicName();
454 StyleElement xslOverride = container.findAncestorElement(StandardNames.XSL_OVERRIDE);
455 if (xslOverride == null) {
456 throw new XPathException("A reference to xsl:original can be used only within an xsl:override element");
457 }
458 StyleElement usePackage = xslOverride.findAncestorElement(StandardNames.XSL_USE_PACKAGE);
459 if (usePackage == null) {
460 throw new XPathException("The parent of xsl:override must be an xsl:use-package element", "XTSE0010", xslOverride);
461 }
462
463 Component overridden = usePackage.getUsedPackage().getComponent(originalName);
464 if (overridden == null) {
465 // the error will be detected and reported elsewhere
466 return null;
467 }
468 return overridden.getActor();
469 }
470
471 /**
472 * Get the component that this declaration overrides, or null if this is not an overriding declaration
473 *
474 * @return the overridden component, or null
475 */
476
477 public Component getOverriddenComponent() {
478 if (!(this instanceof StylesheetComponent)) {
479 return null;
480 }
481 SymbolicName originalName = ((StylesheetComponent) this).getSymbolicName();
482 StyleElement xslOverride = findAncestorElement(StandardNames.XSL_OVERRIDE);
483 if (xslOverride == null) {
484 return null;
485 }
486 StyleElement usePackage = xslOverride.findAncestorElement(StandardNames.XSL_USE_PACKAGE);
487 if (usePackage == null) {
488 return null;
489 }
490
491 return usePackage.getUsedPackage().getComponent(originalName);
492 }
493
494 /**
495 * Make a NamespaceContext object representing the list of in-scope namespaces. This will
496 * be a copy of the namespace context with no references to objects in the stylesheet tree,
497 * so that it can be kept until run-time without locking the tree down in memory.
498 *
499 * @return a copy of the namespace context
500 */
501
502 public SavedNamespaceContext makeNamespaceContext() {
503 StylesheetPackage pack = getPackageData();
504 return new SavedNamespaceContext(NamespaceIterator.iterateNamespaces(this));
505 }
506
507 public RetainedStaticContext makeRetainedStaticContext() {
508 return getStaticContext().makeRetainedStaticContext();
509 }
510
511 /**
512 * Ask whether this instruction requires a different retained static context from the containing
513 * (parent) instruction. That is, this instruction changes the static base URI, the default collation,
514 * or the set of in-scope namespaces.
515 *
516 * @return true if the context for evaluating this instruction differs in relevant ways from that
517 * of the calling instruction
518 */
519 public boolean changesRetainedStaticContext() {
520 NodeImpl parent = getParent();
521 return parent == null
522 || !ExpressionTool.equalOrNull(getBaseURI(), parent.getBaseURI())
523 || defaultCollationName != null
524 || defaultXPathNamespace != null
525 || getDeclaredNamespaces(NamespaceBinding.EMPTY_ARRAY).length != 0
526 || !(parent instanceof StyleElement)
527 || getEffectiveVersion() != ((StyleElement) getParent()).getEffectiveVersion();
528 }
529
530 /**
531 * Get the namespace context of the instruction.
532 *
533 * @return the namespace context. This method does not make a copy of the namespace context,
534 * so a reference to the returned NamespaceResolver will lock the stylesheet tree in memory.
535 */
536
537 public NamespaceResolver getNamespaceResolver() {
538 return this;
539 }
540
541 /**
542 * Process the attributes of this element and all its children
543 *
544 * @throws XPathException in the event of a static error being detected
545 */
546
547 public void processAllAttributes() throws XPathException {
548 processDefaultCollationAttribute();
549 processDefaultMode();
550 staticContext = new ExpressionContext(this, null);
551 processAttributes();
552 iterateAxis(AxisInfo.CHILD).forEachOrFail(child -> {
553 if (child instanceof StyleElement) {
554 ((StyleElement) child).processAllAttributes();
555 if (((StyleElement) child).explaining) {
556 // saxon:explain on any element in a template/function now causes an explanation at the
557 // level of the template/function
558 explaining = true;
559 }
560 }
561 });
562 }
563
564 /**
565 * Process the standard attributes such as {@code [xsl:]expand-text}. Invokes
566 * {@link #compileError(String)} or similar if the value of any of these attributes
567 * is invalid.
568 *
569 * <p>The method processes:</p>
570 * <ul>
571 * <li>{@code extension-element-prefixes}</li>
572 * <li>{@code exclude-result-prefixes}</li>
573 * <li>{@code version}</li>
574 * <li>{@code default-xpath-namespace}</li>
575 * <li>{@code default-validation}</li>
576 * <li>{@code expand-text}</li>
577 * </ul>
578 *
579 * <p>but not:</p>
580 * <ul>
581 * <li>{@code default-collation}</li>
582 * <li>{@code default-mode}</li>
583 * </ul>
584 *
585 * @param namespace either "" to find the attributes in the null namespace,
586 * or NamespaceConstant.XSLT to find them in the XSLT namespace
587 */
588
589 public void processStandardAttributes(String namespace) {
590 processExtensionElementAttribute(namespace);
591 processExcludedNamespaces(namespace);
592 processVersionAttribute(namespace);
593 processDefaultXPathNamespaceAttribute(namespace);
594 processDefaultValidationAttribute(namespace);
595 processExpandTextAttribute(namespace);
596 }
597
598 /**
599 * Get an attribute value given the Clark name of the attribute (that is,
600 * the name in {uri}local format).
601 *
602 * @param clarkName the name of the attribute in {uri}local format
603 * @return the value of the attribute if it exists, or null otherwise
604 */
605
606 public String getAttributeValue(String clarkName) {
607 NodeName nn = FingerprintedQName.fromClarkName(clarkName);
608 return getAttributeValue(nn.getURI(), nn.getLocalPart());
609 }
610
611 /**
612 * Process the attribute list for the element. This is a wrapper method that calls
613 * prepareAttributes (provided in the subclass) and traps any exceptions
614 */
615
616 protected final void processAttributes() {
617 try {
618 prepareAttributes();
619 } catch (XPathException err) {
620 compileError(err);
621 }
622 }
623
624 /**
625 * Check whether an unknown attribute is permitted.
626 *
627 * @param nc The name code of the attribute name
628 */
629
630 protected void checkUnknownAttribute(NodeName nc) {
631
632 String attributeURI = nc.getURI();
633 String elementURI = getURI();
634 String clarkName = nc.getStructuredQName().getClarkName();
635
636 if (clarkName.equals(StandardNames.SAXON_EXPLAIN)) {
637 String value = getAttributeValue(clarkName);
638 explaining = processBooleanAttribute("saxon:explain", value);
639 }
640
641 if (forwardsCompatibleModeIsEnabled()) {
642 // then unknown attributes are permitted and ignored
643 return;
644 }
645
646 // allow xsl:extension-element-prefixes etc on an extension element
647
648 if (isInstruction() &&
649 attributeURI.equals(NamespaceConstant.XSLT) &&
650 !elementURI.equals(NamespaceConstant.XSLT) &&
651 (clarkName.endsWith("}default-collation") ||
652 clarkName.endsWith("}default-mode") ||
653 clarkName.endsWith("}xpath-default-namespace") ||
654 clarkName.endsWith("}expand-text") ||
655 clarkName.endsWith("}extension-element-prefixes") ||
656 clarkName.endsWith("}exclude-result-prefixes") ||
657 clarkName.endsWith("}version") ||
658 clarkName.endsWith("}default-validation") ||
659 clarkName.endsWith("}use-when"))) {
660 return;
661 }
662
663 // allow standard attributes on an XSLT element
664
665 if (elementURI.equals(NamespaceConstant.XSLT) &&
666 (clarkName.equals("default-collation") ||
667 clarkName.equals("default-mode") ||
668 clarkName.equals("expand-text") ||
669 clarkName.equals("xpath-default-namespace") ||
670 clarkName.equals("extension-element-prefixes") ||
671 clarkName.equals("exclude-result-prefixes") ||
672 clarkName.equals("version") ||
673 clarkName.equals("default-validation") ||
674 clarkName.equals("use-when"))) {
675 return;
676 }
677
678 if ("".equals(attributeURI) || NamespaceConstant.XSLT.equals(attributeURI)) {
679 compileErrorInAttribute("Attribute " + Err.wrap(nc.getDisplayName(), Err.ATTRIBUTE) +
680 " is not allowed on element " + Err.wrap(getDisplayName(), Err.ELEMENT),
681 "XTSE0090", clarkName);
682 } else if (NamespaceConstant.SAXON.equals(attributeURI)) {
683 compileWarning("Unrecognized attribute in Saxon namespace: " + nc.getDisplayName(), "XTSE0090");
684 }
685 }
686
687 /**
688 * Set the attribute list for the element. This is called to process the attributes (note
689 * the distinction from processAttributes in the superclass).
690 * Must be supplied in a subclass
691 *
692 * @throws net.sf.saxon.trans.XPathException if a static error is detected
693 */
694
695 protected abstract void prepareAttributes() throws XPathException;
696
697 /**
698 * Find the last child instruction of this instruction. Returns null if
699 * there are no child instructions, or if the last child is a text node.
700 *
701 * @return the last child instruction, or null if there are no child instructions
702 */
703
704 protected StyleElement getLastChildInstruction() {
705 StyleElement last = null;
706 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
707 NodeInfo child;
708 while ((child = kids.next()) != null) {
709 if (child instanceof StyleElement) {
710 last = (StyleElement) child;
711 } else {
712 last = null;
713 }
714 }
715 return last;
716 }
717
718 /**
719 * Compile an XPath expression in the context of this stylesheet element
720 *
721 * @param expression the source text of the XPath expression
722 * @param attIndex the index position of the attribute containing the XPath expression, or
723 * -1 if the expression is in a text node
724 * @return the compiled expression tree for the XPath expression. In the case of an error,
725 * returns an ErrorExpression that will fail at run-time if executed.
726 */
727
728 public Expression makeExpression(String expression, int attIndex) {
729 try {
730 StaticContext env = staticContext;
731 if (attIndex >= 0) {
732 StructuredQName attName = getAttributeList().getNodeName(attIndex).getStructuredQName();
733 env = getStaticContext(attName);
734 }
735 return ExpressionTool.make(expression, env, 0, Token.EOF,
736 getCompilation().getCompilerInfo().getCodeInjector());
737 } catch (XPathException err) {
738 err.maybeSetLocation(allocateLocation());
739 if (err.isReportableStatically()) {
740 compileError(err);
741 }
742 ErrorExpression erexp = new ErrorExpression(err);
743 erexp.setRetainedStaticContext(makeRetainedStaticContext());
744 erexp.setLocation(allocateLocation());
745 return erexp;
746 }
747 }
748
749 /**
750 * Make a pattern in the context of this stylesheet element
751 *
752 * @param pattern the source text of the pattern
753 * @return the compiled pattern
754 */
755
756 public Pattern makePattern(String pattern, String attributeName) {
757 try {
758 StaticContext env = getStaticContext(new StructuredQName("", "", attributeName));
759 Pattern p = Pattern.make(pattern, env, getCompilation().getPackageData());
760 p.setLocation(allocateLocation());
761 return p;
762 } catch (XPathException err) {
763 if ("XPST0003".equals(err.getErrorCodeLocalPart())) {
764 err.setErrorCode("XTSE0340");
765 }
766 compileError(err);
767 NodeTestPattern nsp = new NodeTestPattern(AnyNodeTest.getInstance());
768 nsp.setLocation(allocateLocation());
769 return nsp;
770 }
771 }
772
773 /**
774 * Make an attribute value template in the context of this stylesheet element
775 *
776 * @param expression the source text of the attribute value template
777 * @return a compiled XPath expression that computes the value of the attribute (including
778 * concatenating the results of embedded expressions with any surrounding fixed text)
779 */
780
781 protected Expression makeAttributeValueTemplate(String expression, int attIndex) {
782 StaticContext env = attIndex == -1 ?
783 staticContext :
784 getStaticContext(getAttributeList().getNodeName(attIndex).getStructuredQName());
785 if (attIndex >= 0) {
786 StructuredQName attName = getAttributeList().getNodeName(attIndex).getStructuredQName();
787 env = getStaticContext(attName);
788 }
789 try {
790 return AttributeValueTemplate.make(expression, env);
791 } catch (XPathException err) {
792 compileError(err);
793 return new StringLiteral(expression);
794 }
795 }
796
797
798 /**
799 * Check the value of an attribute, as supplied statically
800 *
801 * @param name the name of the attribute
802 * @param value the value of the attribute
803 * @param avt set to true if the value is permitted to be an attribute value template
804 * @param allowed list of permitted values, which must be in alphabetical order
805 */
806
807 protected void checkAttributeValue(String name, String value, boolean avt, String[] allowed) {
808 if (avt && value.contains("{")) {
809 return;
810 }
811 if (Arrays.binarySearch(allowed, value) < 0) {
812 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
813 sb.append("Invalid value for ");
814 sb.append("@");
815 sb.append(name);
816 sb.append(". Value must be one of (");
817 for (int i = 0; i < allowed.length; i++) {
818 sb.append(i == 0 ? "" : "|");
819 sb.append(allowed[i]);
820 }
821 sb.append(")");
822 compileError(sb.toString(), "XTSE0020");
823 }
824 }
825
826 protected final static String[] YES_NO = new String[]{"0", "1", "false", "no", "true", "yes"};
827
828
829 /**
830 * Process an attribute whose value is yes, no, true, false, 1, or 0; returning true or false.
831 *
832 * @param name the name of the attribute (used for diagnostics)
833 * @param value the value of the attribute
834 */
835
836 public boolean processBooleanAttribute(String name, String value) {
837 String s = Whitespace.trim(value);
838 if (isYes(s)) {
839 return true;
840 } else if (isNo(s)) {
841 return false;
842 } else {
843 invalidAttribute(name, "yes|no | true|false | 1|0");
844 return false; // never get here
845 }
846
847 }
848
849 static boolean isYes(String s) {
850 return "yes".equals(s) || "true".equals(s) || "1".equals(s);
851 }
852
853 static boolean isNo(String s) {
854 return "no".equals(s) || "false".equals(s) || "0".equals(s);
855 }
856
857 boolean processStreamableAtt(String streamableAtt) {
858 boolean streamable = processBooleanAttribute("streamable", streamableAtt);
859 if (streamable) {
860 if (!getConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XSLT)) {
861 compileWarning("Request for streaming ignored: this Saxon configuration does not support streaming", SaxonErrorCode.SXST0068);
862 return false;
863 }
864 if ("off".equals(getConfiguration().getConfigurationProperty(Feature.STREAMABILITY))) {
865 compileWarning("Request for streaming ignored: streaming is disabled in this Saxon configuration", SaxonErrorCode.SXST0068);
866 return false;
867 }
868 }
869 return streamable;
870 }
871
872 /**
873 * Process an attribute whose value is a SequenceType
874 *
875 * @param sequenceType the source text of the attribute
876 * @return the processed sequence type
877 * @throws XPathException if the syntax is invalid or for example if it refers to a type
878 * that is not in the static context
879 */
880
881 public SequenceType makeSequenceType(String sequenceType)
882 throws XPathException {
883 ExpressionContext env = getStaticContext();
884 int languageLevel = env.getXPathVersion();
885 if (languageLevel == 30) {
886 languageLevel = 305; // XPath 3.0 + XSLT extensions
887 }
888 XPathParser parser =
889 getConfiguration().newExpressionParser("XP", false, languageLevel);
890 QNameParser qp = new QNameParser(staticContext.getNamespaceResolver());
891 qp.setAcceptEQName(staticContext.getXPathVersion() >= 30);
892 qp.setDefaultNamespace("");
893 qp.setErrorOnBadSyntax("XPST0003");
894 qp.setErrorOnUnresolvedPrefix("XPST0081");
895 parser.setQNameParser(qp);
896 return parser.parseSequenceType(sequenceType, staticContext);
897 }
898
899 public SequenceType makeExtendedSequenceType(String sequenceType)
900 throws XPathException {
901 getStaticContext();
902 XPathParser parser =
903 getConfiguration().newExpressionParser("XP", false, 31);
904 QNameParser qp = new QNameParser(staticContext.getNamespaceResolver());
905 qp.setAcceptEQName(staticContext.getXPathVersion() >= 30);
906 qp.setDefaultNamespace("");
907 qp.setErrorOnBadSyntax("XPST0003");
908 qp.setErrorOnUnresolvedPrefix("XPST0081");
909 parser.setQNameParser(qp);
910 return parser.parseExtendedSequenceType(sequenceType, staticContext);
911 }
912
913 /**
914 * Process the [xsl:]extension-element-prefixes attribute if there is one
915 *
916 * @param ns the namespace URI of the attribute - either the XSLT namespace or "" for the null namespace
917 */
918
919 protected void processExtensionElementAttribute(String ns) {
920 String ext = getAttributeValue(ns, "extension-element-prefixes");
921 if (ext != null) {
922 // go round twice, once to count the values and next to add them to the array
923 int count = 0;
924 StringTokenizer st1 = new StringTokenizer(ext, " \t\n\r", false);
925 while (st1.hasMoreTokens()) {
926 st1.nextToken();
927 count++;
928 }
929 extensionNamespaces = new String[count];
930 count = 0;
931 StringTokenizer st2 = new StringTokenizer(ext, " \t\n\r", false);
932 while (st2.hasMoreTokens()) {
933 String s = st2.nextToken();
934 if ("#default".equals(s)) {
935 s = "";
936 }
937 String uri = getURIForPrefix(s, false);
938 if (uri == null) {
939 compileError("Namespace prefix " + s + " is undeclared", "XTSE1430");
940 extensionNamespaces[count++] = NamespaceConstant.SAXON; // for recovery
941 } else if (NamespaceConstant.isReserved(uri)) {
942 compileError("Namespace " + uri + " is reserved: it cannot be used for extension instructions " +
943 "(perhaps exclude-result-prefixes was intended).",
944 "XTSE0085");
945 extensionNamespaces[count++] = NamespaceConstant.SAXON; // for recovery
946 } else {
947 extensionNamespaces[count++] = uri;
948 }
949 }
950 }
951 }
952
953 /**
954 * Process the [xsl:]exclude-result-prefixes attribute if there is one
955 *
956 * @param ns the namespace URI of the attribute required, either the XSLT namespace or ""
957 */
958
959 protected void processExcludedNamespaces(String ns) {
960 String ext = getAttributeValue(ns, "exclude-result-prefixes");
961 if (ext != null) {
962 if ("#all".equals(Whitespace.trim(ext))) {
963 Iterator<NamespaceBinding> codes = NamespaceIterator.iterateNamespaces(this);
964 List<String> excluded = new ArrayList<>();
965 while (codes.hasNext()) {
966 excluded.add(codes.next().getURI());
967 }
968 excludedNamespaces = excluded.toArray(new String[0]);
969 } else {
970 // go round twice, once to count the values and next to add them to the array
971 int count = 0;
972 StringTokenizer st1 = new StringTokenizer(ext, " \t\n\r", false);
973 while (st1.hasMoreTokens()) {
974 st1.nextToken();
975 count++;
976 }
977 excludedNamespaces = new String[count];
978 count = 0;
979 StringTokenizer st2 = new StringTokenizer(ext, " \t\n\r", false);
980 while (st2.hasMoreTokens()) {
981 String s = st2.nextToken();
982 if ("#default".equals(s)) {
983 s = "";
984 } else if ("#all".equals(s)) {
985 compileError("In exclude-result-prefixes, cannot mix #all with other values", "XTSE0020");
986 }
987 String uri = getURIForPrefix(s, true);
988 if (uri == null) {
989 excludedNamespaces = null;
990 compileError("Namespace prefix " + s + " is not declared", "XTSE0808");
991 break;
992 }
993 excludedNamespaces[count++] = uri;
994 if (s.isEmpty() && uri.isEmpty()) {
995 compileError("Cannot exclude the #default namespace when no default namespace is declared",
996 "XTSE0809");
997 }
998 }
999 }
1000 }
1001 }
1002
1003 /**
1004 * Process the [xsl:]version attribute if there is one
1005 *
1006 * @param ns the namespace URI of the attribute required, either the XSLT namespace or ""
1007 */
1008
1009 protected void processVersionAttribute(String ns) {
1010 String v = Whitespace.trim(getAttributeValue(ns, "version"));
1011 if (v != null) {
1012 ConversionResult val = BigDecimalValue.makeDecimalValue(v, true);
1013 if (val instanceof ValidationFailure) {
1014 version = 30;
1015 compileError("The version attribute must be a decimal literal", "XTSE0110");
1016 } else {
1017 // Note this will normalize the decimal so that trailing spaces are not significant
1018 version = ((BigDecimalValue) val).getDecimalValue().multiply(BigDecimal.TEN).intValue();
1019 if (version < 20 && version != 10) {
1020 // XSLT 2.0 says use backwards compatible mode. XSLT 3.0 says we can raise an error.
1021 // Both allow a warning
1022 issueWarning("Unrecognized version " + val + ": treated as 1.0", this);
1023 version = 10;
1024 } else if (version > 20 && version < 30) {
1025 issueWarning("Unrecognized version " + val + ": treated as 2.0", this);
1026 version = 20;
1027 }
1028 }
1029 }
1030 }
1031
1032 /**
1033 * Get the numeric value of the version number appearing as an attribute on this element,
1034 * or inherited from its ancestors
1035 *
1036 * @return the version number times ten as an integer
1037 */
1038
1039 public int getEffectiveVersion() {
1040 if (version == -1) {
1041 NodeInfo node = getParent();
1042 if (node instanceof StyleElement) {
1043 version = ((StyleElement) node).getEffectiveVersion();
1044 } else {
1045 return 20; // defensive programming
1046 }
1047 }
1048 return version;
1049 }
1050
1051 /**
1052 * Get the effective version in a form suitable for display (for example "1.0" or "2.0")
1053 *
1054 * @return the version number in conventional format
1055 */
1056
1057 public String getEffectiveVersionAsString() {
1058 return Double.toString(getEffectiveVersion() / 10);
1059 }
1060
1061 /**
1062 * Validate the value of the [xsl:]validation attribute
1063 *
1064 * @param value the raw value of the attribute
1065 * @return the encoded value of the attribute
1066 */
1067
1068 protected int validateValidationAttribute(String value) {
1069 int code = Validation.getCode(value);
1070 if (code == Validation.INVALID) {
1071 String prefix = this instanceof LiteralResultElement ? "xsl:" : "";
1072 compileError("Invalid value of " + prefix + "validation attribute: '" + value + "'", "XTSE0020");
1073 code = getDefaultValidation();
1074 }
1075 if (!isSchemaAware()) {
1076 if (code == Validation.STRICT) {
1077 compileError("To perform validation, a schema-aware XSLT processor is needed", "XTSE1660");
1078 }
1079 code = Validation.STRIP;
1080 }
1081 return code;
1082 }
1083
1084 /**
1085 * Determine whether forwards-compatible mode is enabled for this element
1086 *
1087 * @return true if forwards-compatible mode is enabled
1088 */
1089
1090 public boolean forwardsCompatibleModeIsEnabled() {
1091 return getEffectiveVersion() > 30;
1092 }
1093
1094 /**
1095 * Determine whether 1.0-compatible mode is enabled for this element
1096 *
1097 * @return true if 1.0 compatable mode is enabled, that is, if this or an enclosing
1098 * element specifies an [xsl:]version attribute whose value is less than 2.0
1099 */
1100
1101 public boolean xPath10ModeIsEnabled() {
1102 return getEffectiveVersion() < 20;
1103 }
1104
1105 /**
1106 * Process the [xsl:]default-collation attribute if there is one.
1107 *
1108 * @throws XPathException if the value is not a valid URI, or not a recognized collation URI
1109 */
1110
1111 protected void processDefaultCollationAttribute() throws XPathException {
1112 String ns = getURI().equals(NamespaceConstant.XSLT) ? "" : NamespaceConstant.XSLT;
1113 String v = getAttributeValue(ns, "default-collation");
1114 StringBuilder reasons = new StringBuilder();
1115 if (v != null) {
1116 StringTokenizer st = new StringTokenizer(v, " \t\n\r", false);
1117 while (st.hasMoreTokens()) {
1118 String uri = st.nextToken();
1119 if (uri.equals(NamespaceConstant.CODEPOINT_COLLATION_URI)) {
1120 defaultCollationName = uri;
1121 return;
1122 } else {
1123 URI collationURI;
1124 try {
1125 collationURI = new URI(uri);
1126 if (!collationURI.isAbsolute()) {
1127 URI base = new URI(getBaseURI());
1128 collationURI = base.resolve(collationURI);
1129 uri = collationURI.toString();
1130 }
1131 } catch (URISyntaxException err) {
1132 compileError("default collation '" + uri + "' is not a valid URI");
1133 uri = NamespaceConstant.CODEPOINT_COLLATION_URI;
1134 }
1135
1136 try {
1137 if (getConfiguration().getCollation(uri) != null) {
1138 defaultCollationName = uri;
1139 return;
1140 } else {
1141 if (reasons.length() != 0) {
1142 reasons.append("; ");
1143 }
1144 reasons.append("Collation ").append(uri).append(" is not recognized");
1145
1146 }
1147 } catch (XPathException e) {
1148 if (reasons.length() != 0) {
1149 reasons.append("; ");
1150 }
1151 reasons.append("Collation ").append(uri).append(" is not recognized (").append(e.getMessage()).append(")");
1152 // Ignore an unrecognized collation URI
1153 }
1154
1155 }
1156 // if not recognized, try the next URI in order
1157 }
1158 String msg = "No recognized collation URI found in default-collation attribute";
1159 if (reasons.length() != 0) {
1160 msg += ". ";
1161 msg += reasons.toString();
1162 }
1163 compileErrorInAttribute(msg, "XTSE0125",
1164 new StructuredQName("", ns, "default-collation").getClarkName());
1165 }
1166 }
1167
1168 /**
1169 * Get the default collation for this stylesheet element. If no default collation is
1170 * specified in the stylesheet, return the Unicode codepoint collation name.
1171 *
1172 * @return the name of the default collation
1173 */
1174
1175 protected String getDefaultCollationName() {
1176 StyleElement e = this;
1177 while (true) {
1178 if (e.defaultCollationName != null) {
1179 return e.defaultCollationName;
1180 }
1181 NodeInfo p = e.getParent();
1182 if (!(p instanceof StyleElement)) {
1183 break;
1184 }
1185 e = (StyleElement) p;
1186 }
1187 return getConfiguration().getDefaultCollationName();
1188 }
1189
1190 /**
1191 * Find a named collation. Note this method should only be used at compile-time, before declarations
1192 * have been pre-processed. After that time, use getCollation().
1193 *
1194 * @param name identifies the name of the collation required
1195 * @param baseURI the base URI to be used for resolving the collation name if it is relative
1196 * @return null if the collation is not found
1197 * @throws XPathException if either URI is invalid as a URI
1198 */
1199
1200 public StringCollator findCollation(String name, String baseURI) throws XPathException {
1201 return getConfiguration().getCollation(name, baseURI);
1202 }
1203
1204 /**
1205 * Process the [xsl:]default-mode attribute if there is one
1206 *
1207 * @throws net.sf.saxon.trans.XPathException if the value is not a valid EQName, or the token #unnamed
1208 */
1209
1210 protected void processDefaultMode() throws XPathException {
1211 String ns = getURI().equals(NamespaceConstant.XSLT) ? "" : NamespaceConstant.XSLT;
1212 String v = getAttributeValue(ns, "default-mode");
1213 if (v != null) {
1214 if (v.equals("#unnamed")) {
1215 defaultMode = Mode.UNNAMED_MODE_NAME;
1216 } else {
1217 defaultMode = makeQName(v); // should check that this is actually a mode on a template
1218 }
1219 }
1220 PrincipalStylesheetModule psm = compilation.getPrincipalStylesheetModule();
1221 final StructuredQName checkedName = defaultMode;
1222 if (psm != null && psm.isDeclaredModes()) {
1223 // It will be null on the xsl:package element itself
1224 psm.addFixupAction(() -> {
1225 if (psm.getRuleManager().obtainMode(checkedName, false) == null) {
1226 XPathException err = new XPathException("Mode " + checkedName.getDisplayName() + " is not declared in an xsl:mode declaration", "XTSE3085");
1227 err.setLocation(this);
1228 throw err;
1229 }
1230 });
1231 }
1232 }
1233
1234 /**
1235 * Get the default mode for this stylesheet element.
1236 *
1237 * @return the name of the default mode, obtained by looking for the default-mode attribute on this element
1238 * and all all its ancestors. In the absence of a default-mode attribute, returns the magic value
1239 * {@link Mode#UNNAMED_MODE_NAME}
1240 */
1241
1242 public StructuredQName getDefaultMode() throws XPathException {
1243 if (defaultMode == null) {
1244 processDefaultMode();
1245 if (defaultMode == null) {
1246 NodeInfo p = getParent();
1247 if (p instanceof StyleElement) {
1248 return defaultMode = ((StyleElement) p).getDefaultMode();
1249 } else {
1250 return defaultMode = Mode.UNNAMED_MODE_NAME;
1251 }
1252 }
1253 }
1254 return defaultMode;
1255 }
1256
1257
1258 /**
1259 * Check whether a particular extension element namespace is defined on this node.
1260 * This checks this node only, not the ancestor nodes.
1261 * The implementation checks whether the prefix is included in the
1262 * [xsl:]extension-element-prefixes attribute.
1263 *
1264 * @param uri the namespace URI being tested
1265 * @return true if this namespace is defined on this element as an extension element namespace
1266 */
1267
1268 protected boolean definesExtensionElement(String uri) {
1269 if (extensionNamespaces == null) {
1270 return false;
1271 }
1272 for (String extensionNamespace : extensionNamespaces) {
1273 if (extensionNamespace.equals(uri)) {
1274 return true;
1275 }
1276 }
1277 return false;
1278 }
1279
1280 /**
1281 * Check whether a namespace uri defines an extension element. This checks whether the
1282 * namespace is defined as an extension namespace on this or any ancestor node.
1283 *
1284 * @param uri the namespace URI being tested
1285 * @return true if the URI is an extension element namespace URI
1286 */
1287
1288 public boolean isExtensionNamespace(String uri) {
1289 NodeInfo anc = this;
1290 while (anc instanceof StyleElement) {
1291 if (((StyleElement) anc).definesExtensionElement(uri)) {
1292 return true;
1293 }
1294 anc = anc.getParent();
1295 }
1296 return false;
1297 }
1298
1299 /**
1300 * Check whether this node excludes a particular namespace from the result.
1301 * This method checks this node only, not the ancestor nodes.
1302 *
1303 * @param uri the namespace URI being tested
1304 * @return true if the namespace is excluded by virtue of an [xsl:]exclude-result-prefixes attribute
1305 */
1306
1307 protected boolean definesExcludedNamespace(String uri) {
1308 if (excludedNamespaces == null) {
1309 return false;
1310 }
1311 for (String excludedNamespace : excludedNamespaces) {
1312 if (excludedNamespace.equals(uri)) {
1313 return true;
1314 }
1315 }
1316 return false;
1317 }
1318
1319 /**
1320 * Check whether a namespace uri defines an namespace excluded from the result.
1321 * This checks whether the namespace is defined as an excluded namespace on this
1322 * or any ancestor node.
1323 *
1324 * @param uri the namespace URI being tested
1325 * @return true if this namespace URI is a namespace excluded by virtue of exclude-result-prefixes
1326 * on this element or on an ancestor element
1327 */
1328
1329 public boolean isExcludedNamespace(String uri) {
1330 if (uri.equals(NamespaceConstant.XSLT) || uri.equals(NamespaceConstant.XML)) {
1331 return true;
1332 }
1333 if (isExtensionNamespace(uri)) {
1334 return true;
1335 }
1336 NodeInfo anc = this;
1337 while (anc instanceof StyleElement) {
1338 if (((StyleElement) anc).definesExcludedNamespace(uri)) {
1339 return true;
1340 }
1341 anc = anc.getParent();
1342 }
1343 return false;
1344 }
1345
1346 /**
1347 * Process the [xsl:]xpath-default-namespace attribute if there is one
1348 *
1349 * @param ns the namespace URI of the attribute required (the default namespace or the XSLT namespace.)
1350 */
1351
1352 protected void processDefaultXPathNamespaceAttribute(String ns) {
1353 String v = getAttributeValue(ns, "xpath-default-namespace");
1354 if (v != null) {
1355 defaultXPathNamespace = v;
1356 }
1357 }
1358
1359 /**
1360 * Get the default XPath namespace for elements and types
1361 *
1362 * @return the default namespace for elements and types.
1363 * Return {@link NamespaceConstant#NULL} for the non-namespace
1364 */
1365
1366 public String getDefaultXPathNamespace() {
1367 NodeInfo anc = this;
1368 while (anc instanceof StyleElement) {
1369 String x = ((StyleElement) anc).defaultXPathNamespace;
1370 if (x != null) {
1371 return x;
1372 }
1373 anc = anc.getParent();
1374 }
1375 return NamespaceConstant.NULL;
1376 // indicates that the default namespace is the null namespace
1377 }
1378
1379 /**
1380 * Process the [xsl:]expand-text attribute if there is one (and if XSLT 3.0 is enabled)
1381 *
1382 * @param ns the namespace URI of the attribute required (the default namespace or the XSLT namespace.)
1383 */
1384
1385 protected void processExpandTextAttribute(String ns) {
1386 String v = getAttributeValue(ns, "expand-text");
1387 if (v != null) {
1388 expandText = processBooleanAttribute("expand-text", v);
1389 } else {
1390 NodeInfo parent = getParent();
1391 expandText = parent instanceof StyleElement && ((StyleElement) parent).expandText;
1392 }
1393 }
1394
1395 /**
1396 * Process the [xsl:]expand-text attribute if there is one
1397 *
1398 * @param ns the namespace URI of the attribute required (the default namespace or the XSLT namespace.)
1399 */
1400
1401 protected void processDefaultValidationAttribute(String ns) {
1402 String v = getAttributeValue(ns, "default-validation");
1403 if (v != null) {
1404 int val = Validation.getCode(v);
1405 if (val == Validation.STRIP || val == Validation.PRESERVE) {
1406 defaultValidation = val;
1407 } else {
1408 compileErrorInAttribute("@default-validation must be preserve|strip", "XTSE0020", "default-validation");
1409 }
1410 }
1411 }
1412
1413 /**
1414 * Ask whether content value templates are available within this element
1415 *
1416 * @return true if content value templates are enabled
1417 */
1418
1419 public boolean isExpandingText() {
1420 return expandText;
1421 }
1422
1423
1424 /**
1425 * Get the Schema type definition for a type named in the stylesheet (in a
1426 * "type" attribute).
1427 *
1428 * @param typeAtt the value of the type attribute
1429 * @return the corresponding schema type
1430 * @throws XPathException if the type is not declared in an
1431 * imported schema, or is not a built-in type
1432 */
1433
1434 public SchemaType getSchemaType(String typeAtt) throws XPathException {
1435 try {
1436 String uri;
1437 String lname;
1438 if (typeAtt.startsWith("Q{")) {
1439 StructuredQName q = makeQName(typeAtt);
1440 uri = q.getURI();
1441 lname = q.getLocalPart();
1442 } else {
1443 String[] parts = NameChecker.getQNameParts(typeAtt);
1444 lname = parts[1];
1445 if ("".equals(parts[0])) {
1446 // Name is unprefixed: use the default-xpath-namespace
1447 uri = getDefaultXPathNamespace();
1448 } else {
1449 uri = getURIForPrefix(parts[0], false);
1450 if (uri == null) {
1451 compileError("Namespace prefix for type annotation is undeclared", "XTSE1520");
1452 return null;
1453 }
1454 }
1455 }
1456 if (uri.equals(NamespaceConstant.SCHEMA)) {
1457 SchemaType t = BuiltInType.getSchemaTypeByLocalName(lname);
1458 if (t == null) {
1459 compileError("Unknown built-in type " + typeAtt, "XTSE1520");
1460 return null;
1461 }
1462 return t;
1463 }
1464
1465 // not a built-in type: look in the imported schemas
1466
1467 if (!getPrincipalStylesheetModule().isImportedSchema(uri)) {
1468 compileError("There is no imported schema for the namespace of type " + typeAtt, "XTSE1520");
1469 return null;
1470 }
1471 StructuredQName qName = new StructuredQName("", uri, lname);
1472 SchemaType stype = getConfiguration().getSchemaType(qName);
1473 if (stype == null) {
1474 compileError("There is no type named " + typeAtt + " in an imported schema", "XTSE1520");
1475 }
1476 return stype;
1477
1478 } catch (QNameException err) {
1479 compileError("Invalid type name. " + err.getMessage(), "XTSE1520");
1480 }
1481 return null;
1482 }
1483
1484 /**
1485 * Get the type annotation to use for a given schema type
1486 *
1487 * @param schemaType the schema type
1488 * @return the corresponding numeric type annotation
1489 */
1490
1491 public SimpleType getTypeAnnotation(SchemaType schemaType) {
1492 return (SimpleType) schemaType;
1493 }
1494
1495 /**
1496 * Check that the stylesheet element is valid. This is called once for each element, after
1497 * the entire tree has been built. As well as validation, it can perform first-time
1498 * initialisation. The default implementation does nothing; it is normally overriden
1499 * in subclasses.
1500 *
1501 * @param decl the declaration to be validated
1502 * @throws XPathException if any error is found during validation
1503 */
1504
1505 public void validate(ComponentDeclaration decl) throws XPathException {
1506 }
1507
1508 /**
1509 * Hook to allow additional validation of a parent element immediately after its
1510 * children have been validated.
1511 *
1512 * @throws XPathException if any error is found during post-traversal validation
1513 */
1514
1515 public void postValidate() throws XPathException {
1516 }
1517
1518 /**
1519 * Method supplied by declaration elements to add themselves to a stylesheet-level index
1520 *
1521 * @param decl the Declaration being indexed. (This corresponds to the StyleElement object
1522 * except in cases where one module is imported several times with different precedence.)
1523 * @param top represents the outermost XSLStylesheet or XSLPackage element
1524 * @throws XPathException if any error is encountered
1525 */
1526
1527 public void index(ComponentDeclaration decl, PrincipalStylesheetModule top) throws XPathException {
1528 }
1529
1530 /**
1531 * Type-check an expression. This is called to check each expression while the containing
1532 * instruction is being validated. It is not just a static type-check, it also adds code
1533 * to perform any necessary run-time type checking and/or conversion.
1534 *
1535 * @param name the name of the attribute containing the expression to be checked (used for diagnostics)
1536 * @param exp the expression to be checked
1537 * @return the (possibly rewritten) expression after type checking
1538 * @throws XPathException if type-checking fails statically, that is, if it can be determined that the
1539 * supplied value for the expression cannot possibly be of the required type
1540 */
1541
1542 // Note: the typeCheck() call is done at the level of individual path expression; the optimize() call is done
1543 // for a template or function as a whole. We can't do it all at the function/template level because
1544 // the static context (e.g. namespaces) changes from one XPath expression to another.
1545 public Expression typeCheck(String name, Expression exp) throws XPathException {
1546
1547 if (exp == null) {
1548 return null;
1549 }
1550 Configuration config = getConfiguration();
1551 if (config.getBooleanProperty(Feature.STRICT_STREAMABILITY)) {
1552 return exp;
1553 }
1554 try {
1555 exp = exp.typeCheck(makeExpressionVisitor(), config.makeContextItemStaticInfo(Type.ITEM_TYPE, true));
1556 exp = ExpressionTool.resolveCallsToCurrentFunction(exp);
1557 // if (explaining) {
1558 // System.err.println("Attribute '" + name + "' of element '" + getDisplayName() + "' at line " + getLineNumber() + ':');
1559 // System.err.println("Static type: " +
1560 // SequenceType.makeSequenceType(exp.getItemType(), exp.getCardinality()));
1561 // System.err.println("Optimized expression tree:");
1562 // exp.display(10, getNamePool(), System.err);
1563 // }
1564 CodeInjector injector = getCompilation().getCompilerInfo().getCodeInjector();
1565 if (injector != null) {
1566 return injector.inject(exp, getStaticContext(), LocationKind.XPATH_IN_XSLT, new StructuredQName("", "", name));
1567 }
1568 return exp;
1569 } catch (XPathException err) {
1570 // we can't report a dynamic error such as divide by zero unless the expression
1571 // is actually executed.
1572 //err.printStackTrace();
1573 if (err.isReportableStatically()) {
1574 err.setLocation(new AttributeLocation(this, StructuredQName.fromClarkName(name)));
1575 compileError(err);
1576 return exp;
1577 } else {
1578 ErrorExpression erexp = new ErrorExpression(err);
1579 erexp.setLocation(allocateLocation());
1580 return erexp;
1581 }
1582 }
1583 }
1584
1585 /**
1586 * Allocate slots in the local stack frame to range variables used in an XPath expression
1587 *
1588 * @param exp the XPath expression for which slots are to be allocated
1589 */
1590
1591 public void allocateLocalSlots(Expression exp) {
1592 SlotManager slotManager = getContainingSlotManager();
1593 if (slotManager == null) {
1594 throw new AssertionError("Slot manager has not been allocated");
1595 } else {
1596 int firstSlot = slotManager.getNumberOfVariables();
1597 int highWater = ExpressionTool.allocateSlots(exp, firstSlot, slotManager);
1598 if (highWater > firstSlot) {
1599 slotManager.setNumberOfVariables(highWater);
1600 // This algorithm is not very efficient because it never reuses
1601 // a slot when a variable goes out of scope. But at least it is safe.
1602 // Note that range variables within XPath expressions need to maintain
1603 // a slot until the instruction they are part of finishes, e.g. in
1604 // xsl:for-each.
1605 }
1606 }
1607 }
1608
1609 /**
1610 * Type-check a pattern. This is called to check each pattern while the containing
1611 * instruction is being validated. It is not just a static type-check, it also adds code
1612 * to perform any necessary run-time type checking and/or conversion.
1613 *
1614 * @param name the name of the attribute holding the pattern, for example "match": used in
1615 * diagnostics
1616 * @param pattern the compiled pattern
1617 * @return the original pattern, or a substitute pattern if it has been rewritten. Returns null
1618 * if and only if the supplied pattern is null.
1619 * @throws net.sf.saxon.trans.XPathException if the pattern fails optimistic static type-checking
1620 */
1621
1622 public Pattern typeCheck(String name, Pattern pattern) throws XPathException {
1623 if (pattern == null) {
1624 return null;
1625 }
1626 try {
1627 ItemType cit = Type.ITEM_TYPE;
1628 pattern = pattern.typeCheck(makeExpressionVisitor(), getConfiguration().makeContextItemStaticInfo(cit, true));
1629 boolean usesCurrent = false;
1630
1631 for (Operand o : pattern.operands()) {
1632 Expression filter = o.getChildExpression();
1633 if (ExpressionTool.callsFunction(filter, Current.FN_CURRENT, false)) {
1634 usesCurrent = true;
1635 break;
1636 }
1637 }
1638 if (usesCurrent) {
1639 PatternThatSetsCurrent p2 = new PatternThatSetsCurrent(pattern);
1640 pattern.bindCurrent(p2.getCurrentBinding());
1641 pattern = p2;
1642 }
1643
1644 return pattern;
1645 } catch (XPathException err) {
1646 // we can't report a dynamic error such as divide by zero unless the pattern
1647 // is actually executed. We don't have an error pattern available, so we
1648 // construct one
1649 if (err.isReportableStatically()) {
1650 XPathException e2 = new XPathException("Error in " + name + " pattern", err);
1651 e2.setLocator(this);
1652 e2.setErrorCodeQName(err.getErrorCodeQName());
1653 throw e2;
1654 } else {
1655 Pattern p = new BasePatternWithPredicate(
1656 new NodeTestPattern(ErrorType.getInstance()), new ErrorExpression(err));
1657 p.setLocation(allocateLocation());
1658 return p;
1659 }
1660 }
1661 }
1662
1663 /**
1664 * Fix up references from XPath expressions. Overridden for function declarations
1665 * and variable declarations
1666 *
1667 * @throws net.sf.saxon.trans.XPathException if any references cannot be fixed up.
1668 */
1669
1670 public void fixupReferences() throws XPathException {
1671 iterateAxis(AxisInfo.CHILD).forEachOrFail(child -> {
1672 if (child instanceof StyleElement) {
1673 ((StyleElement) child).fixupReferences();
1674 }
1675 });
1676 }
1677
1678 /**
1679 * Get the SlotManager for the containing Procedure definition
1680 *
1681 * @return the SlotManager associated with the containing Function, Template, etc,
1682 * or null if there is no such containing Function, Template etc.
1683 */
1684
1685 public SlotManager getContainingSlotManager() {
1686 NodeImpl node = this;
1687 while (true) {
1688 NodeImpl next = node.getParent();
1689 assert next != null;
1690 if (next instanceof XSLModuleRoot || next.getFingerprint() == StandardNames.XSL_OVERRIDE) {
1691 if (node instanceof StylesheetComponent) {
1692 return ((StylesheetComponent) node).getSlotManager();
1693 } else {
1694 return null;
1695 }
1696 }
1697 node = next;
1698 }
1699 }
1700
1701
1702 /**
1703 * Recursive walk through the stylesheet to validate all nodes
1704 *
1705 * @param decl the declaration to be validated
1706 * @param excludeStylesheet true if the XSLStylesheet element is to be excluded
1707 * @throws XPathException if validation fails
1708 */
1709
1710 public void validateSubtree(ComponentDeclaration decl, boolean excludeStylesheet) throws XPathException {
1711 if (isActionCompleted(StyleElement.ACTION_VALIDATE)) {
1712 return;
1713 }
1714 setActionCompleted(StyleElement.ACTION_VALIDATE);
1715 if (validationError != null) {
1716 if (reportingCircumstances == REPORT_ALWAYS) {
1717 compileError(validationError);
1718 } else if (reportingCircumstances == REPORT_UNLESS_FORWARDS_COMPATIBLE
1719 && !forwardsCompatibleModeIsEnabled()) {
1720 compileError(validationError);
1721 } else if (reportingCircumstances == REPORT_STATICALLY_UNLESS_FALLBACK_AVAILABLE) {
1722 boolean hasFallback = false;
1723 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
1724 NodeInfo child;
1725 while ((child = kids.next()) != null) {
1726 if (child instanceof XSLFallback) {
1727 hasFallback = true;
1728 ((XSLFallback) child).validateSubtree(decl, false);
1729 }
1730 }
1731 if (!hasFallback) {
1732 compileError(validationError);
1733 }
1734
1735 } else if (reportingCircumstances == REPORT_DYNAMICALLY_UNLESS_FALLBACK_AVAILABLE) {
1736 iterateAxis(AxisInfo.CHILD).forEachOrFail(child -> {
1737 if (child instanceof XSLFallback) {
1738 ((XSLFallback) child).validateSubtree(decl, false);
1739 }
1740 });
1741 }
1742 } else {
1743 try {
1744 validate(decl);
1745 } catch (XPathException err) {
1746 compileError(err);
1747 }
1748 validateChildren(decl, excludeStylesheet);
1749 if (getCompilation().getErrorCount() == 0) {
1750 postValidate();
1751 }
1752 }
1753 }
1754
1755 /**
1756 * Validate the children of this node, recursively. Overridden for top-level
1757 * data elements.
1758 *
1759 * @param decl the declaration whose children are to be validated
1760 * @param excludeStylesheet true if the xsl:stylesheet element is to be excluded
1761 * @throws XPathException if validation fails
1762 */
1763
1764 protected void validateChildren(ComponentDeclaration decl, boolean excludeStylesheet) throws XPathException {
1765 boolean containsInstructions = mayContainSequenceConstructor();
1766 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
1767 StyleElement lastChild = null;
1768 boolean endsWithTextTemplate = false;
1769 NodeInfo child;
1770 while ((child = kids.next()) != null) {
1771 if (child instanceof StyleElement) {
1772 if (!(excludeStylesheet && child instanceof XSLStylesheet)) {
1773 endsWithTextTemplate = false;
1774 if (containsInstructions && !((StyleElement) child).isInstruction()
1775 && !isPermittedChild((StyleElement) child)) {
1776 ((StyleElement) child).compileError("An " + getDisplayName() + " element must not contain an " +
1777 child.getDisplayName() + " element", "XTSE0010");
1778 }
1779 ((StyleElement) child).validateSubtree(decl, excludeStylesheet);
1780 lastChild = (StyleElement) child;
1781 }
1782 } else {
1783 endsWithTextTemplate = examineTextNode(child);
1784 }
1785 }
1786 if (lastChild instanceof XSLLocalVariable &&
1787 !(this instanceof XSLStylesheet) && !endsWithTextTemplate) {
1788 lastChild.compileWarning("A variable with no following sibling instructions has no effect",
1789 SaxonErrorCode.SXWN9001);
1790 }
1791 }
1792
1793 /**
1794 * Examine a text node in the stylesheet to see if it is a text value template
1795 *
1796 * @param node the text node
1797 * @throws XPathException if the node is is a text value template with variable content
1798 */
1799
1800 private boolean examineTextNode(NodeInfo node) throws XPathException {
1801 if (node instanceof TextValueTemplateNode) {
1802 ((TextValueTemplateNode) node).validate();
1803 return !(((TextValueTemplateNode) node).getContentExpression() instanceof Literal);
1804 } else {
1805 return false;
1806 }
1807 }
1808
1809 /**
1810 * Check whether a given child is permitted for this element. This method is used when a non-instruction
1811 * child element such as xsl:sort is encountered in a context where instructions would normally be expected.
1812 *
1813 * @param child the child that may or may not be permitted
1814 * @return true if the child is permitted.
1815 */
1816
1817 protected boolean isPermittedChild(StyleElement child) {
1818 return false;
1819 }
1820
1821 /**
1822 * Get the principal stylesheet module of the package in which
1823 * this XSLT element appears
1824 *
1825 * @return the containing package
1826 */
1827
1828 public PrincipalStylesheetModule getPrincipalStylesheetModule() {
1829 return getCompilation().getPrincipalStylesheetModule();
1830 }
1831
1832 /**
1833 * Get the containing package (the principal stylesheet module of the package in which
1834 * this XSLT element appears)
1835 *
1836 * @return the containing package. May be null if the method is called during initialization.
1837 */
1838
1839 public StylesheetPackage getContainingPackage() {
1840 PrincipalStylesheetModule psm = getPrincipalStylesheetModule();
1841 return psm==null ? null : psm.getStylesheetPackage();
1842 }
1843
1844 /**
1845 * Check that among the children of this element, any xsl:sort elements precede any other elements
1846 *
1847 * @param sortRequired true if there must be at least one xsl:sort element
1848 */
1849
1850 protected void checkSortComesFirst(boolean sortRequired) {
1851 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
1852 boolean sortFound = false;
1853 boolean nonSortFound = false;
1854 NodeInfo child;
1855 while ((child = kids.next()) != null) {
1856 if (child instanceof XSLSort) {
1857 if (nonSortFound) {
1858 ((XSLSort) child).compileError("Within " + getDisplayName() +
1859 ", xsl:sort elements must come before other instructions", "XTSE0010");
1860 }
1861 sortFound = true;
1862 } else if (child.getNodeKind() == Type.TEXT) {
1863 // with xml:space=preserve, white space nodes may still be there
1864 if (!Whitespace.isWhite(child.getStringValueCS())) {
1865 nonSortFound = true;
1866 }
1867 } else {
1868 nonSortFound = true;
1869 }
1870 }
1871 if (sortRequired && !sortFound) {
1872 compileError(getDisplayName() + " must have at least one xsl:sort child", "XTSE0010");
1873 }
1874 }
1875
1876 /**
1877 * Convenience method to check that the stylesheet element is at the top level (that is,
1878 * as a child of xsl:stylesheet or xsl:transform)
1879 *
1880 * @param errorCode the error to throw if it is not at the top level; defaults to XTSE0010
1881 * if the value is null
1882 * @param allowOverride true if the element is allowed to appear as a child of xsl:override
1883 */
1884
1885 public void checkTopLevel(/*@NotNull*/ String errorCode, boolean allowOverride) {
1886 NodeImpl parent = getParent();
1887 assert parent != null;
1888 if (parent.getFingerprint() == StandardNames.XSL_OVERRIDE) {
1889 if (!allowOverride) {
1890 compileError("Element " + getDisplayName() + " is not allowed as a child of xsl:override");
1891 }
1892 } else if (!isTopLevel()) {
1893 compileError("Element " + getDisplayName() + " must be top-level (a child of xsl:stylesheet, xsl:transform, or xsl:package)", errorCode);
1894 }
1895 }
1896
1897 /**
1898 * Convenience method to check that the stylesheet element is empty
1899 */
1900
1901 public void checkEmpty() {
1902 if (hasChildNodes()) {
1903 compileError("Element must be empty", "XTSE0260");
1904 }
1905 }
1906
1907 /**
1908 * Convenience method to report the absence of a mandatory attribute
1909 *
1910 * @param attribute the name of the attribute whose absence is to be reported
1911 */
1912
1913 public void reportAbsence(String attribute) {
1914 compileError("Element must have an " + Err.wrap(attribute, Err.ATTRIBUTE) + " attribute", "XTSE0010");
1915 }
1916
1917
1918 /**
1919 * Compile the instruction on the stylesheet tree into an executable instruction
1920 * for use at run-time.
1921 *
1922 * @param compilation the compilation episode
1923 * @param decl the containing top-level declaration, for example xsl:function or xsl:template
1924 * @return either a ComputedExpression, or null. The value null is returned when compiling an instruction
1925 * that returns a no-op, or when compiling a top-level object such as an xsl:template that compiles
1926 * into something other than an instruction.
1927 * @throws net.sf.saxon.trans.XPathException if validation fails
1928 */
1929
1930 public Expression compile(Compilation compilation, ComponentDeclaration decl) throws XPathException {
1931 // no action: default for non-instruction elements
1932 return null;
1933 }
1934
1935 protected boolean isWithinDeclaredStreamableConstruct() {
1936 String streamableAtt = getAttributeValue("streamable");
1937 if (streamableAtt != null) {
1938 return processStreamableAtt(streamableAtt);
1939 }
1940 NodeInfo parent = getParent();
1941 return parent instanceof StyleElement && ((StyleElement) parent).isWithinDeclaredStreamableConstruct();
1942 }
1943
1944 protected String generateId() {
1945 FastStringBuffer buff = new FastStringBuffer(FastStringBuffer.C16);
1946 generateId(buff);
1947 return buff.toString();
1948 }
1949
1950 /**
1951 * Compile a declaration in the stylesheet tree
1952 * for use at run-time.
1953 *
1954 * @param compilation the compilation episode
1955 * @param decl the containing top-level declaration, for example xsl:function or xsl:template
1956 * @throws net.sf.saxon.trans.XPathException if compilation fails
1957 */
1958
1959 public void compileDeclaration(Compilation compilation, ComponentDeclaration decl) throws XPathException {
1960 // no action: default for elements that are not declarations
1961 }
1962
1963 /**
1964 * Compile the children of this instruction on the stylesheet tree, adding the
1965 * subordinate instructions to the parent instruction on the execution tree.
1966 *
1967 * @param compilation the Executable
1968 * @param decl the Declaration of the containing top-level stylesheet element
1969 * @param includeParams true if xsl:param elements are to be treated as child instructions (true
1970 * for templates but not for functions)
1971 * @return the compiled sequence constructor
1972 * @throws net.sf.saxon.trans.XPathException if compilation fails
1973 */
1974
1975 public Expression compileSequenceConstructor(Compilation compilation, ComponentDeclaration decl,
1976 boolean includeParams)
1977 throws XPathException {
1978 // If there are any xsl:on-empty or xsl:on-non-empty children, then reorder the children so
1979 // that local variable declarations come first. This is necessary to ensure that the instructions
1980 // remain part of a single "block", since the containing block affects the semantics of
1981 // on-empty and on-non-empty. Moving variables to come first would probably be a safe strategy in all
1982 // cases, but there might be a performance disadvantage in some cases, and it's unnecessarily disruptive,
1983 // especially if there are calls on user extension functions having side-effects.
1984 // Note: we have already bound variable references to their declarations at this stage, so the reordering
1985 // does not change the scope of variables.
1986 // We also move any on-empty instructions to the end of the list, since this makes streaming easier.
1987 boolean containsEmptyTest = false;
1988 boolean containsLocalVariable = false;
1989 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
1990 NodeInfo child;
1991 while ((child = kids.next()) != null) {
1992 int fp = child.getFingerprint();
1993 if (fp == StandardNames.XSL_VARIABLE) {
1994 containsLocalVariable = true;
1995 }
1996 if (fp == StandardNames.XSL_ON_EMPTY || fp == StandardNames.XSL_ON_NON_EMPTY) {
1997 containsEmptyTest = true;
1998 }
1999 }
2000 if (containsEmptyTest) {
2001 List<NodeInfo> vars = new ArrayList<>();
2002 List<NodeInfo> onEmpties = new ArrayList<>();
2003 List<NodeInfo> others = new ArrayList<>();
2004 iterateAxis(AxisInfo.CHILD).forEach(kid -> {
2005 int fp = kid.getFingerprint();
2006 if (fp == StandardNames.XSL_VARIABLE || fp == StandardNames.XSL_PARAM) {
2007 vars.add(kid);
2008 } else if (fp == StandardNames.XSL_ON_EMPTY) {
2009 onEmpties.add(kid);
2010 } else {
2011 others.add(kid);
2012 }
2013 });
2014 vars.addAll(others);
2015 vars.addAll(onEmpties);
2016 return compileSequenceConstructor(compilation, decl, new ListIterator<>(vars), includeParams);
2017 } else {
2018 return compileSequenceConstructor(compilation, decl, iterateAxis(AxisInfo.CHILD), includeParams);
2019 }
2020 }
2021
2022
2023 /**
2024 * Compile the children of this instruction on the stylesheet tree, adding the
2025 * subordinate instructions to the parent instruction on the execution tree.
2026 *
2027 * @param compilation the Executable
2028 * @param decl the Declaration of the containing top-level stylesheet element
2029 * @param iter Iterator over the children. This is used in the case where there are children
2030 * that are not part of the sequence constructor, for example the xsl:sort children of xsl:for-each;
2031 * the iterator can be positioned past such elements.
2032 * @param includeParams true if xsl:param elements are to be treated as child instructions (true
2033 * for templates but not for functions)
2034 * @return the compiled sequence constructor
2035 * @throws net.sf.saxon.trans.XPathException if compilation fails
2036 */
2037
2038 public Expression compileSequenceConstructor(Compilation compilation, ComponentDeclaration decl,
2039 SequenceIterator iter, boolean includeParams)
2040 throws XPathException {
2041
2042 Location locationId = allocateLocation();
2043 List<Expression> contents = new ArrayList<>(10);
2044 boolean containsSpecials = false;
2045 NodeInfo node;
2046 while ((node = (NodeInfo) iter.next()) != null) {
2047 if (node.getNodeKind() == Type.TEXT) {
2048 if (isExpandingText()) {
2049 compileContentValueTemplate((TextImpl) node, contents);
2050 } else {
2051 // handle literal text nodes by generating an xsl:value-of instruction, unless expand-text is enabled
2052 AxisIterator lookahead = node.iterateAxis(AxisInfo.FOLLOWING_SIBLING);
2053 NodeInfo sibling = lookahead.next();
2054 if (!(sibling instanceof XSLLocalParam || sibling instanceof XSLSort
2055 || sibling instanceof XSLContextItem || sibling instanceof XSLOnCompletion)) {
2056 // The test for XSLParam and XSLSort is to eliminate whitespace nodes that have been retained
2057 // because of xml:space="preserve"
2058 Expression text = new ValueOf(new StringLiteral(node.getStringValue()), false, false);
2059 text.setLocation(allocateLocation());
2060
2061 CodeInjector injector = getCompilation().getCompilerInfo().getCodeInjector();
2062 if (injector != null) {
2063 Expression tracer = injector.inject(text, getStaticContext(), StandardNames.XSL_TEXT, null);
2064 tracer.setLocation(text.getLocation());
2065 text = tracer;
2066 }
2067
2068 contents.add(text);
2069 }
2070 }
2071
2072 } else if (node instanceof XSLLocalVariable) {
2073 XSLLocalVariable var = (XSLLocalVariable) node;
2074 SourceBinding sourceBinding = var.getSourceBinding();
2075 var.compileLocalVariable(compilation, decl);
2076
2077 Expression tail = compileSequenceConstructor(compilation, decl, iter, includeParams);
2078 if (tail == null || Literal.isEmptySequence(tail)) {
2079 // this doesn't happen, because if there are no instructions following
2080 // a variable, we'll have taken the var==null path above
2081 //return result;
2082 } else {
2083 LetExpression let = new LetExpression();
2084 let.setInstruction(true);
2085 let.setRequiredType(var.getRequiredType());
2086 let.setVariableQName(sourceBinding.getVariableQName());
2087 let.setSequence(sourceBinding.getSelectExpression());
2088 let.setAction(tail);
2089 sourceBinding.fixupBinding(let);
2090 locationId = ((StyleElement) node).allocateLocation();
2091 let.setLocation(locationId);
2092 if (getCompilation().getCompilerInfo().isCompileWithTracing()) {
2093 TraceExpression t = new TraceExpression(let);
2094 t.setConstructType(LocationKind.LET_EXPRESSION);
2095 t.setObjectName(var.getSourceBinding().getVariableQName());
2096 t.setNamespaceResolver(getNamespaceResolver());
2097 contents.add(t);
2098 } else {
2099 contents.add(let);
2100 }
2101 if (var.changesRetainedStaticContext()) {
2102 let.setRetainedStaticContext(makeRetainedStaticContext());
2103 }
2104 //result.setLocationId(locationId);
2105 }
2106
2107
2108 } else if (node instanceof StyleElement) {
2109 StyleElement snode = (StyleElement) node;
2110 int fp = snode.getFingerprint();
2111 if (fp == StandardNames.XSL_ON_EMPTY || fp == StandardNames.XSL_ON_NON_EMPTY) {
2112 containsSpecials = true;
2113 }
2114 Expression child;
2115 if (snode.validationError != null && !(snode instanceof AbsentExtensionElement)) {
2116 if (snode.reportingCircumstances == REPORT_IF_INSTANTIATED) {
2117 child = new ErrorExpression(snode.validationError);
2118 } else {
2119 child = fallbackProcessing(compilation, decl, snode);
2120 }
2121
2122 } else {
2123 child = snode.compile(compilation, decl);
2124 if (child != null) {
2125 if (snode.changesRetainedStaticContext()) {
2126 child.setRetainedStaticContext(snode.makeRetainedStaticContext());
2127 }
2128 if ((includeParams || !(node instanceof XSLLocalParam))
2129 && getCompilation().getCompilerInfo().isCompileWithTracing()) {
2130 child = makeTraceInstruction(snode, child);
2131 }
2132 }
2133 }
2134 if (child != null) {
2135 contents.add(child);
2136 }
2137 }
2138 }
2139 if (containsSpecials) {
2140 return new ConditionalBlock(contents);
2141 }
2142 Expression block = Block.makeBlock(contents);
2143 if (block.getLocation() == null) {
2144 block.setLocation(locationId);
2145 }
2146 if (block.getLocalRetainedStaticContext() == null) {
2147 block.setRetainedStaticContext(makeRetainedStaticContext());
2148 }
2149 return block;
2150 }
2151
2152 /**
2153 * Compile a content value text node.
2154 *
2155 * @param node the text node potentially containing the template
2156 * @param contents a list to which expressions representing the fixed and variable parts of the content template
2157 * will be appended
2158 */
2159
2160 public void compileContentValueTemplate(TextImpl node, List<Expression> contents) {
2161 if (node instanceof TextValueTemplateNode) {
2162 Expression exp = ((TextValueTemplateNode) node).getContentExpression();
2163 if (getConfiguration().getBooleanProperty(Feature.STRICT_STREAMABILITY) && !(exp instanceof Literal)) {
2164 exp = new SequenceInstr(exp);
2165 }
2166 contents.add(exp);
2167 } else {
2168 contents.add(new StringLiteral(node.getStringValue()));
2169 }
2170 }
2171
2172
2173 /**
2174 * Create a trace instruction to wrap a real instruction
2175 *
2176 * @param source the parent element
2177 * @param child the compiled expression tree for the instruction to be traced
2178 * @return a wrapper instruction that performs the tracing (if activated at run-time)
2179 */
2180
2181 protected static Expression makeTraceInstruction(StyleElement source, Expression child) {
2182 if (child instanceof TraceExpression && !(source instanceof StylesheetComponent)) {
2183 return child;
2184 // this can happen, for example, after optimizing a compile-time xsl:if
2185 }
2186 if (source instanceof XSLOnEmpty || source instanceof XSLOnNonEmpty) {
2187 // Cannot wrap these in a trace instruction because this changes the scope of the "emptiness" test
2188 return child;
2189 }
2190 CodeInjector injector = source.getCompilation().getCompilerInfo().getCodeInjector();
2191 if (injector != null) {
2192 int construct = source.getFingerprint();
2193 if (source instanceof LiteralResultElement) {
2194 construct = LocationKind.LITERAL_RESULT_ELEMENT;
2195 }
2196 Expression tracer = injector.inject(child, source.getStaticContext(), construct, source.getObjectName());
2197 tracer.setLocation(source.allocateLocation());
2198 return tracer;
2199 }
2200 return child;
2201 }
2202
2203 /**
2204 * Perform fallback processing. Generate fallback code for an extension
2205 * instruction that is not recognized by the implementation.
2206 *
2207 * @param exec the Executable
2208 * @param decl the Declaration of the top-level element containing the extension instruction
2209 * @param instruction The unknown extension instruction
2210 * @return the expression tree representing the fallback code
2211 * @throws net.sf.saxon.trans.XPathException if any error occurs
2212 */
2213
2214 protected Expression fallbackProcessing(Compilation exec, ComponentDeclaration decl, StyleElement instruction)
2215 throws XPathException {
2216 // process any xsl:fallback children; if there are none,
2217 // generate code to report the original failure reason
2218 Expression fallback = null;
2219 AxisIterator kids = instruction.iterateAxis(AxisInfo.CHILD);
2220 NodeInfo child;
2221 while ((child = kids.next()) != null) {
2222 if (child instanceof XSLFallback) {
2223 //fallback.setLocationId(allocateLocationId(getSystemId(), child.getLineNumber()));
2224 //((XSLFallback)child).compileChildren(exec, fallback, true);
2225 Expression b = ((XSLFallback) child).compileSequenceConstructor(exec, decl, true);
2226 if (b == null) {
2227 b = Literal.makeEmptySequence();
2228 }
2229 if (fallback == null) {
2230 fallback = b;
2231 } else {
2232 fallback = Block.makeBlock(fallback, b);
2233 fallback.setLocation(
2234 allocateLocation());
2235 }
2236 }
2237 }
2238 if (fallback != null) {
2239 return fallback;
2240 } else {
2241 return new ErrorExpression(instruction.validationError);
2242 // compileError(instruction.validationError);
2243 // return EmptySequence.getInstance();
2244 }
2245
2246 }
2247
2248 /**
2249 * Allocate a location
2250 *
2251 * @return an location which can be used to report the location of the instruction
2252 */
2253
2254 protected Location allocateLocation() {
2255 if (savedLocation == null) {
2256 savedLocation = new ExplicitLocation(this);
2257 }
2258 return savedLocation;
2259 }
2260
2261 /**
2262 * Construct sort keys for a SortedIterator
2263 *
2264 * @param compilation the compilation episode
2265 * @param decl the declaration containing the sort keys @throws XPathException if any error is detected
2266 * @return an array of SortKeyDefinition objects if there are any sort keys;
2267 * or null if there are none.
2268 * @throws XPathException if an error is found
2269 */
2270
2271 public SortKeyDefinitionList makeSortKeys(Compilation compilation, ComponentDeclaration decl) throws XPathException {
2272 // handle sort keys if any
2273
2274 int numberOfSortKeys = 0;
2275 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
2276 NodeInfo child;
2277 while ((child = kids.next()) != null) {
2278 if (child instanceof XSLSortOrMergeKey) {
2279 ((XSLSortOrMergeKey) child).compile(compilation, decl);
2280 if (child instanceof XSLSort) {
2281 if (numberOfSortKeys != 0 && ((XSLSort) child).getStable() != null) {
2282 compileError("stable attribute may appear only on the first xsl:sort element", "XTSE1017");
2283 }
2284 }
2285 numberOfSortKeys++;
2286 }
2287 }
2288
2289 if (numberOfSortKeys > 0) {
2290 SortKeyDefinition[] keys = new SortKeyDefinition[numberOfSortKeys];
2291 kids = iterateAxis(AxisInfo.CHILD);
2292 int k = 0;
2293 while ((child = kids.next()) != null) {
2294 if (child instanceof XSLSortOrMergeKey) {
2295 keys[k++] = (SortKeyDefinition) ((XSLSortOrMergeKey) child).getSortKeyDefinition().simplify();
2296 }
2297 }
2298 return new SortKeyDefinitionList(keys);
2299
2300 } else {
2301 return null;
2302 }
2303 }
2304
2305 /**
2306 * Get the list of attribute-set names associated with this element.
2307 * This is used for xsl:element, xsl:copy, xsl:attribute-set, and on literal
2308 * result elements
2309 *
2310 * @param use the original value of the [xsl:]use-attribute-sets attribute
2311 * @return an array of names of the attribute sets
2312 */
2313
2314 protected StructuredQName[] getUsedAttributeSets(String use) {
2315
2316 List<StructuredQName> nameList = new ArrayList<>(4);
2317 StringTokenizer st = new StringTokenizer(use, " \t\n\r", false);
2318 while (st.hasMoreTokens()) {
2319 String asetname = st.nextToken();
2320 StructuredQName name;
2321 try {
2322 name = makeQName(asetname);
2323 } catch (XPathException err) {
2324 compileError(err.getMessage(), "XTSE0710");
2325 name = null;
2326 }
2327 nameList.add(name);
2328 }
2329 return nameList.toArray(new StructuredQName[0]);
2330 }
2331
2332 /**
2333 * Process the value of the visibility attribute (XSLT 3.0). Invokes
2334 * {@link #invalidAttribute(String, String)} if the value is invalid.
2335 *
2336 * @param s the value of the attribute after whitespace collapsing
2337 * @param flags contains "h" if the value "hidden" is allowed, "a" if the value "absent" is allowed
2338 * @return the corresponding visibility
2339 */
2340
2341 protected Visibility interpretVisibilityValue(String s, String flags) {
2342 for (Visibility v : Visibility.values()) {
2343 if (v.visibilityStr.equals(s) &&
2344 (flags.contains("h") || !s.equals("hidden")) &&
2345 (flags.contains("a") || !s.equals("absent"))) {
2346 return v;
2347 }
2348 }
2349 invalidAttribute("visibility", "public|final|private|abstract" +
2350 (flags.contains("h") ? "|hidden" : "") +
2351 (flags.contains("a") ? "|absent" : "")
2352 );
2353 return null;
2354 }
2355
2356 /**
2357 * Get the list of xsl:with-param elements for a calling element (apply-templates,
2358 * call-template, apply-imports, next-match). This method can be used to get either
2359 * the tunnel parameters, or the non-tunnel parameters.
2360 *
2361 * @param compilation the compilation episode
2362 * @param decl the containing stylesheet declaration
2363 * @param tunnel true if the tunnel="yes" parameters are wanted, false to get
2364 * @return an array of WithParam objects for either the ordinary parameters
2365 * or the tunnel parameters, as an array containing the results of
2366 * compiling the xsl:with-param children of this instruction (if any)
2367 * @throws XPathException if any error is detected
2368 */
2369
2370 public WithParam[] getWithParamInstructions(Expression parent, Compilation compilation, ComponentDeclaration decl, boolean tunnel)
2371 throws XPathException {
2372 int count = 0;
2373 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
2374 NodeInfo child;
2375 while ((child = kids.next()) != null) {
2376 if (child instanceof XSLWithParam) {
2377 XSLWithParam wp = (XSLWithParam) child;
2378 if (wp.getSourceBinding().hasProperty(SourceBinding.TUNNEL) == tunnel) {
2379 count++;
2380 }
2381 }
2382 }
2383 if (count == 0) {
2384 return WithParam.EMPTY_ARRAY;
2385 }
2386 WithParam[] array = new WithParam[count];
2387 count = 0;
2388 kids = iterateAxis(AxisInfo.CHILD);
2389 while ((child = kids.next()) != null) {
2390 if (child instanceof XSLWithParam) {
2391 XSLWithParam wp = (XSLWithParam) child;
2392 if (wp.getSourceBinding().hasProperty(SourceBinding.TUNNEL) == tunnel) {
2393 WithParam p = wp.compileWithParam(parent, compilation, decl);
2394 array[count++] = p;
2395 }
2396 }
2397 }
2398 return array;
2399 }
2400
2401 /**
2402 * Report an error with diagnostic information
2403 *
2404 * @param error contains information about the error
2405 */
2406
2407 public void compileError(XPathException error) {
2408 error.setIsStaticError(true);
2409 // Set the location of the error if there is no current location information,
2410 // or if the current location information is local to an XPath expression, unless we are
2411 // positioned on an xsl:function or xsl:template, in which case this would lose too much information
2412 if (error.getLocator() == null ||
2413 ((error.getLocator() instanceof ExplicitLocation ||
2414 error.getLocator() instanceof Expression) && !(this instanceof StylesheetComponent))) {
2415 error.setLocator(this);
2416 }
2417 // Add a reference to the stylesheet node to any AttributeLocation: see bug 2662
2418 if (error.getLocator() instanceof AttributeLocation) {
2419 ((AttributeLocation) error.getLocator()).setElementNode(this);
2420 }
2421 if (error.getLocator() instanceof XPathParser.NestedLocation) {
2422 Location container = ((XPathParser.NestedLocation) error.getLocator()).getContainingLocation();
2423 if (container instanceof AttributeLocation) {
2424 ((AttributeLocation) container).setElementNode(this);
2425 }
2426 }
2427 getCompilation().reportError(error);
2428 }
2429
2430 /**
2431 * Report a static error in the stylesheet
2432 *
2433 * @param message the error message
2434 */
2435
2436 public void compileError(String message) {
2437 compileError(message, "XTSE0010");
2438 }
2439
2440 /**
2441 * Compile time error, specifying an error code
2442 *
2443 * @param message the error message
2444 * @param errorCode the error code. May be null if not known or not defined
2445 */
2446
2447 public void compileError(String message, StructuredQName errorCode) {
2448 XPathException tce = new XPathException(message);
2449 tce.setErrorCodeQName(errorCode);
2450 tce.setLocator(this);
2451 compileError(tce);
2452 }
2453
2454 /**
2455 * Compile time error, specifying an error code
2456 *
2457 * @param message the error message
2458 * @param errorCode the error code. May be null if not known or not defined
2459 */
2460
2461 public void compileError(String message, String errorCode) {
2462 compileError(new XPathException(message, errorCode, this));
2463 }
2464
2465 /**
2466 * Compile time error, specifying an error code and the name of the attribute that
2467 * is in error.
2468 *
2469 * @param message the error message
2470 * @param errorCode the error code. May be null if not known or not defined
2471 * @param attributeName the name of the attribute. For attributes in no namespace
2472 * this is the local part of the name; for namespaced attributes
2473 * a name in Clark format may be supplied.
2474 */
2475
2476 public void compileErrorInAttribute(String message, String errorCode, String attributeName) {
2477 StructuredQName att = StructuredQName.fromClarkName(attributeName);
2478 Location location = new AttributeLocation(this, att);
2479 compileError(new XPathException(message, errorCode, location));
2480 }
2481
2482 protected void invalidAttribute(String attributeName, String allowedValues) {
2483 compileErrorInAttribute("Attribute " + getDisplayName() + "/@" + attributeName + " must be " + allowedValues,
2484 "XTSE0020", attributeName);
2485 }
2486
2487 protected void undeclaredNamespaceError(String prefix, String errorCode, String attributeName) {
2488 if (errorCode == null) {
2489 errorCode = "XTSE0280";
2490 }
2491 compileErrorInAttribute("Undeclared namespace prefix " + Err.wrap(prefix), errorCode, attributeName);
2492 }
2493
2494 public void compileWarning(String message, StructuredQName errorCode) {
2495 XPathException tce = new XPathException(message);
2496 tce.setErrorCodeQName(errorCode);
2497 tce.setLocator(this);
2498 getCompilation().reportWarning(tce);
2499 }
2500
2501 public void compileWarning(String message, String errorCode) {
2502 XPathException tce = new XPathException(message);
2503 tce.setErrorCode(errorCode);
2504 tce.setLocator(this);
2505 getCompilation().reportWarning(tce);
2506 }
2507
2508 /**
2509 * Report a warning to the error listener
2510 *
2511 * @param error an exception containing the warning text
2512 */
2513
2514 protected void issueWarning(XPathException error) {
2515 if (error.getLocator() == null) {
2516 error.setLocator(this);
2517 }
2518 getCompilation().reportWarning(error);
2519 }
2520
2521 /**
2522 * Report a warning to the error listener
2523 *
2524 * @param message the warning message text
2525 * @param locator the location of the problem in the source stylesheet
2526 */
2527
2528 protected void issueWarning(String message, SourceLocator locator) {
2529 XPathException tce = new XPathException(message);
2530 if (locator == null) {
2531 tce.setLocator(this);
2532 } else {
2533 tce.setLocator(locator);
2534 }
2535 issueWarning(tce);
2536 }
2537
2538 /**
2539 * Test whether this is a top-level element
2540 *
2541 * @return true if the element is a child of the xsl:stylesheet or xsl:package element
2542 */
2543
2544 public boolean isTopLevel() {
2545 return getParent() instanceof XSLModuleRoot;
2546 }
2547
2548 /**
2549 * Ask whether this is an instruction that is known to be constructing nodes which
2550 * will become children of a parent document or element node, and will not have an
2551 * independent existence of their own.
2552 *
2553 * @return true if it is known that this is an instruction that creates nodes that
2554 * will immediately be attached to a parent element or document node
2555 */
2556
2557 public boolean isConstructingComplexContent() {
2558 if (!isInstruction()) {
2559 return false;
2560 }
2561 NodeInfo parent = getParent();
2562 while (true) {
2563 if (!(parent instanceof StyleElement && ((StyleElement) parent).isInstruction())) {
2564 return false;
2565 }
2566 if (parent instanceof XSLGeneralVariable) {
2567 return ((XSLGeneralVariable) parent).getAttributeValue("as") == null;
2568 }
2569 if (parent instanceof XSLElement || parent instanceof LiteralResultElement || parent instanceof XSLDocument || parent instanceof XSLCopy) {
2570 return true;
2571 }
2572 parent = parent.getParent();
2573 }
2574 }
2575
2576 /**
2577 * Ask whether this element contains a binding for a variable with a given name; and if it does,
2578 * return the source binding information
2579 *
2580 * @param name the variable name
2581 * @return the binding information if this element binds a variable of this name; otherwise null
2582 */
2583
2584 public SourceBinding getBindingInformation(StructuredQName name) {
2585 return null;
2586 }
2587
2588 /**
2589 * Bind a variable used in this element to the compiled form of the XSLVariable element in which it is
2590 * declared
2591 *
2592 * @param qName The name of the variable
2593 * @return the XSLVariableDeclaration (that is, an xsl:variable or xsl:param instruction) for the variable,
2594 * or null if no declaration of the variable can be found
2595 */
2596
2597 public SourceBinding bindVariable(StructuredQName qName) {
2598
2599 SourceBinding decl = bindLocalVariable(qName);
2600 if (decl != null) {
2601 return decl;
2602 }
2603
2604 // Now check for a global variable
2605 // we rely on the search following the order of decreasing import precedence.
2606 SourceBinding binding = getPrincipalStylesheetModule().getGlobalVariableBinding(qName);
2607 if (binding == null || Navigator.isAncestorOrSelf(binding.getSourceElement(), this)) {
2608 // test case variable-0118
2609 return null;
2610 } else {
2611 return binding;
2612 }
2613 }
2614
2615 /**
2616 * Bind a variable reference used in this element to the compiled form of the XSLVariable element in which it is
2617 * declared, considering only local variables and params
2618 *
2619 * @param qName The name of the variable
2620 * @return the XSLVariableDeclaration (that is, an xsl:variable or xsl:param instruction) for the variable,
2621 * or null if no local declaration of the variable can be found
2622 */
2623
2624 public SourceBinding bindLocalVariable(StructuredQName qName) {
2625 NodeInfo curr = this;
2626 NodeInfo prev = this;
2627
2628 SourceBinding implicit = hasImplicitBinding(qName);
2629 if (implicit != null) {
2630 return implicit;
2631 }
2632
2633 // first search for a local variable declaration
2634 if (!isTopLevel()) {
2635 AxisIterator preceding = curr.iterateAxis(AxisInfo.PRECEDING_SIBLING);
2636 while (true) {
2637 curr = preceding.next();
2638 while (curr == null) {
2639 curr = prev.getParent();
2640 if (curr instanceof StyleElement) {
2641 implicit = ((StyleElement) curr).hasImplicitBinding(qName);
2642 if (implicit != null) {
2643 return implicit;
2644 }
2645 }
2646 while (curr instanceof StyleElement && !((StyleElement) curr).seesAvuncularVariables()) {
2647 // a local variable is not visible within a sibling xsl:fallback or xsl:catch element
2648 curr = curr.getParent();
2649 }
2650 prev = curr;
2651 if (curr.getParent() instanceof XSLModuleRoot) {
2652 break; // top level
2653 }
2654 preceding = curr.iterateAxis(AxisInfo.PRECEDING_SIBLING);
2655 curr = preceding.next();
2656 }
2657 if (curr.getParent() instanceof XSLModuleRoot) {
2658 break;
2659 }
2660 if (curr instanceof XSLGeneralVariable) {
2661 SourceBinding sourceBinding = ((XSLGeneralVariable) curr).getBindingInformation(qName);
2662 if (sourceBinding != null) {
2663 return sourceBinding;
2664 }
2665 }
2666
2667 }
2668 }
2669 return null;
2670 }
2671
2672 /**
2673 * Ask whether variables declared in an "uncle" element are visible.
2674 *
2675 * @return true for all elements except xsl:fallback and xsl:catch
2676 */
2677
2678 protected boolean seesAvuncularVariables() {
2679 return true;
2680 }
2681
2682 /**
2683 * Ask whether this particular element implicitly binds a given variable (used for xsl:accumulator-rule)
2684 */
2685
2686 protected SourceBinding hasImplicitBinding(StructuredQName name) {
2687 return null;
2688 }
2689
2690 /**
2691 * Get the type of construct. This will be a constant in
2692 * class {@link LocationKind}. This method is part of the {@link InstructionInfo} interface
2693 */
2694
2695 public int getConstructType() {
2696 return getFingerprint();
2697 }
2698
2699 /**
2700 * Get a name identifying the object of the expression, for example a function name, template name,
2701 * variable name, key name, element name, etc. This is used only where the name is known statically.
2702 * If there is no name, the value will be null.
2703 *
2704 * @return the name of the object declared in this element, if any
2705 */
2706
2707 public StructuredQName getObjectName() {
2708 return objectName;
2709 }
2710
2711 /**
2712 * Set the object name, for example the name of a function, variable, or template declared on this element
2713 *
2714 * @param qName the object name as a QName
2715 */
2716
2717 public void setObjectName(StructuredQName qName) {
2718 objectName = qName;
2719 }
2720
2721 /**
2722 * Get the value of a particular property of the instruction. This is part of the
2723 * {@link InstructionInfo} interface for run-time tracing and debugging. The properties
2724 * available include all the attributes of the source instruction (named by the attribute name):
2725 * these are all provided as string values.
2726 *
2727 * @param name The name of the required property
2728 * @return The value of the requested property, or null if the property is not available
2729 */
2730
2731 public Object getProperty(String name) {
2732 return getAttributeValue("", name);
2733 }
2734
2735 /**
2736 * Get an iterator over all the properties available. The values returned by the iterator
2737 * will be of type String, and each string can be supplied as input to the getProperty()
2738 * method to retrieve the value of the property.
2739 */
2740
2741 public Iterator<String> getProperties() {
2742 List<String> list = new ArrayList<>(10);
2743 iterateAxis(AxisInfo.ATTRIBUTE).forEach(a ->
2744 list.add(NameOfNode.makeName(a).getStructuredQName().getClarkName())
2745 );
2746 return list.iterator();
2747 }
2748
2749 /**
2750 * Ask if an action on this StyleElement has been completed
2751 *
2752 * @param action for example ACTION_VALIDATE
2753 * @return true if the action has already been performed
2754 */
2755
2756 public boolean isActionCompleted(int action) {
2757 return (actionsCompleted & action) != 0;
2758 }
2759
2760 /**
2761 * Say that an action on this StyleElement has been completed
2762 *
2763 * @param action for example ACTION_VALIDATE
2764 */
2765
2766 public void setActionCompleted(int action) {
2767 actionsCompleted |= action;
2768 }
2769
2770 }
2771