Debian Codegraph @

net/sf/saxon/tree/util/Navigator.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.tree.util;
9
10 import net.sf.saxon.Controller;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.expr.Expression;
13 import net.sf.saxon.expr.XPathContext;
14 import net.sf.saxon.expr.parser.Location;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.om.*;
17 import net.sf.saxon.pattern.*;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.iter.*;
20 import net.sf.saxon.tree.tiny.TinyElementImpl;
21 import net.sf.saxon.tree.tiny.TinyNodeImpl;
22 import net.sf.saxon.tree.tiny.TinyTextualElement;
23 import net.sf.saxon.tree.wrapper.SiblingCountingNode;
24 import net.sf.saxon.tree.wrapper.VirtualCopy;
25 import net.sf.saxon.type.*;
26
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.ArrayList;
30 import java.util.LinkedList;
31 import java.util.List;
32 import java.util.function.Predicate;
33
34
35 /**
36 * The Navigator class provides helper classes for navigating a tree, irrespective
37 * of its implementation
38 *
39 * @author Michael H. Kay
40 */
41
42
43 public final class Navigator {
44
45 // Class is never instantiated
46 private Navigator() {
47 }
48
49 /**
50 * Get the string value of an attribute of a given element, given the URI and
51 * local part of the attribute name.
52 *
53 * @param element the element on which the required attribute appears
54 * @param uri The namespace URI of the attribute name.
55 * The "no namespace" case is represented as an empty string.
56 * @param localName The local part of the attribute name.
57 * @return the attribute value, or null if the attribute is not present
58 * @since 9.0
59 */
60
61 public static String getAttributeValue(/*@NotNull*/ NodeInfo element, /*@NotNull*/ String uri, /*@NotNull*/ String localName) {
62 return element.getAttributeValue(uri, localName);
63 }
64
65 /**
66 * Get the string value of an inherited attribute of a given element, given the URI and
67 * local part of the attribute name. If the element does not have such an attribute, go up
68 * the ancestor axis to find such an attribute
69 *
70 * @param element the element where the search should start
71 * @param uri The namespace URI of the attribute name.
72 * The "no namespace" case is represented as an empty string.
73 * @param localName The local part of the attribute name.
74 * @return the attribute value, or null if the attribute is not present on any ancestor
75 * @since 9.9
76 */
77
78 public static String getInheritedAttributeValue(NodeInfo element, String uri, String localName) {
79 NodeInfo node = element;
80 while (node != null) {
81 String value = node.getAttributeValue(uri, localName);
82 if (value == null) {
83 node = node.getParent();
84 } else {
85 return value;
86 }
87 }
88 return null;
89 }
90
91 /**
92 * Helper method to get the name of a node as a structuredQName. Used from bytecode
93 * @param node the node
94 * @return the name of the node if it has a name, or null otherwise
95 */
96
97 public static StructuredQName getNodeName(NodeInfo node) {
98 if (node.getLocalPart() != null) {
99 return new StructuredQName(node.getPrefix(), node.getURI(), node.getLocalPart());
100 } else {
101 return null;
102 }
103 }
104
105 /**
106 * Helper method to get the outermost element of a document, given the document node
107 *
108 * @param doc the document node at the root of the document
109 * @return the first element child of the document node, if there is one, else null. This
110 * is often referred to as the "root element" or "document element". No error is reported
111 * if the document node has multiple element children, which can happen in a document
112 * constructed using XSLT or XQuery.
113 * @since 9.3
114 */
115
116 /*@Nullable*/
117 public static NodeInfo getOutermostElement(/*@NotNull*/ TreeInfo doc) {
118 return doc.getRootNode().iterateAxis(AxisInfo.CHILD, NodeKindTest.ELEMENT).next();
119 }
120
121 /**
122 * Helper method to construct a NodeTest for use with the {@link NodeInfo#iterateAxis} method
123 *
124 * @param pool the NamePool.
125 * @param nodeKind The kind of node required, for example {@link Type#ELEMENT} or {@link Type#ATTRIBUTE}.
126 * To select nodes of any kind, use {@link Type#NODE}.
127 * @param uri The namespace URI of the nodes to be selected. Supply null to selects nodes from any
128 * namespace or none. Supply "" to select nodes that are not in a namespace.
129 * @param localName The local name of the nodes to be selected. Supply null to select nodes irrespective
130 * of their local name.
131 * @return a NodeTest that matches the requested nodes
132 * @since 9.0
133 */
134
135 /*@Nullable*/
136 public static NodeTest makeNodeTest(/*@NotNull*/ NamePool pool, int nodeKind, /*@Nullable*/ String uri, /*@Nullable*/ String localName) {
137 if (uri == null && localName == null) {
138 return NodeKindTest.makeNodeKindTest(nodeKind);
139 } else if (uri == null) {
140 return new LocalNameTest(pool, nodeKind, localName);
141 } else if (localName == null) {
142 return new NamespaceTest(pool, nodeKind, uri);
143 } else {
144 int fp = pool.allocateFingerprint(uri, localName);
145 return new NameTest(nodeKind, fp, pool);
146 }
147 }
148
149 /**
150 * Helper method to get the base URI of an element or processing instruction node
151 *
152 * @param node the node whose base URI is required
153 * @return the base URI of the node
154 * @since 8.7
155 */
156
157 /*@Nullable*/
158 public static String getBaseURI(/*@NotNull*/ NodeInfo node) {
159 return getBaseURI(node, n -> {
160 NodeInfo parent = n.getParent();
161 return parent == null || !parent.getSystemId().equals(n.getSystemId());
162 });
163 }
164
165 /**
166 * Helper method to get the base URI of an element or processing instruction node
167 * @param node the node whose base URI is required
168 * @param isTopElementWithinEntity a predicate applied to a node that can be tested to determine
169 * if the node is an element that originated as the outermost element within
170 * an external entity. If this is the case, the rules for determining
171 * the base URI are slightly different; in particular, any @xml:base
172 * attribute on such a node is interpreted relative to the system ID of
173 * the entity, not relative to the base URI of the parent node.
174 * @return the base URI of the node
175 * @since 9.9
176 */
177
178 /*@Nullable*/
179 public static String getBaseURI(/*@NotNull*/ NodeInfo node, Predicate<NodeInfo> isTopElementWithinEntity) {
180 String xmlBase = node instanceof TinyElementImpl ?
181 ((TinyElementImpl)node).getAttributeValue(StandardNames.XML_BASE) :
182 node.getAttributeValue(NamespaceConstant.XML, "base");
183 if (xmlBase != null) {
184 URI baseURI;
185 try {
186 baseURI = new URI(xmlBase);
187 if (!baseURI.isAbsolute()) {
188 NodeInfo parent = node.getParent();
189 if (parent == null) {
190 // We have a parentless element with a relative xml:base attribute.
191 // See for example test XQTS fn-base-uri-10 and base-uri-27
192 URI base = new URI(node.getSystemId());
193 URI resolved = xmlBase.isEmpty() ? base : base.resolve(baseURI);
194 return resolved.toString();
195 }
196 String startSystemId = node.getSystemId();
197 if (startSystemId == null) {
198 return null;
199 }
200 String parentSystemId = parent.getSystemId();
201 boolean isTopWithinEntity = false;
202 if (node instanceof TinyElementImpl) {
203 isTopWithinEntity = ((TinyElementImpl)node).getTree().isTopWithinEntity(((TinyElementImpl) node).getNodeNumber());
204 } else {
205 isTopWithinEntity = !startSystemId.equals(parentSystemId);
206 }
207 URI base = new URI(isTopElementWithinEntity.test(node) ? startSystemId : parent.getBaseURI());
208 //URI base = new URI(parent.getBaseURI()); //bug 3530
209 baseURI = xmlBase.isEmpty() ? base : base.resolve(baseURI);
210 }
211 } catch (URISyntaxException e) {
212 // xml:base is an invalid URI. Just return it as is: the operation that needs the base URI
213 // will probably fail as a result. \
214 return xmlBase;
215 }
216 return baseURI.toString();
217 }
218 String startSystemId = node.getSystemId();
219 if (startSystemId == null) {
220 return null;
221 }
222 NodeInfo parent = node.getParent();
223 if (parent == null) {
224 return startSystemId;
225 }
226 String parentSystemId = parent.getSystemId();
227 if (startSystemId.equals(parentSystemId) || parentSystemId.isEmpty()) {
228 return parent.getBaseURI();
229 } else {
230 return startSystemId;
231 }
232 }
233
234 /**
235 * Get an absolute XPath expression that identifies a given node within its document
236 *
237 * @param node the node whose path is required. If null is supplied,
238 * an empty string is returned - this fact is used in making a recursive call
239 * for a parentless node.
240 * @return a path expression that can be used to retrieve the node
241 */
242
243 public static String getPath(NodeInfo node) {
244 return getPath(node, null);
245 }
246
247 /**
248 * Get an absolute XPath expression that identifies a given node within its document. The
249 * resulting path is intended for human readers, not for software evaluation. It uses lexical
250 * QNames (prefix:localname) for element and attribute names, with the original prefix as it
251 * appears in the source document. The sibling position of an element (a/b[2]) is included
252 * unless the node is a streamed node.
253 *
254 * @param node the node whose path is required. If null is supplied,
255 * an empty string is returned - this fact is used in making a recursive call
256 * for a parentless node.
257 * @param context the XPath dynamic evaluation context. May be null if no context is known
258 * @return a path expression that can be used to retrieve the node
259 */
260
261 public static String getPath(/*@Nullable*/ NodeInfo node, /*@Nullable*/ XPathContext context) {
262 if (node == null) {
263 return "";
264 }
265 String pre;
266 boolean streamed = node.getConfiguration().isStreamedNode(node);
267 NodeInfo parent = node.getParent();
268 // System.err.println("node = " + node + " parent = " + parent);
269
270 switch (node.getNodeKind()) {
271 case Type.DOCUMENT:
272 return "/";
273 case Type.ELEMENT:
274 if (parent == null) {
275 return node.getDisplayName();
276 } else {
277 pre = getPath(parent, context);
278 if (pre.equals("/")) {
279 return '/' + node.getDisplayName();
280 } else {
281 return pre + '/' + node.getDisplayName() + (streamed ? "" : "[" + getNumberSimple(node, context) + "]");
282 }
283 }
284 case Type.ATTRIBUTE:
285 return getPath(parent, context) + "/@" + node.getDisplayName();
286 case Type.TEXT:
287 pre = getPath(parent, context);
288 return (pre.equals("/") ? "" : pre) +
289 "/text()" + (streamed ? "" : "[" + getNumberSimple(node, context) + "]");
290
291 case Type.COMMENT:
292 pre = getPath(parent, context);
293 return (pre.equals("/") ? "" : pre) +
294 "/comment()" + (streamed ? "" : "[" + getNumberSimple(node, context) + "]");
295
296 case Type.PROCESSING_INSTRUCTION:
297 pre = getPath(parent, context);
298 return (pre.equals("/") ? "" : pre) +
299 "/processing-instruction()" + (streamed ? "" : "[" + getNumberSimple(node, context) + "]");
300
301 case Type.NAMESPACE:
302 String test = node.getLocalPart();
303 if (test.isEmpty()) {
304 // default namespace: need a node-test that selects unnamed nodes only
305 test = "*[not(local-name()]";
306 }
307 return getPath(parent, context) + "/namespace::" + test;
308 default:
309 return "";
310 }
311 }
312
313 /**
314 * Get the absolute path to a node
315 *
316 * @param node the node in question
317 * @return an object representing the path to the node
318 */
319
320 public static AbsolutePath getAbsolutePath(NodeInfo node) {
321 boolean streamed = node.getConfiguration().isStreamedNode(node);
322 List<AbsolutePath.PathElement> path = new LinkedList<>();
323 String sysId = node.getSystemId();
324 while (node != null && node.getNodeKind() != Type.DOCUMENT) {
325 path.add(0, new AbsolutePath.PathElement(node.getNodeKind(),
326 NameOfNode.makeName(node),
327 streamed ? -1 : getNumberSimple(node, null)));
328 node = node.getParent();
329 }
330 AbsolutePath a = new AbsolutePath(path);
331 a.setSystemId(sysId);
332 return a;
333 }
334
335 /**
336 * Ask whether two nodes have the same name
337 * @param n1 the first node
338 * @param n2 the second node
339 * @return true if they have the same namespace and local part
340 */
341
342 public static boolean haveSameName(NodeInfo n1, NodeInfo n2) {
343 if (n1.hasFingerprint() && n2.hasFingerprint()) {
344 return n1.getFingerprint() == n2.getFingerprint();
345 } else {
346 return n1.getLocalPart().equals(n2.getLocalPart()) &&
347 n1.getURI().equals(n2.getURI());
348 }
349 }
350
351 /**
352 * Get simple node number. This is defined as one plus the number of previous siblings of the
353 * same node type and name. It is not accessible directly in XSL.
354 *
355 * @param node The node whose number is required
356 * @param context Used for remembering previous result, for
357 * performance. May be null.
358 * @return the node number, as defined above
359 */
360
361 public static int getNumberSimple(/*@NotNull*/ NodeInfo node, /*@Nullable*/ XPathContext context) {
362
363 //checkNumberable(node);
364
365 NodeTest same;
366
367 if (node.getLocalPart().isEmpty()) {
368 same = NodeKindTest.makeNodeKindTest(node.getNodeKind());
369 } else {
370 same = new SameNameTest(node);
371 }
372
373 Controller controller = context == null ? null : context.getController();
374 AxisIterator preceding = node.iterateAxis(AxisInfo.PRECEDING_SIBLING, same);
375
376 int i = 1;
377 while (true) {
378 NodeInfo prev = preceding.next();
379 if (prev == null) {
380 break;
381 }
382
383 if (controller != null) {
384 int memo = controller.getRememberedNumber(prev);
385 if (memo > 0) {
386 memo += i;
387 controller.setRememberedNumber(node, memo);
388 return memo;
389 }
390 }
391
392 i++;
393 }
394
395 if (controller != null) {
396 controller.setRememberedNumber(node, i);
397 }
398 return i;
399 }
400
401 /**
402 * Get node number (level="single"). If the current node matches the supplied pattern, the returned
403 * number is one plus the number of previous siblings that match the pattern. Otherwise,
404 * return the element number of the nearest ancestor that matches the supplied pattern.
405 *
406 * @param node the current node, the one whose node number is required
407 * @param count Pattern that identifies which nodes should be
408 * counted. Default (null) is the element name if the current node is
409 * an element, or "node()" otherwise.
410 * @param from Pattern that specifies where counting starts from.
411 * Default (null) is the root node. (This parameter does not seem
412 * useful but is included for the sake of XSLT conformance.)
413 * @param context the dynamic context of the transformation, used if
414 * the patterns reference context values (e.g. variables)
415 * @return the node number established as follows: go to the nearest
416 * ancestor-or-self that matches the 'count' pattern and that is a
417 * descendant of the nearest ancestor that matches the 'from' pattern.
418 * Return one plus the nunber of preceding siblings of that ancestor
419 * that match the 'count' pattern. If there is no such ancestor,
420 * return 0.
421 * @throws XPathException when any error occurs in processing
422 */
423
424 public static int getNumberSingle(/*@NotNull*/ NodeInfo node, /*@Nullable*/ Pattern count,
425 /*@Nullable*/ Pattern from, XPathContext context) throws XPathException {
426
427 if (count == null && from == null) {
428 return getNumberSimple(node, context);
429 }
430
431 boolean knownToMatch = false;
432 if (count == null) {
433 if (node.getLocalPart().isEmpty()) { // unnamed node
434 count = new NodeTestPattern(NodeKindTest.makeNodeKindTest(node.getNodeKind()));
435 } else {
436 count = new NodeTestPattern(new SameNameTest(node));
437 }
438 knownToMatch = true;
439 }
440
441 NodeInfo target = node;
442 // code changed in 9.5 to fix issue described in spec bug 9840
443 if (!knownToMatch) {
444 while (true) {
445 if (count.matches(target, context)) {
446 if (from == null) {
447 break;
448 } else {
449 // see whether there is an ancestor node that matches the from pattern
450 NodeInfo anc = target;
451 while (!from.matches(anc, context)) {
452 anc = anc.getParent();
453 if (anc == null) {
454 // there's no ancestor that matches the "from" pattern
455 return 0;
456 }
457 }
458 // we've found the node to be counted
459 break;
460 }
461 } else if (from != null && from.matches(target, context)) {
462 // if we find something that matches "from" before we find something that matches "count", exit
463 return 0;
464 } else {
465 target = target.getParent();
466 if (target == null) {
467 // found the root before finding a match on either "count" or "from"
468 return 0;
469 }
470 }
471 }
472 }
473
474 // we've found the ancestor to count from
475
476 SequenceIterator preceding =
477 target.iterateAxis(AxisInfo.PRECEDING_SIBLING, getNodeTestForPattern(count));
478 // pass the filter condition down to the axis enumeration where possible
479 boolean alreadyChecked = count instanceof NodeTestPattern;
480 int i = 1;
481 while (true) {
482 NodeInfo p = (NodeInfo) preceding.next();
483 if (p == null) {
484 return i;
485 }
486 if (alreadyChecked || count.matches(p, context)) {
487 i++;
488 }
489 }
490 }
491
492 /**
493 * Get node number (level="any").
494 * Return one plus the number of previous nodes in the
495 * document that match the supplied pattern
496 *
497 * @param inst Identifies the xsl:number expression; this is relevant
498 * when the function is memoised to support repeated use of the same
499 * instruction to number multiple nodes
500 * @param node The node being numbered
501 * @param count Pattern that identifies which nodes should be
502 * counted. Default (null) is the element name if the current node is
503 * an element, or "node()" otherwise.
504 * @param from Pattern that specifies where counting starts from.
505 * Default (null) is the root node. Only nodes at or after the first (most
506 * recent) node that matches the 'from' pattern are counted.
507 * @param context The dynamic context for the transformation
508 * @param hasVariablesInPatterns if the count or from patterns
509 * contain variables, then it's not safe to get the answer by adding
510 * one to the number of the most recent node that matches
511 * @return one plus the number of nodes that precede the current node,
512 * that match the count pattern, and that follow the first node that
513 * matches the from pattern if specified.
514 * @throws net.sf.saxon.trans.XPathException
515 * if any dynamic error occurs
516 */
517
518 public static int getNumberAny(/*@NotNull*/ Expression inst, /*@NotNull*/ NodeInfo node, /*@Nullable*/ Pattern count,
519 /*@Nullable*/ Pattern from, /*@NotNull*/ XPathContext context, boolean hasVariablesInPatterns) throws XPathException {
520
521 NodeInfo memoNode = null;
522 int memoNumber = 0;
523 Controller controller = context.getController();
524 assert controller != null;
525 boolean memoise = !hasVariablesInPatterns && from == null;
526 if (memoise) {
527 Object[] memo = (Object[]) controller.getUserData(inst.getLocation(), "xsl:number");
528 if (memo != null) {
529 memoNode = (NodeInfo) memo[0];
530 memoNumber = (Integer) memo[1];
531 }
532 }
533
534 int num = 0;
535 if (count == null) {
536 if (node.getLocalPart().isEmpty()) { // unnamed node
537 count = new NodeTestPattern(NodeKindTest.makeNodeKindTest(node.getNodeKind()));
538 } else {
539 count = new NodeTestPattern(new SameNameTest(node));
540 }
541 num = 1;
542 } else if (count.matches(node, context)) {
543 num = 1;
544 }
545
546 // We use a special axis invented for the purpose: the union of the preceding and
547 // ancestor axes, but in reverse document order
548
549 // Pass part of the filtering down to the axis iterator if possible
550 NodeTest filter;
551 if (from == null) {
552 filter = getNodeTestForPattern(count);
553 } else if (from.getUType() == UType.ELEMENT && count.getUType() == UType.ELEMENT) {
554 filter = NodeKindTest.ELEMENT;
555 } else {
556 filter = AnyNodeTest.getInstance();
557 }
558
559 if (from != null && from.matches(node, context)) {
560 return num;
561 }
562
563 SequenceIterator preceding =
564 node.iterateAxis(AxisInfo.PRECEDING_OR_ANCESTOR, filter);
565
566 while (true) {
567 NodeInfo prev = (NodeInfo) preceding.next();
568 if (prev == null) {
569 break;
570 }
571
572 if (count.matches(prev, context)) {
573 if (num == 1 && prev.equals(memoNode)) {
574 num = memoNumber + 1;
575 break;
576 }
577 num++;
578 }
579
580 if (from != null && from.matches(prev, context)) {
581 break;
582 }
583 }
584
585 if (memoise) {
586 Object[] memo = new Object[2];
587 memo[0] = node;
588 memo[1] = num;
589 controller.setUserData(inst.getLocation(), "xsl:number", memo);
590 }
591 return num;
592 }
593
594 /**
595 * Get node number (level="multiple").
596 * Return a vector giving the hierarchic position of this node. See the XSLT spec for details.
597 *
598 * @param node The node to be numbered
599 * @param count Pattern that identifies which nodes (ancestors and
600 * their previous siblings) should be counted. Default (null) is the
601 * element name if the current node is an element, or "node()"
602 * otherwise.
603 * @param from Pattern that specifies where counting starts from.
604 * Default (null) is the root node. Only nodes below the first (most
605 * recent) node that matches the 'from' pattern are counted.
606 * @param context The dynamic context for the transformation
607 * @return a vector containing for each ancestor-or-self that matches the
608 * count pattern and that is below the nearest node that matches the
609 * from pattern, an Integer which is one greater than the number of
610 * previous siblings that match the count pattern.
611 * @throws XPathException if an error occurs
612 */
613
614 /*@NotNull*/
615 public static List<Long> getNumberMulti(/*@NotNull*/ NodeInfo node, /*@Nullable*/ Pattern count,
616 /*@Nullable*/ Pattern from, XPathContext context) throws XPathException {
617
618 //checkNumberable(node);
619
620 ArrayList<Long> v = new ArrayList<>(5);
621
622 if (count == null) {
623 if (node.getLocalPart().isEmpty()) { // unnamed node
624 count = new NodeTestPattern(NodeKindTest.makeNodeKindTest(node.getNodeKind()));
625 } else {
626 count = new NodeTestPattern(new SameNameTest(node));
627 }
628 }
629
630 NodeInfo curr = node;
631
632 while (true) {
633 if (count.matches(curr, context)) {
634 int num = getNumberSingle(curr, count, null, context);
635 v.add(0, (long) num);
636 }
637 if (from != null && from.matches(curr, context)) {
638 break;
639 }
640 curr = curr.getParent();
641 if (curr == null) {
642 break;
643 }
644 }
645
646 return v;
647 }
648
649 /**
650 * Get a NodeTest to use as a filter for nodes, given a pattern.
651 */
652
653 private static NodeTest getNodeTestForPattern(Pattern pattern) {
654 ItemType type = pattern.getItemType();
655 if (type instanceof NodeTest) {
656 return (NodeTest) type;
657 } else if (pattern.getUType().overlaps(UType.ANY_NODE)) {
658 return AnyNodeTest.getInstance();
659 } else {
660 return ErrorType.getInstance();
661 }
662 }
663
664 /**
665 * Generic (model-independent) implementation of deep copy algorithm for nodes.
666 * This is available for use by any node implementations that choose to use it.
667 *
668 * @param node The node to be copied
669 * @param out The receiver to which events will be sent
670 * @param copyOptions Options for copying namespaces, type annotations, etc,
671 * as defined in {@link net.sf.saxon.om.CopyOptions}
672 * @param locationId The location of the instruction invoking the copy
673 * @throws XPathException on any failure reported by the Receiver
674 */
675
676 public static void copy(/*@NotNull*/ NodeInfo node,
677 /*@NotNull*/ Receiver out,
678 int copyOptions,
679 Location locationId) throws XPathException {
680
681 switch (node.getNodeKind()) {
682 case Type.DOCUMENT: {
683 out.startDocument(CopyOptions.getStartDocumentProperties(copyOptions));
684 AxisIterator children0 = node.iterateAxis(AxisInfo.CHILD, AnyNodeTest.getInstance());
685 while (true) {
686 NodeInfo child = children0.next();
687 if (child == null) {
688 break;
689 }
690 child.copy(out, copyOptions, locationId);
691 }
692 out.endDocument();
693 break;
694 }
695 case Type.ELEMENT: {
696 SchemaType annotation = (copyOptions & CopyOptions.TYPE_ANNOTATIONS) != 0 ?
697 node.getSchemaType() :
698 Untyped.getInstance();
699 out.startElement(NameOfNode.makeName(node), annotation, locationId, 0);
700
701 // output the namespaces
702
703 if ((copyOptions & CopyOptions.LOCAL_NAMESPACES) != 0) {
704 NamespaceBinding[] localNamespaces = node.getDeclaredNamespaces(null);
705 for (NamespaceBinding ns : localNamespaces) {
706 if (ns == null) {
707 break;
708 }
709 out.namespace(ns, 0);
710 }
711 } else if ((copyOptions & CopyOptions.ALL_NAMESPACES) != 0) {
712 NamespaceIterator.sendNamespaces(node, out);
713 }
714
715 // output the attributes
716
717 AxisIterator attributes = node.iterateAxis(AxisInfo.ATTRIBUTE, AnyNodeTest.getInstance());
718 while (true) {
719 NodeInfo att = attributes.next();
720 if (att == null) {
721 break;
722 }
723 att.copy(out, copyOptions, locationId);
724 }
725
726 // notify the start of content
727
728 out.startContent();
729
730 // output the children
731
732 AxisIterator children = node.iterateAxis(AxisInfo.CHILD, AnyNodeTest.getInstance());
733 int options = copyOptions;
734 if ((options & CopyOptions.ALL_NAMESPACES) != 0) {
735 // Avoid copying namespaces of ancestors unnecessarily
736 options = options & ~CopyOptions.ALL_NAMESPACES | CopyOptions.LOCAL_NAMESPACES;
737 }
738 while (true) {
739 NodeInfo child = children.next();
740 if (child == null) {
741 break;
742 }
743 child.copy(out, options, locationId);
744 }
745
746 // finally the end tag
747
748 out.endElement();
749 return;
750 }
751 case Type.ATTRIBUTE: {
752 SimpleType annotation = (copyOptions & CopyOptions.TYPE_ANNOTATIONS) != 0 ?
753 (SimpleType) node.getSchemaType() :
754 BuiltInAtomicType.UNTYPED_ATOMIC;
755 out.attribute(NameOfNode.makeName(node), annotation, node.getStringValueCS(), locationId, 0);
756 return;
757 }
758 case Type.TEXT: {
759 CharSequence value = node.getStringValueCS();
760 if (value.length() != 0) {
761 // zero-length text nodes can arise from external model wrappers
762 out.characters(value, locationId, 0);
763 }
764 return;
765 }
766 case Type.COMMENT: {
767 out.comment(node.getStringValueCS(), locationId, 0);
768 return;
769 }
770 case Type.PROCESSING_INSTRUCTION: {
771 out.processingInstruction(node.getLocalPart(), node.getStringValueCS(), locationId, 0);
772 return;
773 }
774 case Type.NAMESPACE: {
775 out.namespace(new NamespaceBinding(node.getLocalPart(), node.getStringValue()), 0);
776 return;
777 }
778 default:
779
780 }
781 }
782
783 /**
784 * Generic (model-independent) method to determine the relative position of two
785 * node in document order. The nodes must be in the same tree.
786 *
787 * @param first The first node
788 * @param second The second node, whose position is to be compared with the first node
789 * @return -1 if this node precedes the other node, +1 if it follows the other
790 * node, or 0 if they are the same node. (In this case, isSameNode() will always
791 * return true, and the two nodes will produce the same result for generateId())
792 */
793
794 public static int compareOrder(/*@NotNull*/ SiblingCountingNode first, /*@NotNull*/ SiblingCountingNode second) {
795
796 // are they the same node?
797 if (first.equals(second)) {
798 return 0;
799 }
800
801 NodeInfo firstParent = first.getParent();
802 if (firstParent == null) {
803 // first node is the root
804 return -1;
805 }
806
807 NodeInfo secondParent = second.getParent();
808 if (secondParent == null) {
809 // second node is the root
810 return +1;
811 }
812
813 // do they have the same parent (common case)?
814 if (firstParent.equals(secondParent)) {
815 int cat1 = nodeCategories[first.getNodeKind()];
816 int cat2 = nodeCategories[second.getNodeKind()];
817 if (cat1 == cat2) {
818 return first.getSiblingPosition() - second.getSiblingPosition();
819 } else {
820 return cat1 - cat2;
821 }
822 }
823
824 // find the depths of both nodes in the tree
825 int depth1 = 0;
826 int depth2 = 0;
827 NodeInfo p1 = first;
828 NodeInfo p2 = second;
829 while (p1 != null) {
830 depth1++;
831 p1 = p1.getParent();
832 }
833 while (p2 != null) {
834 depth2++;
835 p2 = p2.getParent();
836 }
837 // move up one branch of the tree so we have two nodes on the same level
838
839 p1 = first;
840 while (depth1 > depth2) {
841 p1 = p1.getParent();
842 assert p1 != null;
843 if (p1.equals(second)) {
844 return +1;
845 }
846 depth1--;
847 }
848
849 p2 = second;
850 while (depth2 > depth1) {
851 p2 = p2.getParent();
852 assert p2 != null;
853 if (p2.equals(first)) {
854 return -1;
855 }
856 depth2--;
857 }
858
859 // now move up both branches in sync until we find a common parent
860 while (true) {
861 NodeInfo par1 = p1.getParent();
862 NodeInfo par2 = p2.getParent();
863 if (par1 == null || par2 == null) {
864 throw new NullPointerException("Node order comparison - internal error");
865 }
866 if (par1.equals(par2)) {
867 if (p1.getNodeKind() == Type.ATTRIBUTE && p2.getNodeKind() != Type.ATTRIBUTE) {
868 return -1; // attributes first
869 }
870 if (p1.getNodeKind() != Type.ATTRIBUTE && p2.getNodeKind() == Type.ATTRIBUTE) {
871 return +1; // attributes first
872 }
873 return ((SiblingCountingNode) p1).getSiblingPosition() -
874 ((SiblingCountingNode) p2).getSiblingPosition();
875 }
876 p1 = par1;
877 p2 = par2;
878 }
879 }
880
881 /**
882 * Generic (model-independent) method to determine the relative position of two
883 * node in document order. The nodes must be in the same tree.
884 *
885 * @param first The first node
886 * @param second The second node, whose position is to be compared with the first node
887 * @return {@link net.sf.saxon.om.AxisInfo#PRECEDING} if this node is on the preceding axis of the other node;
888 * {@link net.sf.saxon.om.AxisInfo#FOLLOWING} if it is on the following axis; {@link net.sf.saxon.om.AxisInfo#ANCESTOR} if the first node is an
889 * ancestor of the second; {@link net.sf.saxon.om.AxisInfo#DESCENDANT} if the first is a descendant of the second;
890 * {@link net.sf.saxon.om.AxisInfo#SELF} if they are the same node.
891 * @throws UnsupportedOperationException if either node is an attribute or namespace
892 * @since 9.5
893 */
894
895 public static int comparePosition(/*@NotNull*/ NodeInfo first, /*@NotNull*/ NodeInfo second) {
896
897 if (first.getNodeKind() == Type.ATTRIBUTE || first.getNodeKind() == Type.NAMESPACE ||
898 second.getNodeKind() == Type.ATTRIBUTE || second.getNodeKind() == Type.NAMESPACE) {
899 throw new UnsupportedOperationException();
900 }
901
902 // are they the same node?
903 if (first.equals(second)) {
904 return AxisInfo.SELF;
905 }
906
907 NodeInfo firstParent = first.getParent();
908 if (firstParent == null) {
909 // first node is the root
910 return AxisInfo.ANCESTOR;
911 }
912
913 NodeInfo secondParent = second.getParent();
914 if (secondParent == null) {
915 // second node is the root
916 return AxisInfo.DESCENDANT;
917 }
918
919 // do they have the same parent (common case)?
920 if (firstParent.equals(secondParent)) {
921 if (first.compareOrder(second) < 0) {
922 return AxisInfo.PRECEDING;
923 } else {
924 return AxisInfo.FOLLOWING;
925 }
926 }
927
928 // find the depths of both nodes in the tree
929 int depth1 = 0;
930 int depth2 = 0;
931 NodeInfo p1 = first;
932 NodeInfo p2 = second;
933 while (p1 != null) {
934 depth1++;
935 p1 = p1.getParent();
936 }
937 while (p2 != null) {
938 depth2++;
939 p2 = p2.getParent();
940 }
941 // Test if either node is an ancestor of the other
942
943 p1 = first;
944 while (depth1 > depth2) {
945 p1 = p1.getParent();
946 assert p1 != null;
947 if (p1.equals(second)) {
948 return AxisInfo.DESCENDANT;
949 }
950 depth1--;
951 }
952
953 p2 = second;
954 while (depth2 > depth1) {
955 p2 = p2.getParent();
956 assert p2 != null;
957 if (p2.equals(first)) {
958 return AxisInfo.ANCESTOR;
959 }
960 depth2--;
961 }
962
963 // now delegate to compareOrder()
964 if (first.compareOrder(second) < 0) {
965 return AxisInfo.PRECEDING;
966 } else {
967 return AxisInfo.FOLLOWING;
968 }
969 }
970
971
972 /**
973 * Classify node kinds into categories for sorting into document order:
974 * 0 = document, 1 = namespace, 2 = attribute, 3 = (element, text, comment, pi)
975 */
976
977 /*@NotNull*/ private static int[] nodeCategories = {
978 -1, //0 = not used
979 3, //1 = element
980 2, //2 = attribute
981 3, //3 = text
982 -1, -1, -1, //4,5,6 = not used
983 3, //7 = processing-instruction
984 3, //8 = comment
985 0, //9 = document
986 -1, -1, -1, //10,11,12 = not used
987 1 //13 = namespace
988 };
989
990 /**
991 * Get a character string that uniquely identifies this node and that collates nodes
992 * into document order
993 *
994 * @param node the node whose unique identifier is reuqired
995 * @param sb a buffer to which the unique identifier will be appended
996 * @param addDocNr true if a unique document number is to be included in the information
997 */
998
999 public static void appendSequentialKey(/*@NotNull*/ SiblingCountingNode node, /*@NotNull*/ FastStringBuffer sb, boolean addDocNr) {
1000 if (addDocNr) {
1001 sb.append('w');
1002 sb.append(Long.toString(node.getTreeInfo().getDocumentNumber()));
1003 }
1004 if (node.getNodeKind() != Type.DOCUMENT) {
1005 NodeInfo parent = node.getParent();
1006 if (parent != null) {
1007 appendSequentialKey((SiblingCountingNode) parent, sb, false);
1008 }
1009 if (node.getNodeKind() == Type.ATTRIBUTE) {
1010 sb.append('A');
1011 }
1012 }
1013 sb.append(alphaKey(node.getSiblingPosition()));
1014 }
1015
1016
1017 /**
1018 * Construct an alphabetic key from an positive integer; the key collates in the same sequence
1019 * as the integer
1020 *
1021 * @param value The positive integer key value (negative values are treated as zero).
1022 * @return the alphabetic key value
1023 */
1024
1025 /*@NotNull*/
1026 public static String alphaKey(int value) {
1027 if (value < 1) {
1028 return "a";
1029 }
1030 if (value < 10) {
1031 return "b" + value;
1032 }
1033 if (value < 100) {
1034 return "c" + value;
1035 }
1036 if (value < 1000) {
1037 return "d" + value;
1038 }
1039 if (value < 10000) {
1040 return "e" + value;
1041 }
1042 if (value < 100000) {
1043 return "f" + value;
1044 }
1045 if (value < 1000000) {
1046 return "g" + value;
1047 }
1048 if (value < 10000000) {
1049 return "h" + value;
1050 }
1051 if (value < 100000000) {
1052 return "i" + value;
1053 }
1054 if (value < 1000000000) {
1055 return "j" + value;
1056 }
1057 return "k" + value;
1058 }
1059
1060 /**
1061 * Test if one node is an ancestor-or-self of another
1062 *
1063 * @param a the putative ancestor-or-self node
1064 * @param d the putative descendant node
1065 * @return true if a is an ancestor-or-self of d
1066 */
1067
1068 public static boolean isAncestorOrSelf(/*@NotNull*/ NodeInfo a, /*@NotNull*/ NodeInfo d) {
1069 int k = a.getNodeKind();
1070 if (k != Type.ELEMENT && k != Type.DOCUMENT) {
1071 return a.equals(d);
1072 }
1073 // Fast path for the TinyTree implementation
1074 if (a instanceof TinyNodeImpl) {
1075 if (d instanceof TinyNodeImpl) {
1076 return ((TinyNodeImpl) a).isAncestorOrSelf((TinyNodeImpl) d);
1077 } else if (d instanceof TinyTextualElement.TinyTextualElementText) {
1078 return a.equals(d) || isAncestorOrSelf(a, d.getParent());
1079 } else if (d.getNodeKind() == Type.NAMESPACE) {
1080 // fall through
1081 } else if (d instanceof VirtualCopy) {
1082 // fall through
1083 } else {
1084 return false;
1085 }
1086 }
1087 // Generic implementation
1088 NodeInfo p = d;
1089 while (p != null) {
1090 if (a.equals(p)) {
1091 return true;
1092 }
1093 p = p.getParent();
1094 }
1095 return false;
1096 }
1097
1098
1099 ///////////////////////////////////////////////////////////////////////////////
1100 // Helper classes to support axis iteration
1101 ///////////////////////////////////////////////////////////////////////////////
1102
1103 /**
1104 * Create an iterator over a singleton node, if it exists and matches a nodetest;
1105 * otherwise return an empty iterator
1106 *
1107 * @param node the singleton node, or null if the node does not exist
1108 * @param nodeTest the test to be applied
1109 * @return an iterator over the node if it exists and matches the test.
1110 */
1111
1112 /*@NotNull*/
1113 public static AxisIterator filteredSingleton(/*@Nullable*/ NodeInfo node, /*@NotNull*/ NodeTest nodeTest) {
1114 if (node != null && nodeTest.matchesNode(node)) {
1115 return SingleNodeIterator.makeIterator(node);
1116 } else {
1117 return EmptyIterator.OfNodes.THE_INSTANCE;
1118 }
1119 }
1120
1121 /**
1122 * Get the sibling position of a node: specifically, count how many preceding siblings
1123 * of a node satisfy the nodetest.
1124 *
1125 * @param node the starting node, which is assumed to satisfy the node test
1126 * @param nodeTest the node test
1127 * @param max the maximum number of nodes to be counted
1128 * @return the number of preceding siblings that satisfy the node test, plus one, unless the
1129 * number exceeds max, in which case return some number greater than or equal to max.
1130 */
1131
1132 public static int getSiblingPosition(NodeInfo node, NodeTest nodeTest, int max) {
1133 if (node instanceof SiblingCountingNode && nodeTest instanceof AnyNodeTest) {
1134 return ((SiblingCountingNode)node).getSiblingPosition();
1135 }
1136 AxisIterator prev = node.iterateAxis(AxisInfo.PRECEDING_SIBLING, nodeTest);
1137 int count = 1;
1138 while (prev.next() != null) {
1139 if (++count > max) {
1140 return count;
1141 }
1142 }
1143 return count;
1144 }
1145
1146 /**
1147 * AxisFilter is an iterator that applies a NodeTest filter to
1148 * the nodes returned by an underlying AxisIterator.
1149 */
1150
1151 public static class AxisFilter implements AxisIterator {
1152 private AxisIterator base;
1153 private NodeTest nodeTest;
1154
1155 /**
1156 * Construct a AxisFilter
1157 *
1158 * @param base the underlying iterator that returns all the nodes on
1159 * a required axis. This must not be an atomizing iterator!
1160 * @param test a NodeTest that is applied to each node returned by the
1161 * underlying AxisIterator; only those nodes that pass the NodeTest are
1162 * returned by the AxisFilter
1163 */
1164
1165 public AxisFilter(AxisIterator base, NodeTest test) {
1166 this.base = base;
1167 nodeTest = test;
1168 }
1169
1170 /*@Nullable*/
1171 public NodeInfo next() {
1172 while (true) {
1173 NodeInfo next = base.next();
1174 if (next == null) {
1175 return null;
1176 }
1177 if (nodeTest.matchesNode(next)) {
1178 return next;
1179 }
1180 }
1181 }
1182
1183 }
1184
1185 /**
1186 * EmptyTextFilter is an iterator that applies removes any zero-length text
1187 * nodes returned by an underlying AxisIterator.
1188 */
1189
1190 public static class EmptyTextFilter implements AxisIterator {
1191 private AxisIterator base;
1192
1193 /**
1194 * Construct an EmptyTextFilter
1195 *
1196 * @param base the underlying iterator that returns all the nodes on
1197 * a required axis. This must not be an atomizing iterator
1198 */
1199
1200 public EmptyTextFilter(AxisIterator base) {
1201 this.base = base;
1202 }
1203
1204 /*@Nullable*/
1205 public NodeInfo next() {
1206 while (true) {
1207 NodeInfo next = base.next();
1208 if (next == null) {
1209 return null;
1210 }
1211 if (!(next.getNodeKind() == Type.TEXT && next.getStringValueCS().length() == 0)) {
1212 return next;
1213 }
1214 }
1215 }
1216
1217 }
1218
1219
1220 /**
1221 * General-purpose implementation of the ancestor and ancestor-or-self axes
1222 */
1223
1224 public static final class AncestorEnumeration implements AxisIterator {
1225
1226 private boolean includeSelf;
1227 private boolean atStart;
1228 private NodeInfo start;
1229 private NodeInfo current;
1230
1231 /**
1232 * Create an iterator over the ancestor or ancestor-or-self axis
1233 *
1234 * @param start the initial context node
1235 * @param includeSelf true if the "self" node is to be included
1236 */
1237
1238 public AncestorEnumeration(NodeInfo start, boolean includeSelf) {
1239 this.start = start;
1240 this.includeSelf = includeSelf;
1241 current = start;
1242 atStart = true;
1243 }
1244
1245 public final NodeInfo next() {
1246 if (atStart) {
1247 atStart = false;
1248 if (includeSelf) {
1249 return current;
1250 }
1251 }
1252 return current = current == null ? null : current.getParent();
1253 }
1254
1255 } // end of class AncestorEnumeration
1256
1257 /**
1258 * General-purpose implementation of the descendant and descendant-or-self axes,
1259 * in terms of the child axis.
1260 * But it also has the option to return the descendants in reverse document order;
1261 * this is used when evaluating the preceding axis. Note that the includeSelf option
1262 * should not be used when scanning in reverse order, as the self node will always be
1263 * returned first.
1264 */
1265
1266 public static final class DescendantEnumeration implements AxisIterator {
1267
1268 /*@Nullable*/ private AxisIterator children = null;
1269 /*@Nullable*/ private AxisIterator descendants = null;
1270 private NodeInfo start;
1271 private boolean includeSelf;
1272 private boolean forwards;
1273 private boolean atEnd = false;
1274
1275 /**
1276 * Create an iterator over the descendant or descendant-or-self axis
1277 *
1278 * @param start the initial context node
1279 * @param includeSelf true if the "self" node is to be included
1280 * @param forwards true for a forwards iteration, false for reverse order
1281 */
1282
1283 public DescendantEnumeration(NodeInfo start,
1284 boolean includeSelf, boolean forwards) {
1285 this.start = start;
1286 this.includeSelf = includeSelf;
1287 this.forwards = forwards;
1288 }
1289
1290 public final NodeInfo next() {
1291 if (descendants != null) {
1292 NodeInfo nextd = descendants.next();
1293 if (nextd != null) {
1294 return nextd;
1295 } else {
1296 descendants = null;
1297 }
1298 }
1299 if (children != null) {
1300 NodeInfo n = children.next();
1301 if (n != null) {
1302 if (n.hasChildNodes()) {
1303 if (forwards) {
1304 descendants = new DescendantEnumeration(n, false, true);
1305 return n;
1306 } else {
1307 descendants = new DescendantEnumeration(n, true, false);
1308 return next();
1309 }
1310 } else {
1311 return n;
1312 }
1313 } else {
1314 if (forwards || !includeSelf) {
1315 return null;
1316 } else {
1317 atEnd = true;
1318 children = null;
1319 return start;
1320 }
1321 }
1322 } else if (atEnd) {
1323 // we're just finishing a backwards scan
1324 return null;
1325 } else {
1326 // we're just starting...
1327 if (start.hasChildNodes()) {
1328 //children = new NodeWrapper.ChildEnumeration(start, true, forwards);
1329 children = start.iterateAxis(AxisInfo.CHILD);
1330 if (!forwards) {
1331 if (children instanceof ReversibleIterator) {
1332 children = (AxisIterator) ((ReversibleIterator) children).getReverseIterator();
1333 } else {
1334 LinkedList<NodeInfo> list = new LinkedList<>();
1335 AxisIterator forwards = start.iterateAxis(AxisInfo.CHILD);
1336 NodeInfo n;
1337 while ((n = forwards.next()) != null) {
1338 list.addFirst(n);
1339 }
1340 children = new ListIterator.OfNodes(list);
1341 }
1342 }
1343 } else {
1344 children = EmptyIterator.OfNodes.THE_INSTANCE;
1345 }
1346 if (forwards && includeSelf) {
1347 return start;
1348 } else {
1349 return next();
1350 }
1351 }
1352 }
1353
1354 public void advance() {
1355
1356 }
1357
1358 } // end of class DescendantEnumeration
1359
1360 /**
1361 * General purpose implementation of the following axis, in terms of the
1362 * ancestor, child, and following-sibling axes
1363 */
1364
1365 public static final class FollowingEnumeration implements AxisIterator {
1366 private NodeInfo start;
1367 /*@NotNull*/ private AxisIterator ancestorEnum;
1368 /*@Nullable*/ private AxisIterator siblingEnum = null;
1369 /*@Nullable*/ private AxisIterator descendEnum = null;
1370
1371 /**
1372 * Create an iterator over the "following" axis
1373 *
1374 * @param start the initial context node
1375 */
1376
1377 public FollowingEnumeration(/*@NotNull*/ NodeInfo start) {
1378 this.start = start;
1379 ancestorEnum = new AncestorEnumeration(start, false);
1380 switch (start.getNodeKind()) {
1381 case Type.ELEMENT:
1382 case Type.TEXT:
1383 case Type.COMMENT:
1384 case Type.PROCESSING_INSTRUCTION:
1385 //siblingEnum = new NodeWrapper.ChildEnumeration(start, false, true);
1386 // gets following siblings
1387 siblingEnum = start.iterateAxis(AxisInfo.FOLLOWING_SIBLING);
1388 break;
1389 case Type.ATTRIBUTE:
1390 case Type.NAMESPACE:
1391 //siblingEnum = new NodeWrapper.ChildEnumeration((NodeWrapper)start.getParent(), true, true);
1392 // gets children of the attribute's parent node
1393 NodeInfo parent = start.getParent();
1394 if (parent == null) {
1395 siblingEnum = EmptyIterator.OfNodes.THE_INSTANCE;
1396 } else {
1397 siblingEnum = parent.iterateAxis(AxisInfo.CHILD);
1398 }
1399 break;
1400 default:
1401 siblingEnum = EmptyIterator.OfNodes.THE_INSTANCE;
1402 }
1403 }
1404
1405 public final NodeInfo next() {
1406 if (descendEnum != null) {
1407 NodeInfo nextd = descendEnum.next();
1408 if (nextd != null) {
1409 return nextd;
1410 } else {
1411 descendEnum = null;
1412 }
1413 }
1414 if (siblingEnum != null) {
1415 NodeInfo nexts = siblingEnum.next();
1416 if (nexts != null) {
1417 if (nexts.hasChildNodes()) {
1418 descendEnum = new DescendantEnumeration(nexts, false, true);
1419 } else {
1420 descendEnum = null;
1421 }
1422 return nexts;
1423 } else {
1424 descendEnum = null;
1425 siblingEnum = null;
1426 }
1427 }
1428 NodeInfo nexta = ancestorEnum.next();
1429 if (nexta != null) {
1430 if (nexta.getNodeKind() == Type.DOCUMENT) {
1431 siblingEnum = EmptyIterator.OfNodes.THE_INSTANCE;
1432 } else {
1433 //siblingEnum = new NodeWrapper.ChildEnumeration(next, false, true);
1434 siblingEnum = nexta.iterateAxis(AxisInfo.FOLLOWING_SIBLING);
1435 }
1436 return next();
1437 } else {
1438 return null;
1439 }
1440 }
1441
1442 } // end of class FollowingEnumeration
1443
1444 /**
1445 * Helper method to iterate over the preceding axis, or Saxon's internal
1446 * preceding-or-ancestor axis, by making use of the ancestor, descendant, and
1447 * preceding-sibling axes.
1448 */
1449
1450 public static final class PrecedingEnumeration implements AxisIterator {
1451
1452 private NodeInfo start;
1453 /*@NotNull*/ private AxisIterator ancestorEnum;
1454 /*@Nullable*/ private AxisIterator siblingEnum = null;
1455 /*@Nullable*/ private AxisIterator descendEnum = null;
1456 private boolean includeAncestors;
1457
1458 /**
1459 * Create an iterator for the preceding or "preceding-or-ancestor" axis (the latter being
1460 * used internall to support xsl:number)
1461 *
1462 * @param start the initial context node
1463 * @param includeAncestors true if ancestors of the initial context node are to be included
1464 * in the result
1465 */
1466
1467 public PrecedingEnumeration(/*@NotNull*/ NodeInfo start, boolean includeAncestors) {
1468 this.start = start;
1469 this.includeAncestors = includeAncestors;
1470 ancestorEnum = new AncestorEnumeration(start, false);
1471 switch (start.getNodeKind()) {
1472 case Type.ELEMENT:
1473 case Type.TEXT:
1474 case Type.COMMENT:
1475 case Type.PROCESSING_INSTRUCTION:
1476 // get preceding-sibling enumeration
1477 siblingEnum = start.iterateAxis(AxisInfo.PRECEDING_SIBLING);
1478 break;
1479 default:
1480 siblingEnum = EmptyIterator.OfNodes.THE_INSTANCE;
1481 }
1482 }
1483
1484 public final NodeInfo next() {
1485 if (descendEnum != null) {
1486 NodeInfo nextd = descendEnum.next();
1487 if (nextd != null) {
1488 return nextd;
1489 } else {
1490 descendEnum = null;
1491 }
1492 }
1493 if (siblingEnum != null) {
1494 NodeInfo nexts = siblingEnum.next();
1495 if (nexts != null) {
1496 if (nexts.hasChildNodes()) {
1497 descendEnum = new DescendantEnumeration(nexts, true, false);
1498 return next();
1499 } else {
1500 descendEnum = null;
1501 return nexts;
1502 }
1503 } else {
1504 descendEnum = null;
1505 siblingEnum = null;
1506 }
1507 }
1508 NodeInfo nexta = ancestorEnum.next();
1509 if (nexta != null) {
1510 if (nexta.getNodeKind() == Type.DOCUMENT) {
1511 siblingEnum = EmptyIterator.OfNodes.THE_INSTANCE;
1512 } else {
1513 siblingEnum = nexta.iterateAxis(AxisInfo.PRECEDING_SIBLING);
1514 }
1515 if (!includeAncestors) {
1516 return next();
1517 } else {
1518 return nexta;
1519 }
1520 } else {
1521 return null;
1522 }
1523 }
1524
1525
1526 } // end of class PrecedingEnumeration
1527
1528
1529 }
1530