Debian Codegraph @

net/sf/saxon/tree/linked/DocumentImpl.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.linked;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.Builder;
12 import net.sf.saxon.event.Receiver;
13 import net.sf.saxon.expr.parser.Location;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.iter.AxisIterator;
17 import net.sf.saxon.tree.iter.ListIterator;
18 import net.sf.saxon.tree.util.AttributeCollectionImpl;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20 import net.sf.saxon.type.AnyType;
21 import net.sf.saxon.type.SchemaType;
22 import net.sf.saxon.type.Type;
23 import net.sf.saxon.type.Untyped;
24 import net.sf.saxon.value.Whitespace;
25 import net.sf.saxon.z.IntHashMap;
26
27 import java.util.*;
28
29
30 /**
31 * A node in the XML parse tree representing the Document itself (or equivalently, the root
32 * node of the Document).
33 * <p>A DocumentImpl object may either represent a real document node, or it may represent an imaginary
34 * container for a parentless element.</p>
35 *
36 * @author Michael H. Kay
37 */
38
39 public final class DocumentImpl extends ParentNodeImpl implements TreeInfo, MutableDocumentInfo {
40
41 //private static int nextDocumentNumber = 0;
42
43 private ElementImpl documentElement;
44
45
46 /*@Nullable*/ private HashMap<String, NodeInfo> idTable;
47 private long documentNumber;
48 private String baseURI;
49 private HashMap<String, String[]> entityTable;
50 private Set<ElementImpl> nilledElements;
51 private Set<ElementImpl> topWithinEntityElements;
52 private IntHashMap<List<NodeInfo>> elementList;
53 private HashMap<String, Object> userData;
54 private Configuration config;
55 private LineNumberMap lineNumberMap;
56 private SystemIdMap systemIdMap = new SystemIdMap();
57 private boolean imaginary;
58 private SpaceStrippingRule spaceStrippingRule = NoElementsSpaceStrippingRule.getInstance();
59
60
61 /**
62 * Create a DocumentImpl
63 */
64
65 public DocumentImpl() {
66 setRawParent(null);
67 }
68
69 /**
70 * Get the NodeInfo object representing the document node at the root of the tree
71 *
72 * @return the document node
73 */
74
75 public NodeInfo getRootNode() {
76 return this;
77 }
78
79 /**
80 * Set the Configuration that contains this document
81 *
82 * @param config the Saxon configuration
83 */
84
85 public void setConfiguration(/*@NotNull*/ Configuration config) {
86 this.config = config;
87 documentNumber = config.getDocumentNumberAllocator().allocateDocumentNumber();
88 }
89
90 /**
91 * Get the configuration previously set using setConfiguration
92 *
93 * @return the Saxon configuration
94 */
95
96 public Configuration getConfiguration() {
97 return config;
98 }
99
100 /**
101 * Get the name pool used for the names in this document
102 */
103
104 public NamePool getNamePool() {
105 return config.getNamePool();
106 }
107
108 /**
109 * Get a Builder suitable for building nodes that can be attached to this document.
110 *
111 * @return a new TreeBuilder
112 */
113
114 /*@NotNull*/
115 public Builder newBuilder() {
116 LinkedTreeBuilder builder = new LinkedTreeBuilder(config.makePipelineConfiguration());
117 builder.setAllocateSequenceNumbers(false);
118 return builder;
119 }
120
121 /**
122 * Set whether this is an imaginary document node
123 *
124 * @param imaginary if true, this is an imaginary node - the tree is really rooted at the topmost element
125 */
126
127 public void setImaginary(boolean imaginary) {
128 this.imaginary = imaginary;
129 }
130
131 /**
132 * Ask whether this is an imaginary document node
133 *
134 * @return true if this is an imaginary node - the tree is really rooted at the topmost element
135 */
136
137 public boolean isImaginary() {
138 return imaginary;
139 }
140
141 /**
142 * Ask whether the document contains any nodes whose type annotation is anything other than
143 * UNTYPED
144 *
145 * @return true if the document contains elements whose type is other than UNTYPED
146 */
147 public boolean isTyped() {
148 return documentElement != null && documentElement.getSchemaType() != Untyped.getInstance();
149 }
150
151 /**
152 * Get the unique document number
153 */
154
155 public long getDocumentNumber() {
156 return documentNumber;
157 }
158
159 /**
160 * Set the top-level element of the document (variously called the root element or the
161 * document element). Note that a DocumentImpl may represent the root of a result tree
162 * fragment, in which case there is no document element.
163 *
164 * @param e the top-level element
165 */
166
167 public void setDocumentElement(ElementImpl e) {
168 documentElement = e;
169 }
170
171 /**
172 * Copy the system ID and line number map from another document
173 * (used when grafting a simplified stylesheet)
174 *
175 * @param original the document whose system ID and line number maps are to be grafted
176 * onto this tree
177 */
178
179 public void graftLocationMap(/*@NotNull*/ DocumentImpl original) {
180 systemIdMap = original.systemIdMap;
181 lineNumberMap = original.lineNumberMap;
182 }
183
184 /**
185 * Set the system id (base URI) of this node
186 */
187
188 public void setSystemId(String /*@Nullable*/uri) {
189 if (uri == null) {
190 uri = "";
191 }
192 systemIdMap.setSystemId(getRawSequenceNumber(), uri);
193 }
194
195 /**
196 * Get the system id of this root node
197 */
198
199 public String getSystemId() {
200 return systemIdMap.getSystemId(getRawSequenceNumber());
201 }
202
203 /**
204 * Set the base URI of this document node
205 *
206 * @param uri the new base URI
207 */
208
209 public void setBaseURI(String uri) {
210 baseURI = uri;
211 }
212
213 /**
214 * Get the base URI of this root node.
215 *
216 * @return the base URI
217 */
218
219 public String getBaseURI() {
220 if (baseURI != null) {
221 return baseURI;
222 }
223 return getSystemId();
224 }
225
226
227 /**
228 * Set the system id of an element in the document
229 *
230 * @param seq the sequence number of the element
231 * @param uri the system identifier (base URI) of the element
232 */
233
234 void setSystemId(int seq, String /*@Nullable*/uri) {
235 if (uri == null) {
236 uri = "";
237 }
238 systemIdMap.setSystemId(seq, uri);
239 }
240
241
242 /**
243 * Get the system id of an element in the document
244 *
245 * @param seq the sequence number of the element
246 * @return the systemId (base URI) of the element
247 */
248
249 String getSystemId(int seq) {
250 return systemIdMap.getSystemId(seq);
251 }
252
253
254 /**
255 * Set line numbering on
256 */
257
258 public void setLineNumbering() {
259 lineNumberMap = new LineNumberMap();
260 lineNumberMap.setLineAndColumn(getRawSequenceNumber(), 0, -1);
261 }
262
263 /**
264 * Set the line number for an element. Ignored if line numbering is off.
265 *
266 * @param sequence the sequence number of the element
267 * @param line the line number of the element
268 * @param column the column number of the element
269 */
270
271 void setLineAndColumn(int sequence, int line, int column) {
272 if (lineNumberMap != null && sequence >= 0) {
273 lineNumberMap.setLineAndColumn(sequence, line, column);
274 }
275 }
276
277 /**
278 * Get the line number for an element.
279 *
280 * @param sequence the sequence number of the element
281 * @return the line number for an element. Return -1 if line numbering is off, or if
282 * the element was added subsequent to document creation by use of XQuery update
283 */
284
285 int getLineNumber(int sequence) {
286 if (lineNumberMap != null && sequence >= 0) {
287 return lineNumberMap.getLineNumber(sequence);
288 }
289 return -1;
290 }
291
292 /**
293 * Get the column number for an element.
294 *
295 * @param sequence the sequence number of the element
296 * @return the column number for an element. Return -1 if line numbering is off, or if
297 * the element was added subsequent to document creation by use of XQuery update
298 */
299
300 int getColumnNumber(int sequence) {
301 if (lineNumberMap != null && sequence >= 0) {
302 return lineNumberMap.getColumnNumber(sequence);
303 }
304 return -1;
305 }
306
307 /**
308 * Add a nilled element. Nilled elements are unusual, so we avoid allocating a boolean in the element node;
309 * instead we keep a list of nilled elements at the document level
310 * @param element a nilled element
311 */
312
313 public void addNilledElement(ElementImpl element) {
314 if (nilledElements == null) {
315 nilledElements = new HashSet<>();
316 }
317 nilledElements.add(element);
318 }
319
320 /**
321 * Ask if a given element is nilled
322 * @param element the element about which we want to ask
323 * @return true if the element is in the list of nilled elements
324 */
325
326 boolean isNilledElement(ElementImpl element) {
327 return nilledElements != null && nilledElements.contains(element);
328 }
329
330 public void markTopWithinEntity(ElementImpl element) {
331 if (topWithinEntityElements == null) {
332 topWithinEntityElements = new HashSet<>();
333 }
334 topWithinEntityElements.add(element);
335 }
336
337 public boolean isTopWithinEntity(ElementImpl element) {
338 return topWithinEntityElements != null && topWithinEntityElements.contains(element);
339 }
340
341 /**
342 * Get the line number of this root node.
343 *
344 * @return 0 always
345 */
346
347 public int getLineNumber() {
348 return 0;
349 }
350
351 /**
352 * Return the type of node.
353 *
354 * @return Type.DOCUMENT (always)
355 */
356
357 public final int getNodeKind() {
358 return Type.DOCUMENT;
359 }
360
361 /**
362 * Get next sibling - always null
363 *
364 * @return null
365 */
366
367
368 public /*@Nullable*/ final NodeImpl getNextSibling() {
369 return null;
370 }
371
372 /**
373 * Get previous sibling - always null
374 *
375 * @return null
376 */
377
378 /*@Nullable*/
379 public final NodeImpl getPreviousSibling() {
380 return null;
381 }
382
383 /**
384 * Get the root (outermost) element.
385 *
386 * @return the Element node for the outermost element of the document.
387 * May return null if the document node contains no element node.
388 */
389
390 public ElementImpl getDocumentElement() {
391 return documentElement;
392 }
393
394 /**
395 * Get the root node
396 *
397 * @return the NodeInfo representing the root of this tree
398 */
399
400 /*@NotNull*/
401 public NodeInfo getRoot() {
402 return this;
403 }
404
405 /**
406 * Get the physical root of the tree. This may be an imaginary document node: this method
407 * should be used only when control information held at the physical root is required
408 *
409 * @return the document node, which may be imaginary
410 */
411
412 /*@NotNull*/
413 public DocumentImpl getPhysicalRoot() {
414 return this;
415 }
416
417 /**
418 * Get a character string that uniquely identifies this node
419 *
420 * @param buffer a buffer into which will be placed a string based on the document number
421 */
422
423 public void generateId(/*@NotNull*/ FastStringBuffer buffer) {
424 buffer.append('d');
425 buffer.append(Long.toString(documentNumber));
426 }
427
428 /**
429 * Get a list of all elements with a given name fingerprint
430 *
431 * @param fingerprint the fingerprint of the required element name
432 * @return an iterator over all the elements with this name
433 */
434
435 /*@NotNull*/
436 AxisIterator getAllElements(int fingerprint) {
437 if (elementList == null) {
438 elementList = new IntHashMap<>(500);
439 }
440 IntHashMap<List<NodeInfo>> eList = elementList;
441 List<NodeInfo> list = eList.get(fingerprint);
442 if (list == null) {
443 list = new ArrayList<>(500);
444 NodeImpl next = getNextInDocument(this);
445 while (next != null) {
446 if (next.getNodeKind() == Type.ELEMENT &&
447 next.getFingerprint() == fingerprint) {
448 list.add(next);
449 }
450 next = next.getNextInDocument(this);
451 }
452 eList.put(fingerprint, list);
453 }
454 return new ListIterator.OfNodes(list);
455 }
456
457 /**
458 * Remove a node from any indexes when it is detached from the tree
459 *
460 * @param node the node to be removed from all indexes
461 */
462
463 public void deIndex(/*@NotNull*/ NodeImpl node) {
464 if (node instanceof ElementImpl) {
465 IntHashMap<List<NodeInfo>> eList = elementList;
466 if (eList != null) {
467 List<NodeInfo> list = eList.get(node.getFingerprint());
468 if (list == null) {
469 return;
470 }
471 list.remove(node);
472 }
473 if (node.isId()) {
474 deregisterID(node.getStringValue());
475 }
476 } else if (node instanceof AttributeImpl) {
477 if (node.isId()) {
478 deregisterID(node.getStringValue());
479 }
480 }
481 }
482
483 /**
484 * Index all the ID attributes. This is done the first time the id() function
485 * is used on this document, or the first time that id() is called after a sequence of updates
486 */
487
488 private void indexIDs() {
489 if (idTable != null) {
490 return; // ID's are already indexed
491 }
492 idTable = new HashMap<>(256);
493
494 NodeImpl curr = this;
495 NodeImpl root = curr;
496 while (curr != null) {
497 if (curr.getNodeKind() == Type.ELEMENT) {
498 //noinspection ConstantConditions
499 ElementImpl e = (ElementImpl) curr;
500 if (e.isId()) {
501 registerID(e, Whitespace.trim(e.getStringValueCS()));
502 }
503 AttributeCollectionImpl atts = (AttributeCollectionImpl) e.getAttributeList();
504 for (int i = 0; i < atts.getLength(); i++) {
505 if (!atts.isDeleted(i) && atts.isId(i) && NameChecker.isValidNCName(Whitespace.trim(atts.getValue(i)))) {
506 // don't index any invalid IDs - these can arise when using a non-validating parser
507 registerID(e, Whitespace.trim(atts.getValue(i)));
508 }
509 }
510 }
511 curr = curr.getNextInDocument(root);
512 }
513 }
514
515 /**
516 * Register a unique element ID. Does nothing if there is already an element with that ID.
517 *
518 * @param e The Element having a particular unique ID value
519 * @param id The unique ID value
520 */
521
522 protected void registerID(NodeInfo e, String id) {
523 // the XPath spec (5.2.1) says ignore the second ID if it's not unique
524 if (idTable == null) {
525 idTable = new HashMap<>(256);
526 }
527 HashMap<String, NodeInfo> table = idTable;
528 table.putIfAbsent(id, e);
529 }
530
531 /**
532 * Get the element with a given ID.
533 *
534 * @param id The unique ID of the required element, previously registered using registerID()
535 * @param getParent true if the requirement is for the parent of the node with the given ID,
536 * not the node itself.
537 * @return The NodeInfo for the given ID if one has been registered, otherwise null.
538 */
539
540
541 public NodeInfo/*@Nullable*/ selectID(String id, boolean getParent) {
542 if (idTable == null) {
543 indexIDs();
544 }
545 assert idTable != null;
546 NodeInfo node = idTable.get(id);
547 if (node != null && getParent && node.isId() && node.getStringValue().equals(id)) {
548 node = node.getParent();
549 }
550 return node;
551 }
552
553 /**
554 * Remove the entry for a given ID (when nodes are deleted). Does nothing if the id value is not
555 * present in the index.
556 *
557 * @param id The id value
558 */
559
560 protected void deregisterID(String id) {
561 id = Whitespace.trim(id);
562 if (idTable != null) {
563 idTable.remove(id);
564 }
565 }
566
567 /**
568 * Set an unparsed entity URI associated with this document. For system use only, while
569 * building the document.
570 *
571 * @param name the entity name
572 * @param uri the system identifier of the unparsed entity
573 * @param publicId the public identifier of the unparsed entity
574 */
575
576 public void setUnparsedEntity(String name, String uri, String publicId) {
577 // System.err.println("setUnparsedEntity( " + name + "," + uri + ")");
578 if (entityTable == null) {
579 entityTable = new HashMap<>(10);
580 }
581 String[] ids = new String[2];
582 ids[0] = uri;
583 ids[1] = publicId;
584 entityTable.put(name, ids);
585 }
586
587 /**
588 * Get the list of unparsed entities defined in this document
589 *
590 * @return an Iterator, whose items are of type String, containing the names of all
591 * unparsed entities defined in this document. If there are no unparsed entities or if the
592 * information is not available then an empty iterator is returned
593 */
594
595 public Iterator<String> getUnparsedEntityNames() {
596 if (entityTable == null) {
597 List<String> ls = Collections.emptyList();
598 return ls.iterator();
599 } else {
600 return entityTable.keySet().iterator();
601 }
602 }
603
604 /**
605 * Get the unparsed entity with a given name
606 *
607 * @param name the name of the entity
608 * @return if the entity exists, return an array of two Strings, the first holding the system ID
609 * of the entity, the second holding the public ID if there is one, or null if not. If the entity
610 * does not exist, return null.
611 */
612
613 /*@Nullable*/
614 public String[] getUnparsedEntity(String name) {
615 if (entityTable == null) {
616 return null;
617 }
618 return entityTable.get(name);
619 }
620
621 /**
622 * Get the type annotation
623 *
624 * @return the type annotation of the base node
625 */
626
627 public SchemaType getSchemaType() {
628 if (documentElement == null || documentElement.getSchemaType() == Untyped.getInstance()) {
629 return Untyped.getInstance();
630 } else {
631 return AnyType.getInstance();
632 }
633 }
634
635 /**
636 * Copy this node to a given outputter
637 */
638
639 public void copy(/*@NotNull*/ Receiver out, int copyOptions, Location locationId) throws XPathException {
640 out.startDocument(CopyOptions.getStartDocumentProperties(copyOptions));
641
642 // copy any unparsed entities
643
644 for (Iterator<String> names = getUnparsedEntityNames(); names.hasNext(); ) {
645 String name = names.next();
646 String[] details = getUnparsedEntity(name);
647 assert details != null;
648 out.setUnparsedEntity(name, details[0], details[1]);
649 }
650
651 // copy the children
652
653 NodeImpl next = getFirstChild();
654 while (next != null) {
655 next.copy(out, copyOptions, locationId);
656 next = next.getNextSibling();
657 }
658
659 out.endDocument();
660 }
661
662
663 /**
664 * Replace the string-value of this node
665 *
666 * @param stringValue the new string value
667 */
668
669 public void replaceStringValue(CharSequence stringValue) {
670 throw new UnsupportedOperationException("Cannot replace the value of a document node");
671 }
672
673 /**
674 * This method is called before performing a batch of updates; it allows all cached data that
675 * might be invalidated by such updates to be cleared
676 */
677
678 public void resetIndexes() {
679 idTable = null;
680 elementList = null;
681 }
682
683 /**
684 * Set details of space stripping action that was applied to this document during
685 * construction. This ensures that space stripping is not applied twice to the same
686 * document.
687 *
688 * @param rule details of the space stripping rules that have been applied to this
689 * document during its construction.
690 * @since 9.9
691 */
692 public void setSpaceStrippingRule(SpaceStrippingRule rule) {
693 this.spaceStrippingRule = rule;
694 }
695
696 /**
697 * Get details of space stripping action that was applied to this document during
698 * construction. This ensures that space stripping is not applied twice to the same
699 * document.
700 *
701 * @return details of the space stripping rules that have been applied to this
702 * document during its construction. By default, returns {@link NoElementsSpaceStrippingRule},
703 * indicating that no space stripping has been applied
704 * @since 9.9
705 */
706 public SpaceStrippingRule getSpaceStrippingRule() {
707 return spaceStrippingRule;
708 }
709
710 /**
711 * Set user data on the document node. The user data can be retrieved subsequently
712 * using {@link #getUserData}
713 *
714 * @param key A string giving the name of the property to be set. Clients are responsible
715 * for choosing a key that is likely to be unique. Must not be null. Keys used internally
716 * by Saxon are prefixed "saxon:".
717 * @param value The value to be set for the property. May be null, which effectively
718 * removes the existing value for the property.
719 */
720
721 public void setUserData(String key, Object value) {
722 /*@Nullable*/
723 if (userData == null) {
724 userData = new HashMap<>(4);
725 }
726 if (value == null) {
727 userData.remove(key);
728 } else {
729 userData.put(key, value);
730 }
731 }
732
733 /**
734 * Get user data held in the document node. This retrieves properties previously set using
735 * {@link #setUserData}
736 *
737 * @param key A string giving the name of the property to be retrieved.
738 * @return the value of the property, or null if the property has not been defined.
739 */
740
741 /*@Nullable*/
742 public Object getUserData(String key) {
743 if (userData == null) {
744 return null;
745 } else {
746 return userData.get(key);
747 }
748 }
749
750
751 }
752