Debian Codegraph @

net/sf/saxon/tree/tiny/TinyTree.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.tiny;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.ReceiverOptions;
12 import net.sf.saxon.lib.Feature;
13 import net.sf.saxon.lib.FeatureKeys;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.linked.SystemIdMap;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.*;
19 import net.sf.saxon.value.*;
20 import net.sf.saxon.z.IntArraySet;
21 import net.sf.saxon.z.IntHashMap;
22 import net.sf.saxon.z.IntHashSet;
23 import net.sf.saxon.z.IntSet;
24
25 import java.util.*;
26
27
28 /**
29 * A data structure to hold the contents of a tree. As the name implies, this implementation
30 * of the data model is optimized for size, and for speed of creation: it minimizes the number
31 * of Java objects used.
32 * <p>
33 * <p>It can be used to represent a tree that is rooted at a document node, or one that is rooted
34 * at an element node.</p>
35 * <p>
36 * <p>From Saxon 9.7, as a consequence of bug 2220, it is used only to hold a single tree, whose
37 * root is always node number zero.</p>
38 */
39
40 public final class TinyTree extends GenericTreeInfo implements NodeVectorTree {
41
42 /*@NotNull*/
43 private static final String[] EMPTY_STRING_ARRAY = new String[0];
44
45 // the contents of the document
46
47 protected AppendableCharSequence charBuffer;
48 /*@Nullable*/
49 protected FastStringBuffer commentBuffer = null; // created when needed
50
51 protected int numberOfNodes = 0; // excluding attributes and namespaces
52
53 // The following arrays contain one entry for each node other than attribute
54 // and namespace nodes, arranged in document order.
55
56 // nodeKind indicates the kind of node, e.g. element, text, or comment
57 public byte[] nodeKind;
58
59 // depth is the depth of the node in the hierarchy, i.e. the number of ancestors
60 protected short[] depth;
61
62 // next is the node number of the next sibling
63 // - unless it points backwards, in which case it is the node number of the parent
64 protected int[] next;
65
66 // alpha holds a value that depends on the node kind. For text nodes, it is the offset
67 // into the text buffer. For comments and processing instructions, it is the offset into
68 // the comment buffer. For elements, it is the index of the first attribute node, or -1
69 // if this element has no attributes.
70 protected int[] alpha;
71
72 // beta holds a value that depends on the node kind. For text nodes, it is the length
73 // of the text. For comments and processing instructions, it is the length of the text.
74 // For elements, it is the index of the first namespace node, or -1
75 // if this element has no namespaces.
76 protected int[] beta;
77
78 // nameCode holds the name of the node, as an identifier resolved using the name pool
79 protected int[] nameCode;
80
81 // the prior array indexes preceding-siblings; it is constructed only when required
82 /*@Nullable*/
83 protected int[] prior = null;
84
85 // the typeCode array holds type codes for element nodes; it is constructed only
86 // if at least one element has a type other than untyped, or has an IDREF property.
87 // The array holds a reference to the schema type.
88 /*@Nullable*/
89 protected SchemaType[] typeArray = null;
90
91 // the typedValue array holds the typed values of element nodes if the typed value is anything
92 // other than string, untypedAtomic, or anyURI. This means it is only used for schema-validated
93 // documents. It is created lazily when the typed value of a node is first accessed.
94 /*@Nullable*/
95 protected AtomicSequence[] typedValueArray = null;
96
97 // idRefElements is a set holding the node numbers of element nodes having the IDREF property
98 protected IntSet idRefElements = null;
99
100 // idRefAttributes is a set holding the node numbers of attribute nodes having the IDREF property
101 protected IntSet idRefAttributes = null;
102
103 // nilledElements is a set holding the node numbers of elements having the NILLED property
104 protected IntSet nilledElements = null;
105
106 // defaultedAttribute is a set holding the attribute node numbers of attributes that resulted from expansion of schema defaults
107 protected IntSet defaultedAttributes = null;
108
109 // topWithinEntity is a set holding the node numbers of elements that do not have a parent within
110 // the same external entity
111 protected IntSet topWithinEntity = null;
112
113 // boolean switch to disable the typed value caching
114 private boolean allowTypedValueCache = true;
115
116 public static final int TYPECODE_IDREF = 1 << 29;
117
118 // the owner array gives fast access from a node to its parent; it is constructed
119 // only when required
120 // protected int[] parentIndex = null;
121
122 // the following arrays have one entry for each attribute.
123 protected int numberOfAttributes = 0;
124
125 // attParent is the index of the parent element node
126 protected int[] attParent;
127
128 // attCode is the nameCode representing the attribute name
129 protected int[] attCode;
130
131 // attValue is the string value of the attribute
132 protected CharSequence[] attValue;
133
134 // attTypedValue is the typed vlaue of the attribute, maintained only if the attribute type is
135 // something other than string, untypedAtomic, or anyURI. It is maintained lazily on first reference
136 // to the typed value
137 protected AtomicSequence[] attTypedValue;
138
139 // attTypeCode holds type annotations. The array is created only if any nodes have a type annotation
140
141 /*@Nullable*/
142 protected SimpleType[] attType;
143
144 // The following arrays have one entry for each namespace declaration
145 protected int numberOfNamespaces = 0;
146
147 // namespaceParent is the index of the element node owning the namespace declaration
148 protected int[] namespaceParent;
149
150 // namespaceCode is the namespace binding, holding the prefix and URI
151 protected NamespaceBinding[] namespaceBinding;
152
153 // an array holding the offsets of all the level-0 (root) nodes, so that the root of a given
154 // node can be found efficiently
155 //private int[] rootIndex = new int[5];
156 //protected int rootIndexUsed = 0;
157
158 /*@Nullable*/
159 private int[] lineNumbers = null;
160 /*@Nullable*/
161 private int[] columnNumbers = null;
162 /*@Nullable*/
163 private SystemIdMap systemIdMap = null;
164
165 // a boolean that is set to true if the document declares a namespace other than the XML namespace
166 protected boolean usesNamespaces = false;
167
168 protected PrefixPool prefixPool = new PrefixPool();
169
170 private TinyDocumentImpl root;
171 private HashMap<String, NodeInfo> idTable;
172 protected HashMap<String, String[]> entityTable;
173
174 private NodeInfo copiedFrom;
175
176 protected List<GraftedElement> externalNodes;
177
178 protected IntHashMap<String> knownBaseUris;
179
180 /**
181 * Temporary flag introduced in Saxon 9.8.0.5 to enable or disable fast-path code for copying
182 * element nodes from one TinyTree to another. This code is currently disabled by default until
183 * it has been more thoroughly tested.
184 */
185 public final static boolean useBulkCopy = true; // Until bug 4089 is resolved
186 public static boolean useGraft = false; // KILROY
187
188 /**
189 * Create a tree with a specified initial size
190 *
191 * @param config the Saxon configuration
192 * @param statistics the size parameters for the tree
193 */
194
195 //private static int counter = 0;
196 public TinyTree(/*@NotNull*/ Configuration config, Statistics statistics) {
197 super(config);
198 //if (counter++ % 1000 == 0) System.err.println("TinyTree instances: " + counter);
199
200 int nodes = (int) statistics.getAverageNodes() + 1;
201 int attributes = (int) statistics.getAverageAttributes() + 1;
202 int namespaces = (int) statistics.getAverageNamespaces() + 1;
203 int characters = (int) statistics.getAverageCharacters() + 1;
204
205 nodeKind = new byte[nodes];
206 depth = new short[nodes];
207 next = new int[nodes];
208 alpha = new int[nodes];
209 beta = new int[nodes];
210 nameCode = new int[nodes];
211
212 numberOfAttributes = 0;
213 attParent = new int[attributes];
214 attCode = new int[attributes];
215 attValue = new String[attributes];
216
217 numberOfNamespaces = 0;
218 namespaceParent = new int[namespaces];
219 namespaceBinding = new NamespaceBinding[namespaces];
220
221 //charBuffer = new LargeStringBuffer(characters, 64000);
222 charBuffer = characters > 65000 ? new LargeStringBuffer() : new FastStringBuffer(characters);
223
224 setConfiguration(config);
225 }
226
227 /**
228 * Set the Configuration that contains this document
229 *
230 * @param config the Saxon configuration
231 */
232
233 public void setConfiguration(/*@NotNull*/ Configuration config) {
234 super.setConfiguration(config);
235 allowTypedValueCache = config.isLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION) &&
236 config.getBooleanProperty(Feature.USE_TYPED_VALUE_CACHE);
237 addNamespace(0, NamespaceBinding.XML);
238 }
239
240 private void ensureNodeCapacity(short kind, int needed) {
241 if (nodeKind.length < numberOfNodes + needed) {
242 //System.err.println("Number of nodes = " + numberOfNodes);
243 int k = kind == Type.STOPPER ? numberOfNodes + 1 : Math.max(numberOfNodes * 2, numberOfNodes + needed);
244
245 nodeKind = Arrays.copyOf(nodeKind, k);
246 next = Arrays.copyOf(next, k);
247 depth = Arrays.copyOf(depth, k);
248 alpha = Arrays.copyOf(alpha, k);
249 beta = Arrays.copyOf(beta, k);
250 nameCode = Arrays.copyOf(nameCode, k);
251
252 if (typeArray != null) {
253 typeArray = Arrays.copyOf(typeArray, k);
254 }
255
256 if (typedValueArray != null) {
257 typedValueArray = Arrays.copyOf(typedValueArray, k);
258 }
259
260 if (lineNumbers != null) {
261 lineNumbers = Arrays.copyOf(lineNumbers, k);
262 columnNumbers = Arrays.copyOf(columnNumbers, k);
263 }
264 }
265 }
266
267 private void ensureAttributeCapacity(int needed) {
268 if (attParent.length < numberOfAttributes + needed) {
269 int k = Math.max(numberOfAttributes + needed, numberOfAttributes * 2);
270 if (k == 0) {
271 k = 10 + needed;
272 }
273
274 attParent = Arrays.copyOf(attParent, k);
275 attCode = Arrays.copyOf(attCode, k);
276 attValue = Arrays.copyOf(attValue, k);
277
278 if (attType != null) {
279 attType = Arrays.copyOf(attType, k);
280 }
281
282 if (attTypedValue != null) {
283 attTypedValue = Arrays.copyOf(attTypedValue, k);
284 }
285 }
286 }
287
288 private void ensureNamespaceCapacity(int needed) {
289 if (namespaceParent.length < numberOfNamespaces + needed) {
290 int k = Math.max(numberOfNamespaces * 2, numberOfNamespaces + needed);
291 if (k == 0) {
292 k = 10;
293 }
294 namespaceParent = Arrays.copyOf(namespaceParent, k);
295 namespaceBinding = Arrays.copyOf(namespaceBinding, k);
296 }
297 }
298
299 /**
300 * Get the prefix pool
301 *
302 * @return the prefix pool
303 */
304
305 public PrefixPool getPrefixPool() {
306 return prefixPool;
307 }
308
309 /**
310 * Declare that this tree was produced as a copy of another tree, and identify
311 * the root node of that tree
312 *
313 * @param copiedFrom the root of the tree from which this one was copied
314 */
315
316 public void setCopiedFrom(NodeInfo copiedFrom) {
317 this.copiedFrom = copiedFrom;
318 }
319
320 /**
321 * Declare that this tree was produced as a copy of another tree, and identify
322 * the root node of that tree
323 *
324 * @return the root of the tree from which this one was copied, or null if this
325 * does not apply
326 */
327
328 public NodeInfo getCopiedFrom() {
329 return this.copiedFrom;
330 }
331
332 /**
333 * Add a document node to the tree. The data structure since 9.7 can only hold one tree, therefore at
334 * most one document node, which must be node zero.
335 *
336 * @param doc the document node to be added
337 * @return the number of the node that was added
338 */
339
340 int addDocumentNode(TinyDocumentImpl doc) {
341 setRootNode(doc);
342 return addNode(Type.DOCUMENT, 0, 0, 0, -1);
343 }
344
345 /**
346 * Add a node to the tree
347 *
348 * @param kind The kind of the node. This must be a document, element, text, comment,
349 * or processing-instruction node (not an attribute or namespace)
350 * @param depth The depth in the tree
351 * @param alpha Pointer to attributes or text
352 * @param beta Pointer to namespaces or text
353 * @param nameCode The name of the node
354 * @return the node number of the node that was added
355 */
356 int addNode(short kind, int depth, int alpha, int beta, int nameCode) {
357
358 ensureNodeCapacity(kind, 1);
359 nodeKind[numberOfNodes] = (byte) kind;
360 this.depth[numberOfNodes] = (short) depth;
361 this.alpha[numberOfNodes] = alpha;
362 this.beta[numberOfNodes] = beta;
363 this.nameCode[numberOfNodes] = nameCode;
364 next[numberOfNodes] = -1; // safety precaution
365
366 if (typeArray != null) {
367 typeArray[numberOfNodes] = Untyped.getInstance();
368 }
369
370 if (numberOfNodes == 0) {
371 setDocumentNumber(getConfiguration().getDocumentNumberAllocator().allocateDocumentNumber());
372 }
373
374 // if (depth == 0 && kind != Type.STOPPER) {
375 // if (rootIndexUsed == rootIndex.length) {
376 // int[] r2 = new int[rootIndexUsed * 2];
377 // System.arraycopy(rootIndex, 0, r2, 0, rootIndexUsed);
378 // rootIndex = r2;
379 // }
380 // rootIndex[rootIndexUsed++] = numberOfNodes;
381 // }
382 return numberOfNodes++;
383 }
384
385 /**
386 * Append character data to the current text node
387 *
388 * @param chars the character data to be appended
389 */
390
391 void appendChars(CharSequence chars) {
392 if (charBuffer instanceof FastStringBuffer && charBuffer.length() > 65000) {
393 LargeStringBuffer lsb = new LargeStringBuffer();
394 lsb.append(charBuffer);
395 charBuffer = lsb;
396 }
397 charBuffer.append(chars);
398 }
399
400 /**
401 * Create a new text node that is a copy of an existing text node
402 *
403 * @param depth the depth of the new node
404 * @param existingNodeNr the node to be copied
405 * @return the node number of the new node
406 */
407
408 public int addTextNodeCopy(int depth, int existingNodeNr) {
409 return addNode(Type.TEXT, depth, alpha[existingNodeNr], beta[existingNodeNr], -1);
410 }
411
412 /**
413 * Condense the tree: release unused memory. This is done after the full tree has been built.
414 * The method makes a pragmatic judgement as to whether it is worth reclaiming space; this is
415 * only done when the constructed tree is very small compared with the space allocated.
416 *
417 * @param statistics represents the family of trees to which this tree belongs; statistics for the
418 * size of the tree are recorded in this Statistics object
419 */
420
421 void condense(Statistics statistics) {
422 //System.err.println("TinyTree.condense() " + this + " roots " + rootIndexUsed + " nodes " + numberOfNodes + " capacity " + nodeKind.length);
423
424 if (numberOfNodes * 3 < nodeKind.length ||
425 (nodeKind.length - numberOfNodes > 20000)) {
426
427 //System.err.println("-- copying node arrays");
428
429 nodeKind = Arrays.copyOf(nodeKind, numberOfNodes);
430 next = Arrays.copyOf(next, numberOfNodes);
431 depth = Arrays.copyOf(depth, numberOfNodes);
432 alpha = Arrays.copyOf(alpha, numberOfNodes);
433 beta = Arrays.copyOf(beta, numberOfNodes);
434 nameCode = Arrays.copyOf(nameCode, numberOfNodes);
435
436 if (typeArray != null) {
437 typeArray = Arrays.copyOf(typeArray, numberOfNodes);
438 }
439 if (lineNumbers != null) {
440 lineNumbers = Arrays.copyOf(lineNumbers, numberOfNodes);
441 columnNumbers = Arrays.copyOf(columnNumbers, numberOfNodes);
442 }
443
444 }
445
446 if ((numberOfAttributes * 3 < attParent.length) ||
447 (attParent.length - numberOfAttributes > 1000)) {
448 int k = numberOfAttributes;
449
450 //System.err.println("-- copying attribute arrays");
451
452 if (k == 0) {
453 attParent = IntArraySet.EMPTY_INT_ARRAY;
454 attCode = IntArraySet.EMPTY_INT_ARRAY;
455 attValue = EMPTY_STRING_ARRAY;
456 attType = null;
457 } else {
458 attParent = Arrays.copyOf(attParent, numberOfAttributes);
459 attCode = Arrays.copyOf(attCode, numberOfAttributes);
460 attValue = Arrays.copyOf(attValue, numberOfAttributes);
461 }
462
463 if (attType != null) {
464 attType = Arrays.copyOf(attType, numberOfAttributes);
465 }
466 }
467
468 if (numberOfNamespaces * 3 < namespaceParent.length) {
469 namespaceParent = Arrays.copyOf(namespaceParent, numberOfNamespaces);
470 namespaceBinding = Arrays.copyOf(namespaceBinding, numberOfNamespaces);
471 }
472
473 prefixPool.condense();
474
475 statistics.updateStatistics(numberOfNodes, numberOfAttributes, numberOfNamespaces, charBuffer.length());
476 // System.err.println("STATS: " + averageNodes + ", " + averageAttributes + ", "
477 // + averageNamespaces + ", " + averageCharacters);
478
479 // if (charBufferLength * 3 < charBuffer.length ||
480 // charBuffer.length - charBufferLength > 10000) {
481 // char[] c2 = new char[charBufferLength];
482 // System.arraycopy(charBuffer, 0, c2, 0, charBufferLength);
483 // charBuffer = c2;
484 // }
485 }
486
487 /**
488 * Set the type annotation of an element node
489 *
490 * @param nodeNr the node whose type annotation is to be set
491 * @param type the type annotation
492 */
493
494 void setElementAnnotation(int nodeNr, SchemaType type) {
495 if (!type.equals(Untyped.getInstance())) {
496 if (typeArray == null) {
497 typeArray = new SchemaType[nodeKind.length];
498 Arrays.fill(typeArray, 0, nodeKind.length, Untyped.getInstance());
499 }
500 assert typeArray != null;
501 typeArray[nodeNr] = type;
502 }
503 }
504
505 /**
506 * Get the type annotation of a node. Applies only to document, element, text,
507 * processing instruction, and comment nodes.
508 *
509 * @param nodeNr the node whose type annotation is required
510 * @return the fingerprint of the type annotation for elements and attributes, otherwise undefined.
511 */
512
513 public int getTypeAnnotation(int nodeNr) {
514 if (typeArray == null) {
515 return StandardNames.XS_UNTYPED;
516 }
517 return typeArray[nodeNr].getFingerprint();
518 }
519
520 /**
521 * Get the type annotation of a node. Applies only to document, element, text,
522 * processing instruction, and comment nodes.
523 *
524 * @param nodeNr the node whose type annotation is required
525 * @return the fingerprint of the type annotation for elements and attributes, otherwise undefined.
526 */
527
528 public SchemaType getSchemaType(int nodeNr) {
529 if (typeArray == null) {
530 return Untyped.getInstance();
531 }
532 return typeArray[nodeNr];
533 }
534
535 /**
536 * Get the typed value of an element node.
537 *
538 * @param element the element node
539 * @return the typed value of the node (a Value whose items are AtomicValue instances)
540 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs, for example if the node is
541 * an element annotated with a type that has element-only content
542 */
543
544 /*@Nullable*/
545 public AtomicSequence getTypedValueOfElement(/*@NotNull*/ TinyElementImpl element) throws XPathException {
546 int nodeNr = element.nodeNr;
547 if (typedValueArray == null || typedValueArray[nodeNr] == null) {
548 SchemaType stype = getSchemaType(nodeNr);
549 int annotation = stype.getFingerprint();
550 if (annotation == StandardNames.XS_UNTYPED || annotation == StandardNames.XS_UNTYPED_ATOMIC ||
551 annotation == StandardNames.XS_ANY_TYPE) {
552 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
553 return new UntypedAtomicValue(stringValue);
554 } else if (annotation == StandardNames.XS_STRING) {
555 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
556 return new StringValue(stringValue);
557 } else if (annotation == StandardNames.XS_ANY_URI) {
558 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
559 return new AnyURIValue(stringValue);
560 } else {
561 AtomicSequence value = stype.atomize(element);
562 if (allowTypedValueCache) {
563 if (typedValueArray == null) {
564 //noinspection unchecked
565 typedValueArray = new AtomicSequence[nodeKind.length];
566 }
567 typedValueArray[nodeNr] = value;
568 }
569 return value;
570 }
571 } else {
572 return typedValueArray[nodeNr];
573 }
574 }
575
576 /**
577 * Get the type value of an element node, given only the node number
578 *
579 * @param nodeNr the node number of the element node
580 * @return the typed value of the node
581 * @throws net.sf.saxon.trans.XPathException if the eement has no typed value
582 */
583
584 /*@Nullable*/
585 public AtomicSequence getTypedValueOfElement(int nodeNr) throws XPathException {
586 if (typedValueArray == null || typedValueArray[nodeNr] == null) {
587 SchemaType stype = getSchemaType(nodeNr);
588 int annotation = stype.getFingerprint();
589 if (annotation == StandardNames.XS_UNTYPED_ATOMIC || annotation == StandardNames.XS_UNTYPED) {
590 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
591 return new UntypedAtomicValue(stringValue);
592 } else if (annotation == StandardNames.XS_STRING) {
593 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
594 return new StringValue(stringValue);
595 } else if (annotation == StandardNames.XS_ANY_URI) {
596 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
597 return new AnyURIValue(stringValue);
598 } else if (annotation == StandardNames.XS_ID) {
599 CharSequence stringValue = TinyParentNodeImpl.getStringValueCS(this, nodeNr);
600 return new StringValue(stringValue, BuiltInAtomicType.ID);
601 } else {
602 TinyNodeImpl element = getNode(nodeNr);
603 AtomicSequence value = stype.atomize(element);
604 if (allowTypedValueCache) {
605 if (typedValueArray == null) {
606 //noinspection unchecked
607 typedValueArray = new AtomicSequence[nodeKind.length];
608 }
609 typedValueArray[nodeNr] = value;
610 }
611 return value;
612 }
613 } else {
614 return typedValueArray[nodeNr];
615 }
616 }
617
618 /**
619 * Get the typed value of an attribute node. This method avoids
620 * materializing the attribute node if possible, but uses the attribute node
621 * supplied if it already exists.
622 *
623 * @param att the attribute node if available. If null is supplied, the attribute node
624 * will be materialized only if it is needed.
625 * @param nodeNr the node number of the attribute node
626 * @return the typed value of the node
627 * @throws net.sf.saxon.trans.XPathException if an error is found
628 */
629
630 public AtomicSequence getTypedValueOfAttribute(/*@Nullable*/ TinyAttributeImpl att, int nodeNr) throws XPathException {
631 if (attType == null) {
632 // it's an untyped tree
633 return new UntypedAtomicValue(attValue[nodeNr]);
634 }
635 if (attTypedValue == null || attTypedValue[nodeNr] == null) {
636 SimpleType type = getAttributeType(nodeNr);
637 if (type.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
638 return new UntypedAtomicValue(attValue[nodeNr]);
639 } else if (type.equals(BuiltInAtomicType.STRING)) {
640 return new StringValue(attValue[nodeNr]);
641 } else if (type.equals(BuiltInAtomicType.ANY_URI)) {
642 return new AnyURIValue(attValue[nodeNr]);
643 } else {
644 if (att == null) {
645 att = new TinyAttributeImpl(this, nodeNr);
646 }
647 AtomicSequence value = type.atomize(att);
648 if (allowTypedValueCache) {
649 if (attTypedValue == null) {
650 //noinspection unchecked
651 attTypedValue = new AtomicSequence[attParent.length];
652 }
653 attTypedValue[nodeNr] = value;
654 }
655 return value;
656
657 }
658 } else {
659 return attTypedValue[nodeNr];
660 }
661 }
662
663
664 /**
665 * Get the node kind of a given node, which must be a document, element,
666 * text, comment, or processing instruction node
667 *
668 * @param nodeNr the node number
669 * @return the node kind
670 */
671
672 public int getNodeKind(int nodeNr) {
673 int kind = nodeKind[nodeNr];
674 return kind == Type.WHITESPACE_TEXT ? Type.TEXT : kind;
675 }
676
677 /**
678 * Get the nameCode for a given node, which must be a document, element,
679 * text, comment, or processing instruction node
680 *
681 * @param nodeNr the node number
682 * @return the name code
683 */
684
685 public int getNameCode(int nodeNr) {
686 return nameCode[nodeNr];
687 }
688
689 /**
690 * Get the fingerprint for a given node, which must be a document, element,
691 * text, comment, or processing instruction node
692 *
693 * @param nodeNr the node number
694 * @return the name code
695 */
696
697 public int getFingerprint(int nodeNr) {
698 int nc = nameCode[nodeNr];
699 return nc == -1 ? -1 : nc & NamePool.FP_MASK;
700 }
701
702
703 /**
704 * Get the prefix for a given element node
705 *
706 * @param nodeNr the node number
707 * @return the prefix. Return "" for an unprefixed element node. Result is
708 * undefined for a non-element node.
709 */
710
711 public String getPrefix(int nodeNr) {
712 int code = nameCode[nodeNr] >> 20;
713 if (code <= 0) {
714 return code == 0 ? "" : null;
715 }
716 return prefixPool.getPrefix(code);
717 }
718
719 /**
720 * On demand, make an index for quick access to preceding-sibling nodes
721 */
722
723 void ensurePriorIndex() {
724 if (prior == null || prior.length < numberOfNodes) { // bug 3665
725 makePriorIndex();
726 }
727 }
728
729 private synchronized void makePriorIndex() {
730 int[] p = new int[numberOfNodes];
731 Arrays.fill(p, 0, numberOfNodes, -1);
732 for (int i = 0; i < numberOfNodes; i++) {
733 int nextNode = next[i];
734 if (nextNode > i) {
735 p[nextNode] = i;
736 }
737 }
738 prior = p;
739 }
740
741 /**
742 * Add an attribute node to the tree
743 *
744 * @param root the root of the tree to contain the attribute
745 * @param parent the parent element of the new attribute
746 * @param nameCode the name code of the attribute
747 * @param type the type annotation of the attribute
748 * @param attValue the string value of the attribute
749 * @param properties any special properties of the attribute (bit-significant)
750 */
751
752
753 void addAttribute(/*@NotNull*/ NodeInfo root, int parent, int nameCode, SimpleType type, CharSequence attValue, int properties) {
754 ensureAttributeCapacity(1);
755 attParent[numberOfAttributes] = parent;
756 attCode[numberOfAttributes] = nameCode;
757 this.attValue[numberOfAttributes] = attValue.toString();
758
759 if (!type.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
760 initializeAttributeTypeCodes();
761 }
762
763 if (attType != null) {
764 attType[numberOfAttributes] = type;
765 }
766
767 if (alpha[parent] == -1) {
768 alpha[parent] = numberOfAttributes;
769 }
770
771 if (root instanceof TinyDocumentImpl) {
772 boolean isID = false;
773 try {
774 if ((properties & ReceiverOptions.IS_ID) != 0) {
775 isID = true;
776 } else if ((nameCode & NamePool.FP_MASK) == StandardNames.XML_ID) {
777 isID = true;
778 } else if (type.isIdType()) {
779 isID = true;
780 }
781 } catch (MissingComponentException e) {
782 // isID = false;
783 }
784 if (isID) {
785
786 // The attribute is marked as being an ID. But we don't trust it - it
787 // might come from a non-validating parser. Before adding it to the index, we
788 // check that it really is an ID.
789
790 String id = Whitespace.trim(attValue);
791
792 // Make an exception to our usual policy of storing the original string value.
793 // This is because xml:id processing applies whitespace trimming at an earlier stage
794 this.attValue[numberOfAttributes] = id;
795
796 if (NameChecker.isValidNCName(id)) {
797 NodeInfo e = getNode(parent);
798 registerID(e, id);
799 } else if (attType != null) {
800 attType[numberOfAttributes] = BuiltInAtomicType.UNTYPED_ATOMIC;
801 }
802 }
803 boolean isIDREF = false;
804 try {
805 if ((properties & ReceiverOptions.IS_IDREF) != 0) {
806 isIDREF = true;
807 } else if (type == BuiltInAtomicType.IDREF || type == BuiltInListType.IDREFS) {
808 isIDREF = true;
809 } else if (type.isIdRefType()) {
810 // The attribute has the idref property only if at least one item in its typed value
811 // is an IDREF: see Saxon bug 2331
812 try {
813 AtomicSequence as = type.getTypedValue(attValue, null, getConfiguration().getConversionRules());
814 for (AtomicValue v : as) {
815 if (v.getItemType().isIdRefType()) {
816 isIDREF = true;
817 break;
818 }
819 }
820 } catch (ValidationException ve) {
821 // isIDREF = false
822 }
823 }
824 } catch (MissingComponentException e) {
825 // isIDREF = false
826 }
827 if (isIDREF) {
828 if (idRefAttributes == null) {
829 idRefAttributes = new IntHashSet();
830 }
831 idRefAttributes.add(numberOfAttributes);
832 }
833 }
834
835 // Note: IDREF attributes are not indexed at this stage; that happens only if and when
836 // the idref() function is called.
837
838 // Note that an attTypes array will be created for all attributes if any IDREF value is reported.
839
840 numberOfAttributes++;
841 }
842
843 private void initializeAttributeTypeCodes() {
844 if (attType == null) {
845 // this is the first typed attribute;
846 // create an array for the types, and set all previous attributes to untyped
847 attType = new SimpleType[attParent.length];
848 Arrays.fill(attType, 0, numberOfAttributes, BuiltInAtomicType.UNTYPED_ATOMIC);
849 // for (int i=0; i<numberOfAttributes; i++) {
850 // attTypeCode[i] = StandardNames.XDT_UNTYPED_ATOMIC;
851 // }
852 }
853 }
854
855 /**
856 * Mark an attribute as resulting from expansion of attribute defaults
857 *
858 * @param attNr the attribute number
859 */
860
861 public void markDefaultedAttribute(int attNr) {
862 if (defaultedAttributes == null) {
863 defaultedAttributes = new IntHashSet();
864 }
865 defaultedAttributes.add(attNr);
866 }
867
868 /**
869 * Ask whether an attribute results from expansion of attribute defaults
870 *
871 * @param attNr the attribute number
872 * @return true if this attribute resulted from expansion of default or fixed values defined
873 * in a schema. Note that this property will only be set if both the configuration properties
874 * {@link FeatureKeys#EXPAND_ATTRIBUTE_DEFAULTS} and {@link FeatureKeys#MARK_DEFAULTED_ATTRIBUTES}
875 * are set.
876 */
877
878 public boolean isDefaultedAttribute(int attNr) {
879 return defaultedAttributes != null && defaultedAttributes.contains(attNr);
880 }
881
882 /**
883 * Index an element of type xs:ID
884 *
885 * @param root the root node of the document
886 * @param nodeNr the element of type xs:ID
887 */
888
889 public void indexIDElement(/*@NotNull*/ NodeInfo root, int nodeNr) {
890 String id = Whitespace.trim(TinyParentNodeImpl.getStringValueCS(this, nodeNr));
891 if (root.getNodeKind() == Type.DOCUMENT && NameChecker.isValidNCName(id)) {
892 NodeInfo e = getNode(nodeNr);
893 registerID(e, id);
894 }
895 }
896
897 /**
898 * Ask whether, somewhere in the tree, there is an attribute xml:space="preserve"
899 *
900 * @return true if some element in the tree has an xml:space attribute with the value preserve
901 */
902
903 public boolean hasXmlSpacePreserveAttribute() {
904 for (int i = 0; i < numberOfAttributes; i++) {
905 if ((attCode[i] & NamePool.FP_MASK) == StandardNames.XML_SPACE && "preserve".equals(attValue[i].toString())) {
906 return true;
907 }
908 }
909 return false;
910 }
911
912 /**
913 * Add a namespace node to the current element
914 *
915 * @param parent the node number of the element
916 * @param binding namespace identifying the prefix and uri
917 */
918 void addNamespace(int parent, /*@NotNull*/ NamespaceBinding binding) {
919
920 ensureNamespaceCapacity(1);
921 namespaceParent[numberOfNamespaces] = parent;
922 namespaceBinding[numberOfNamespaces] = binding;
923
924 if (beta[parent] == -1) {
925 beta[parent] = numberOfNamespaces;
926 }
927 numberOfNamespaces++;
928 if (!binding.isXmlNamespace()) {
929 usesNamespaces = true;
930 }
931 }
932
933 /**
934 * Get the node at a given position in the tree
935 *
936 * @param nr the node number
937 * @return the node at the given position
938 */
939
940 public final TinyNodeImpl getNode(int nr) {
941 switch (nodeKind[nr]) {
942 case Type.DOCUMENT:
943 return (TinyDocumentImpl) getRootNode();
944 case Type.ELEMENT:
945 return new TinyElementImpl(this, nr);
946 case Type.TEXTUAL_ELEMENT:
947 return new TinyTextualElement(this, nr);
948 case Type.EXTERNAL_NODE_REFERENCE:
949 return externalNodes.get(alpha[nr]);
950 case Type.TEXT:
951 return new TinyTextImpl(this, nr);
952 case Type.WHITESPACE_TEXT:
953 return new WhitespaceTextImpl(this, nr);
954 case Type.COMMENT:
955 return new TinyCommentImpl(this, nr);
956 case Type.PROCESSING_INSTRUCTION:
957 return new TinyProcInstImpl(this, nr);
958 case Type.PARENT_POINTER:
959 throw new IllegalArgumentException("Attempting to treat a parent pointer as a node");
960 case Type.STOPPER:
961 throw new IllegalArgumentException("Attempting to treat a stopper entry as a node");
962 default:
963 throw new IllegalStateException("Unknown node kind " + nodeKind[nr]);
964 }
965 }
966
967 /**
968 * Get the typed value of a node whose type is known to be untypedAtomic.
969 * The node must be a document, element, text,
970 * comment, or processing-instruction node, and it must have no type annotation.
971 * This method gets the typed value
972 * of a numbered node without actually instantiating the NodeInfo object, as
973 * a performance optimization.
974 *
975 * @param nodeNr the node whose typed value is required
976 * @return the atomic value of the node
977 */
978
979 AtomicValue getAtomizedValueOfUntypedNode(int nodeNr) {
980 switch (nodeKind[nodeNr]) {
981 case Type.ELEMENT:
982 case Type.DOCUMENT:
983 int level = depth[nodeNr];
984 int next = nodeNr + 1;
985
986 // we optimize two special cases: firstly, where the node has no children, and secondly,
987 // where it has a single text node as a child.
988
989 if (depth[next] <= level) {
990 return UntypedAtomicValue.ZERO_LENGTH_UNTYPED;
991 } else if (nodeKind[next] == Type.TEXT && depth[next + 1] <= level) {
992 int length = beta[next];
993 int start = alpha[next];
994 return new UntypedAtomicValue(charBuffer.subSequence(start, start + length));
995 } else if (nodeKind[next] == Type.WHITESPACE_TEXT && depth[next + 1] <= level) {
996 return new UntypedAtomicValue(WhitespaceTextImpl.getStringValueCS(this, next));
997 }
998
999 // Now handle the general case
1000
1001 FastStringBuffer sb = null;
1002 while (next < numberOfNodes && depth[next] > level) {
1003 if (nodeKind[next] == Type.TEXT) {
1004 if (sb == null) {
1005 sb = new FastStringBuffer(FastStringBuffer.C256);
1006 }
1007 sb.append(TinyTextImpl.getStringValue(this, next));
1008 } else if (nodeKind[next] == Type.WHITESPACE_TEXT) {
1009 if (sb == null) {
1010 sb = new FastStringBuffer(FastStringBuffer.C256);
1011 }
1012 WhitespaceTextImpl.appendStringValue(this, next, sb);
1013 }
1014 next++;
1015 }
1016 if (sb == null) {
1017 return UntypedAtomicValue.ZERO_LENGTH_UNTYPED;
1018 } else {
1019 return new UntypedAtomicValue(sb.condense());
1020 }
1021
1022 case Type.TEXT:
1023 return new UntypedAtomicValue(TinyTextImpl.getStringValue(this, nodeNr));
1024 case Type.WHITESPACE_TEXT:
1025 return new UntypedAtomicValue(WhitespaceTextImpl.getStringValueCS(this, nodeNr));
1026 case Type.COMMENT:
1027 case Type.PROCESSING_INSTRUCTION:
1028 int start2 = alpha[nodeNr];
1029 int len2 = beta[nodeNr];
1030 if (len2 == 0) {
1031 return UntypedAtomicValue.ZERO_LENGTH_UNTYPED;
1032 }
1033 char[] dest = new char[len2];
1034 assert commentBuffer != null;
1035 commentBuffer.getChars(start2, start2 + len2, dest, 0);
1036 return new StringValue(new CharSlice(dest, 0, len2));
1037 default:
1038 throw new IllegalStateException("Unknown node kind");
1039 }
1040 }
1041
1042 /**
1043 * Make a (transient) attribute node from the array of attributes
1044 *
1045 * @param nr the node number of the attribute
1046 * @return an attribute node
1047 */
1048
1049 /*@NotNull*/ TinyAttributeImpl getAttributeNode(int nr) {
1050 return new TinyAttributeImpl(this, nr);
1051 }
1052
1053 /**
1054 * Get the type annotation of an attribute node.
1055 *
1056 * @param nr the node number of the attribute
1057 * @return the fingerprint of the type annotation, or Type.UNTYPED_ATOMIC if there is no annotation
1058 */
1059
1060 int getAttributeAnnotation(int nr) {
1061 if (attType == null) {
1062 return StandardNames.XS_UNTYPED_ATOMIC;
1063 } else {
1064 return attType[nr].getFingerprint();
1065 }
1066 }
1067
1068 /**
1069 * Get the type annotation of an attribute node.
1070 *
1071 * @param nr the node number of the attribute
1072 * @return the fingerprint of the type annotation, or Type.UNTYPED_ATOMIC if there is no annotation
1073 */
1074
1075 SimpleType getAttributeType(int nr) {
1076 if (attType == null) {
1077 return BuiltInAtomicType.UNTYPED_ATOMIC;
1078 } else {
1079 return attType[nr];
1080 }
1081 }
1082
1083 /**
1084 * Determine whether an attribute is an ID attribute. (The represents the
1085 * is-id property in the data model)
1086 *
1087 * @param nr the node number of the attribute
1088 * @return true if this is an ID attribute
1089 */
1090
1091 public boolean isIdAttribute(int nr) {
1092 try {
1093 return attType != null && getAttributeType(nr).isIdType();
1094 } catch (MissingComponentException e) {
1095 return false;
1096 }
1097 }
1098
1099
1100 /**
1101 * Determine whether an attribute is an IDREF/IDREFS attribute. (The represents the
1102 * is-idref property in the data model)
1103 *
1104 * @param nr the node number of the attribute
1105 * @return true if this is an IDREF/IDREFS attribute
1106 */
1107
1108 public boolean isIdrefAttribute(int nr) {
1109 return idRefAttributes != null && idRefAttributes.contains(nr);
1110 }
1111
1112 /**
1113 * Ask whether an element is an ID element. (The represents the
1114 * is-id property in the data model)
1115 *
1116 * @param nr the element node whose is-id property is required
1117 * @return true if the node has the is-id property
1118 */
1119
1120 public boolean isIdElement(int nr) {
1121 try {
1122 return getSchemaType(nr).isIdType() && getTypedValueOfElement(nr).getLength() == 1;
1123 } catch (XPathException e) {
1124 return false;
1125 }
1126 }
1127
1128 /**
1129 * Ask whether an element is an IDREF/IDREFS element. (The represents the
1130 * is-idref property in the data model)
1131 *
1132 * @param nr the element node whose is-idref property is required
1133 * @return true if the node has the is-idref property
1134 */
1135
1136 public boolean isIdrefElement(int nr) {
1137 SchemaType type = getSchemaType(nr);
1138 try {
1139 if (type.isIdRefType()) {
1140 if (type == BuiltInAtomicType.IDREF || type == BuiltInListType.IDREFS) {
1141 return true;
1142 }
1143 try {
1144 for (AtomicValue av : getTypedValueOfElement(nr)) {
1145 if (av.getItemType().isIdRefType()) {
1146 return true;
1147 }
1148 }
1149 } catch (XPathException err) {
1150 // no action
1151 }
1152 }
1153 } catch (MissingComponentException e) {
1154 return false;
1155 }
1156 return false;
1157 }
1158
1159
1160 /**
1161 * Set the system id of an element in the document. This identifies the external entity containing
1162 * the node - this is not necessarily the same as the base URI.
1163 *
1164 * @param seq the node number
1165 * @param uri the system ID
1166 */
1167
1168 void setSystemId(int seq, /*@Nullable*/ String uri) {
1169 if (uri == null) {
1170 uri = "";
1171 }
1172 if (systemIdMap == null) {
1173 systemIdMap = new SystemIdMap();
1174 }
1175 systemIdMap.setSystemId(seq, uri);
1176 }
1177
1178
1179 /**
1180 * Get the system id of an element in the document
1181 *
1182 * @param seq the node number of the element node
1183 * @return the system id (base URI) of the element
1184 */
1185
1186 /*@Nullable*/
1187 public String getSystemId(int seq) {
1188 if (systemIdMap == null) {
1189 return null;
1190 }
1191 return systemIdMap.getSystemId(seq);
1192 }
1193
1194
1195 public NodeInfo getRootNode() {
1196 if (getNodeKind(0) == Type.DOCUMENT) {
1197 if (root != null) {
1198 return root;
1199 } else {
1200 root = new TinyDocumentImpl(this);
1201 return root;
1202 }
1203 } else {
1204 return getNode(0);
1205 }
1206 }
1207
1208 /**
1209 * Set line numbering on
1210 */
1211
1212 public void setLineNumbering() {
1213 lineNumbers = new int[nodeKind.length];
1214 Arrays.fill(lineNumbers, -1);
1215 columnNumbers = new int[nodeKind.length];
1216 Arrays.fill(columnNumbers, -1);
1217 }
1218
1219 /**
1220 * Set the line number for a node. Ignored if line numbering is off.
1221 *
1222 * @param sequence the node number
1223 * @param line the line number to be set for the node
1224 * @param column the column number for the node
1225 */
1226
1227 void setLineNumber(int sequence, int line, int column) {
1228 if (lineNumbers != null) {
1229 assert columnNumbers != null;
1230 lineNumbers[sequence] = line;
1231 columnNumbers[sequence] = column;
1232 }
1233 }
1234
1235 /**
1236 * Get the line number for a node.
1237 *
1238 * @param sequence the node number
1239 * @return the line number of the node. Return -1 if line numbering is off.
1240 */
1241
1242 public int getLineNumber(int sequence) {
1243 if (lineNumbers != null) {
1244 // find the nearest preceding node that has a known line number, and return it
1245 for (int i = sequence; i >= 0; i--) {
1246 int c = lineNumbers[i];
1247 if (c > 0) {
1248 return c;
1249 }
1250 }
1251 }
1252 return -1;
1253 }
1254
1255 /**
1256 * Get the column number for a node.
1257 *
1258 * @param sequence the node number
1259 * @return the line number of the node. Return -1 if line numbering is off.
1260 */
1261
1262 public int getColumnNumber(int sequence) {
1263 if (columnNumbers != null) {
1264 // find the nearest preceding node that has a known column number, and return it
1265 for (int i = sequence; i >= 0; i--) {
1266 int c = columnNumbers[i];
1267 if (c > 0) {
1268 return c;
1269 }
1270 }
1271 }
1272 return -1;
1273 }
1274
1275 /**
1276 * Set an element node to be marked as nilled
1277 *
1278 * @param nodeNr the node number to be marked as nilled
1279 */
1280
1281 public void setNilled(int nodeNr) {
1282 if (nilledElements == null) {
1283 nilledElements = new IntHashSet();
1284 }
1285 nilledElements.add(nodeNr);
1286 }
1287
1288 /**
1289 * Ask whether a given node is nilled
1290 *
1291 * @param nodeNr the node in question (which must be an element node)
1292 * @return true if the node has the nilled property
1293 */
1294
1295 public boolean isNilled(int nodeNr) {
1296 return nilledElements != null && nilledElements.contains(nodeNr);
1297 }
1298
1299 /**
1300 * Register a unique element ID. Fails if there is already an element with that ID.
1301 *
1302 * @param e The NodeInfo (always an element) having a particular unique ID value
1303 * @param id The unique ID value. The caller is responsible for checking that this
1304 * is a valid NCName.
1305 */
1306
1307 void registerID(NodeInfo e, String id) {
1308 if (idTable == null) {
1309 idTable = new HashMap<>(256);
1310 }
1311
1312 // the XPath spec (5.2.1) says ignore the second ID if it's not unique
1313 idTable.putIfAbsent(id, e);
1314
1315 }
1316
1317 /**
1318 * Get the element with a given ID.
1319 *
1320 * @param id The unique ID of the required element, previously registered using registerID()
1321 * @param getParent true if the required element is the parent of the element of type ID
1322 * @return The NodeInfo (always an Element) for the given ID if one has been registered,
1323 * otherwise null.
1324 */
1325
1326 /*@Nullable*/
1327 public NodeInfo selectID(String id, boolean getParent) {
1328 if (idTable == null) {
1329 return null; // no ID values found
1330 }
1331 NodeInfo node = idTable.get(id);
1332 if (node != null && getParent && node.isId() && node.getStringValue().equals(id)) {
1333 node = node.getParent();
1334 }
1335 return node;
1336 }
1337
1338
1339 /**
1340 * Set an unparsed entity URI associated with this document. For system use only, while
1341 * building the document.
1342 *
1343 * @param name the name of the unparsed entity
1344 * @param uri the system identifier of the unparsed entity
1345 * @param publicId the public identifier of the unparsed entity
1346 */
1347
1348 void setUnparsedEntity(String name, String uri, String publicId) {
1349 if (entityTable == null) {
1350 entityTable = new HashMap<>(20);
1351 }
1352 String[] ids = new String[2];
1353 ids[0] = uri;
1354 ids[1] = publicId;
1355 entityTable.put(name, ids);
1356 }
1357
1358 /**
1359 * Get the list of unparsed entities defined in this document
1360 *
1361 * @return an Iterator, whose items are of type String, containing the names of all
1362 * unparsed entities defined in this document. If there are no unparsed entities or if the
1363 * information is not available then an empty iterator is returned
1364 */
1365
1366 public Iterator<String> getUnparsedEntityNames() {
1367 if (entityTable == null) {
1368 List<String> emptyList = Collections.emptyList();
1369 return emptyList.iterator();
1370 } else {
1371 return entityTable.keySet().iterator();
1372 }
1373 }
1374
1375 /**
1376 * Get the unparsed entity with a given nameID if there is one, or null if not. If the entity
1377 * does not exist, return null.
1378 *
1379 * @param name the name of the entity
1380 * @return if the entity exists, return an array of two Strings, the first holding the system ID
1381 * of the entity, the second holding the public
1382 */
1383
1384 /*@Nullable*/
1385 public String[] getUnparsedEntity(String name) {
1386 if (entityTable == null) {
1387 return null;
1388 }
1389 return entityTable.get(name);
1390 }
1391
1392 public NamePool getNamePool() {
1393 return getConfiguration().getNamePool();
1394 }
1395
1396 public void markTopWithinEntity(int nodeNr) {
1397 if (topWithinEntity == null) {
1398 topWithinEntity = new IntHashSet();
1399 }
1400 topWithinEntity.add(nodeNr);
1401 }
1402
1403 public boolean isTopWithinEntity(int nodeNr) {
1404 return topWithinEntity != null && topWithinEntity.contains(nodeNr);
1405 }
1406
1407
1408 /**
1409 * Produce diagnostic print of main tree arrays
1410 */
1411
1412 @SuppressWarnings("UseOfSystemOutOrSystemErr")
1413 public void diagnosticDump() {
1414 NamePool pool = getNamePool();
1415 System.err.println(" node kind depth next alpha beta name type");
1416 for (int i = 0; i < numberOfNodes; i++) {
1417 String eqName = "";
1418 if (nameCode[i] != -1) {
1419 try {
1420 eqName = pool.getEQName(nameCode[i]);
1421 } catch (Exception err) {
1422 eqName = "#" + nameCode[1];
1423 }
1424 }
1425 System.err.println(n8(i) + n8(nodeKind[i]) + n8(depth[i]) + n8(next[i]) +
1426 n8(alpha[i]) + n8(beta[i]) + n8(nameCode[i]) +
1427 n8(getTypeAnnotation(i)) + " " + eqName);
1428 }
1429 System.err.println(" attr parent name value");
1430 for (int i = 0; i < numberOfAttributes; i++) {
1431 System.err.println(n8(i) + n8(attParent[i]) + n8(attCode[i]) + " " + attValue[i]);
1432 }
1433 System.err.println(" ns parent prefix uri");
1434 for (int i = 0; i < numberOfNamespaces; i++) {
1435 System.err.println(n8(i) + n8(namespaceParent[i]) + namespaceBinding[i].getPrefix() + "=" + namespaceBinding[i].getURI());
1436 }
1437 }
1438
1439 /**
1440 * Create diagnostic dump of the tree containing a particular node.
1441 * Designed to be called as an extension function for diagnostics.
1442 *
1443 * @param node the node in question
1444 */
1445
1446 public static synchronized void diagnosticDump(/*@NotNull*/ NodeInfo node) {
1447 if (node instanceof TinyNodeImpl) {
1448 TinyTree tree = ((TinyNodeImpl) node).tree;
1449 System.err.println("Tree containing node " + ((TinyNodeImpl) node).nodeNr);
1450 tree.diagnosticDump();
1451 } else {
1452 System.err.println("Node is not in a TinyTree");
1453 }
1454 }
1455
1456 /**
1457 * Output a number as a string of 8 characters
1458 *
1459 * @param val the number
1460 * @return the string representation of the number, aligned in a fixed width field
1461 */
1462
1463 private static String n8(int val) {
1464 String s = " " + val;
1465 return s.substring(s.length() - 8);
1466 }
1467
1468 /**
1469 * Output a statistical summary to System.err
1470 */
1471
1472 public void showSize() {
1473 System.err.println("Tree size: " + numberOfNodes + " nodes, " + charBuffer.length() + " characters, " +
1474 numberOfAttributes + " attributes");
1475 }
1476
1477 /**
1478 * Ask whether the document contains any nodes whose type annotation is anything other than
1479 * UNTYPED
1480 *
1481 * @return true if the document contains elements whose type is other than UNTYPED
1482 */
1483 public boolean isTyped() {
1484 return typeArray != null;
1485 }
1486
1487 /**
1488 * Get the number of nodes in the tree, excluding attributes and namespace nodes
1489 *
1490 * @return the number of nodes.
1491 */
1492
1493 public int getNumberOfNodes() {
1494 return numberOfNodes;
1495 }
1496
1497 /**
1498 * Get the number of attributes in the tree
1499 *
1500 * @return the number of attributes
1501 */
1502
1503 public int getNumberOfAttributes() {
1504 return numberOfAttributes;
1505 }
1506
1507 /**
1508 * Get the number of namespace declarations in the tree
1509 *
1510 * @return the number of namespace declarations
1511 */
1512
1513 public int getNumberOfNamespaces() {
1514 return numberOfNamespaces;
1515 }
1516
1517 /**
1518 * Get the array holding node kind information
1519 *
1520 * @return an array of bytes, byte N is the node kind of node number N
1521 */
1522
1523 public byte[] getNodeKindArray() {
1524 return nodeKind;
1525 }
1526
1527 /**
1528 * Get the array holding node depth information
1529 *
1530 * @return an array of shorts, byte N is the node depth of node number N
1531 */
1532
1533 public short[] getNodeDepthArray() {
1534 return depth;
1535 }
1536
1537 /**
1538 * Get the array holding node name information
1539 *
1540 * @return an array of integers, integer N is the name code of node number N
1541 */
1542
1543 public int[] getNameCodeArray() {
1544 return nameCode;
1545 }
1546
1547 /**
1548 * Get the array holding node type information
1549 *
1550 * @return an array of integers, integer N is the type code of node number N
1551 */
1552
1553 /*@Nullable*/
1554 public SchemaType[] getTypeArray() {
1555 return typeArray;
1556 }
1557
1558 /**
1559 * Get the array holding next-sibling pointers
1560 *
1561 * @return an array of integers, integer N is the next-sibling pointer for node number N
1562 */
1563
1564 public int[] getNextPointerArray() {
1565 return next;
1566 }
1567
1568 /**
1569 * Get the array holding alpha information
1570 *
1571 * @return an array of integers, whose meaning depends on the node kind. For elements it is a pointer
1572 * to the first attribute, for text, comment, and processing instruction nodes it is a pointer to the content
1573 */
1574
1575 public int[] getAlphaArray() {
1576 return alpha;
1577 }
1578
1579 /**
1580 * Get the array holding beta information
1581 *
1582 * @return an array of integers, whose meaning depends on the node kind. For elements it is a pointer
1583 * to the first namespace declaration
1584 */
1585
1586 public int[] getBetaArray() {
1587 return beta;
1588 }
1589
1590 /**
1591 * Get the character buffer used to hold all the text data of the document
1592 *
1593 * @return the character buffer
1594 */
1595
1596 public AppendableCharSequence getCharacterBuffer() {
1597 //return new CharSlice(charBuffer, 0, charBufferLength);
1598 return charBuffer;
1599 }
1600
1601 /**
1602 * Get the character buffer used to hold all the comment data of the document
1603 *
1604 * @return the character buffer used for comments
1605 */
1606
1607 /*@Nullable*/
1608 public CharSequence getCommentBuffer() {
1609 return commentBuffer;
1610 }
1611
1612 /**
1613 * Get the array used to hold the name codes of all attributes
1614 *
1615 * @return an integer array; the Nth integer holds the attribute name code of attribute N
1616 */
1617
1618 public int[] getAttributeNameCodeArray() {
1619 return attCode;
1620 }
1621
1622 /**
1623 * Get the array used to hold the type codes of all attributes
1624 *
1625 * @return an integer array; the Nth integer holds the attribute type code of attribute N
1626 */
1627
1628 /*@Nullable*/
1629 public SimpleType[] getAttributeTypeArray() {
1630 return attType;
1631 }
1632
1633 /**
1634 * Get the array used to hold the parent pointers of all attributes
1635 *
1636 * @return an integer array; the Nth integer holds the pointer to the parent element of attribute N
1637 */
1638
1639 public int[] getAttributeParentArray() {
1640 return attParent;
1641 }
1642
1643 /**
1644 * Get the array used to hold the name codes of all attributes
1645 *
1646 * @return an array of strings; the Nth string holds the string value of attribute N
1647 */
1648
1649 public CharSequence[] getAttributeValueArray() {
1650 return attValue;
1651 }
1652
1653 /**
1654 * Get the array used to hold the namespace declarations
1655 *
1656 * @return an array of namespace bindings
1657 */
1658
1659 public NamespaceBinding[] getNamespaceBindings() {
1660 return namespaceBinding;
1661 }
1662
1663 /**
1664 * Get the array used to hold the parent pointers of all namespace declarations
1665 *
1666 * @return an integer array; the Nth integer holds the pointer to the parent element of namespace N
1667 */
1668
1669 public int[] getNamespaceParentArray() {
1670 return namespaceParent;
1671 }
1672
1673 /**
1674 * Ask whether the tree contains any namespace declarations
1675 *
1676 * @return true if there is a namespace declaration (other than the XML namespace) anywhere
1677 * in the tree
1678 */
1679
1680 public boolean isUsesNamespaces() {
1681 return usesNamespaces;
1682 }
1683
1684 /**
1685 * Bulk copy an element node from another TinyTree. Type annotations will always be
1686 * stripped.
1687 *
1688 * @param source the source tree
1689 * @param nodeNr the element node to be deep-copied
1690 */
1691
1692
1693 public void bulkCopy(TinyTree source, int nodeNr, int[] prevAtDepth, int currentDepth) {
1694 //System.err.println(" **** doing bulk copy **** ");
1695 int end = source.next[nodeNr];
1696 while (end < nodeNr && end >= 0) {
1697 end = source.next[end];
1698 }
1699 if (end == -1) {
1700 end = source.numberOfNodes;
1701 if (end - 1 < source.nodeKind.length && source.nodeKind[end - 1] == Type.STOPPER) {
1702 end--;
1703 }
1704 }
1705 int length = end - nodeNr;
1706 assert length > 0; // Bug 4089 bites here
1707 ensureNodeCapacity(Type.ELEMENT, length);
1708 System.arraycopy(source.nodeKind, nodeNr, nodeKind, numberOfNodes, length);
1709 int depthDiff = currentDepth - source.depth[nodeNr];
1710 for (int i = 0; i < length; i++) {
1711 int from = nodeNr + i;
1712 int to = numberOfNodes + i;
1713 depth[to] = (short) (source.depth[from] + depthDiff);
1714 next[to] = source.next[from] + (to - from);
1715 switch (source.nodeKind[from]) {
1716 case Type.ELEMENT: {
1717 nameCode[to] = (source.nameCode[from] & NamePool.FP_MASK) |
1718 (prefixPool.obtainPrefixCode(source.getPrefix(from)) << 20);
1719 int firstAtt = source.alpha[from];
1720 if (firstAtt >= 0) {
1721 int lastAtt = firstAtt;
1722 while (lastAtt < source.numberOfAttributes && source.attParent[lastAtt] == from) {
1723 lastAtt++;
1724 }
1725 int atts = lastAtt - firstAtt;
1726 ensureAttributeCapacity(atts);
1727 int aFrom = firstAtt;
1728 int aTo = numberOfAttributes;
1729 alpha[to] = aTo;
1730 System.arraycopy(source.attValue, firstAtt, attValue, aTo, atts);
1731 Arrays.fill(attParent, aTo, aTo + atts, to);
1732 for (int a = 0; a < atts; a++, aFrom++, aTo++) {
1733 int attNameCode = attCode[aTo] = source.attCode[aFrom];
1734 if (NamePool.isPrefixed(attNameCode)) {
1735 String prefix = source.prefixPool.getPrefix(attNameCode >> 20);
1736 attCode[aTo] = (attNameCode & 0xfffff) | (prefixPool.obtainPrefixCode(prefix) << 20);
1737 } else {
1738 attCode[aTo] = attNameCode;
1739 }
1740 if (source.isIdAttribute(aFrom)) {
1741 registerID(getNode(to), source.attValue[aFrom].toString());
1742 }
1743 if (source.isIdrefAttribute(aFrom)) {
1744 if (idRefAttributes == null) {
1745 idRefAttributes = new IntHashSet();
1746 }
1747 idRefAttributes.add(aTo);
1748 }
1749 }
1750 numberOfAttributes += atts;
1751 } else {
1752 alpha[to] = -1;
1753 }
1754 // Copy the namespaces. For the top-level element node, this needs special
1755 // attention: we need to ensure that all the in-scope namespaces of the
1756 // source node are declared in the new tree. We may also need to undeclare
1757 // a default namespace that is present in the target tree, but unwanted in the
1758 // new element node.
1759 if (i == 0) {
1760 boolean foundDefaultNamespace = false;
1761 Map<String, String> targetNamespaces = inScopeNamespaces(this, to, prevAtDepth, currentDepth);
1762 List<NamespaceBinding> newNamespaces = new ArrayList<>();
1763 NamespaceBinding[] sourceBindings = source.namespaceBinding;
1764 int anc = from;
1765 while (anc != -1 && source.nodeKind[anc] == Type.ELEMENT) {
1766 int sourceNS = source.beta[anc];
1767 while (sourceNS > 0 && sourceNS < source.numberOfNamespaces && source.namespaceParent[sourceNS] == anc) {
1768 NamespaceBinding nb = sourceBindings[sourceNS];
1769 String prefix = nb.getPrefix();
1770 if (prefix.isEmpty()) {
1771 foundDefaultNamespace = true;
1772 }
1773 String existing = targetNamespaces.get(prefix);
1774 if (existing == null || !existing.equals(prefix)) {
1775 newNamespaces.add(nb);
1776 }
1777 sourceNS++;
1778 }
1779 anc = TinyNodeImpl.getParentNodeNr(source, anc);
1780 }
1781 if (!foundDefaultNamespace && targetNamespaces.get("") != null) {
1782 newNamespaces.add(NamespaceBinding.DEFAULT_UNDECLARATION);
1783 }
1784
1785 int nTo = numberOfNamespaces;
1786 ensureNamespaceCapacity(newNamespaces.size());
1787 beta[to] = nTo;
1788 for (NamespaceBinding nb : newNamespaces) {
1789 namespaceBinding[nTo++] = nb;
1790 }
1791 Arrays.fill(namespaceParent, numberOfNamespaces, nTo, to);
1792 numberOfNamespaces = nTo;
1793
1794 } else {
1795 int firstNS = source.beta[from];
1796 if (firstNS >= 0) {
1797 int lastNS = firstNS;
1798 while (lastNS < source.numberOfNamespaces && source.namespaceParent[lastNS] == from) {
1799 lastNS++;
1800 }
1801 int nrOfNamespaces = lastNS - firstNS;
1802 ensureNamespaceCapacity(nrOfNamespaces);
1803 int nTo = numberOfNamespaces;
1804 beta[to] = nTo;
1805 System.arraycopy(source.namespaceBinding, firstNS, namespaceBinding, nTo, nrOfNamespaces);
1806 Arrays.fill(namespaceParent, nTo, nTo + nrOfNamespaces, to);
1807 numberOfNamespaces += nrOfNamespaces;
1808 } else {
1809 beta[to] = -1;
1810 }
1811 }
1812 break;
1813 }
1814 case Type.TEXTUAL_ELEMENT: {
1815 int start = source.alpha[from];
1816 int len = source.beta[from];
1817 nameCode[to] = (source.nameCode[from] & NamePool.FP_MASK) |
1818 (prefixPool.obtainPrefixCode(source.getPrefix(from)) << 20);
1819 alpha[to] = charBuffer.length();
1820 appendChars(source.charBuffer.subSequence(start, start + len));
1821 beta[to] = len;
1822 break;
1823 }
1824 case Type.TEXT: {
1825 int start = source.alpha[from];
1826 int len = source.beta[from];
1827 nameCode[to] = -1;
1828 alpha[to] = charBuffer.length();
1829 appendChars(source.charBuffer.subSequence(start, start + len));
1830 beta[to] = len;
1831 break;
1832 }
1833 case Type.WHITESPACE_TEXT: {
1834 nameCode[to] = -1;
1835 alpha[to] = source.alpha[from];
1836 beta[to] = source.beta[from];
1837 break;
1838 }
1839 case Type.COMMENT: {
1840 int start = source.alpha[from];
1841 int len = source.beta[from];
1842 nameCode[to] = -1;
1843 CharSequence text = source.commentBuffer.subSequence(start, start + len);
1844 if (commentBuffer == null) {
1845 commentBuffer = new FastStringBuffer(FastStringBuffer.C256);
1846 }
1847 alpha[to] = commentBuffer.length();
1848 commentBuffer.append(text);
1849 beta[to] = len;
1850 break;
1851 }
1852 case Type.PROCESSING_INSTRUCTION:
1853 int start = source.alpha[from];
1854 int len = source.beta[from];
1855 nameCode[to] = source.nameCode[from];
1856 CharSequence text = source.commentBuffer.subSequence(start, start + len);
1857 if (commentBuffer == null) {
1858 commentBuffer = new FastStringBuffer(FastStringBuffer.C256);
1859 }
1860 alpha[to] = commentBuffer.length();
1861 commentBuffer.append(text);
1862 beta[to] = len;
1863 break;
1864
1865 case Type.PARENT_POINTER:
1866 nameCode[to] = -1;
1867 alpha[to] = source.alpha[from] + (to - from);
1868 beta[to] = -1;
1869 break;
1870 default:
1871 break;
1872 }
1873 }
1874 numberOfNodes += length;
1875 }
1876
1877 /**
1878 * Get the in-scope namespaces for a given node on a supplied tree. This is designed to work on
1879 * a tree that is under construction, so normal navigation using the parent axis is not possible.
1880 * See bug 4273.
1881 *
1882 * @param tree the tree
1883 * @param nodeNr the starting element node
1884 * @return a map containing the in-scope namespaces
1885 */
1886
1887 private static Map<String, String> inScopeNamespaces(TinyTree tree, int nodeNr, int[] prevAtDepth, int currentDepth) {
1888 assert tree.nodeKind[nodeNr] == Type.ELEMENT;
1889 Map<String, String> result = new HashMap<>();
1890 int depth = currentDepth - 1;
1891 while (depth >= 0) {
1892 int parent = prevAtDepth[depth];
1893 if (parent >= 0 && tree.nodeKind[parent] == Type.ELEMENT) {
1894 int ns = tree.beta[parent];
1895 if (ns >= 0) {
1896 while (ns < tree.numberOfNamespaces && tree.namespaceParent[ns] == parent) {
1897 NamespaceBinding sourceNs = tree.namespaceBinding[ns];
1898 String prefix = sourceNs.getPrefix();
1899 result.computeIfAbsent(prefix, k -> sourceNs.getURI());
1900 ns++;
1901 }
1902 }
1903 }
1904 depth--;
1905 }
1906 return result;
1907 }
1908 /**
1909 * Graft an element node from an external tree
1910 */
1911
1912 public void graft(NodeInfo externalNode, int nodeNr, int depth, boolean copyNamespaces) {
1913 assert externalNode.getNodeKind() == Type.ELEMENT;
1914 if (externalNodes == null) {
1915 externalNodes = new ArrayList<>();
1916 }
1917 int externalNodeNr = externalNodes.size();
1918 int fp = getNamePool().allocateFingerprint(externalNode.getURI(), externalNode.getLocalPart());
1919 int prefixCode = prefixPool.obtainPrefixCode(externalNode.getPrefix());
1920 int nameCode = (prefixCode << 20) | fp;
1921 addNode(Type.EXTERNAL_NODE_REFERENCE, depth, externalNodeNr, -1, nameCode);
1922 externalNodes.add(new GraftedElement(this, nodeNr, externalNode, copyNamespaces));
1923
1924 }
1925
1926 /**
1927 * Ask if the tree contains grafted subtrees
1928 * @return true if there are references to subtrees of other trees
1929 */
1930
1931 public boolean containsGraftedSubtrees() {
1932 return externalNodes != null;
1933 }
1934
1935 }
1936