Debian Codegraph @

net/sf/saxon/tree/linked/LinkedTreeBuilder.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.event.*;
11 import net.sf.saxon.expr.parser.ExplicitLocation;
12 import net.sf.saxon.expr.parser.Location;
13 import net.sf.saxon.lib.NamespaceConstant;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.util.AttributeCollectionImpl;
17 import net.sf.saxon.type.SchemaType;
18 import net.sf.saxon.type.SimpleType;
19 import net.sf.saxon.value.Whitespace;
20
21 import java.util.ArrayList;
22 import java.util.Arrays;
23
24
25 /**
26 * The LinkedTreeBuilder class is responsible for taking a stream of Receiver events and constructing
27 * a Document tree using the linked tree implementation.
28 *
29 * @author Michael H. Kay
30 */
31
32 public class LinkedTreeBuilder extends Builder
33
34 {
35 // private static AttributeCollectionImpl emptyAttributeCollection =
36 // new AttributeCollectionImpl((Configuration)null);
37
38 /*@Nullable*/ private ParentNodeImpl currentNode;
39 private boolean contentStarted = false; // provides a minimal check on correct sequence of calls
40 private NodeFactory nodeFactory;
41 /*@NotNull*/ private int[] size = new int[100]; // stack of number of children for each open node
42 private int depth = 0;
43 private ArrayList<NodeImpl[]> arrays = new ArrayList<NodeImpl[]>(20); // reusable arrays for creating nodes
44 private NodeName elementNodeName;
45 private SchemaType elementType;
46 private boolean isNilled;
47 private boolean isTopWithinEntity;
48 private Location pendingLocation;
49 /*@Nullable*/ private AttributeCollectionImpl attributes;
50 private NamespaceBinding[] namespaces;
51 private int namespacesUsed;
52 private boolean allocateSequenceNumbers = true;
53 private int nextNodeNumber = 1;
54 private static final NamespaceBinding[] EMPTY_NAMESPACE_LIST = new NamespaceBinding[0];
55
56 /**
57 * Create a Builder and initialise variables
58 *
59 * @param pipe the pipeline configuration
60 */
61
62 public LinkedTreeBuilder(PipelineConfiguration pipe) {
63 super(pipe);
64 nodeFactory = DefaultNodeFactory.THE_INSTANCE;
65 // System.err.println("new TreeBuilder " + this);
66 }
67
68 /**
69 * Get the current root node. This will normally be a document node, but if the root of the tree
70 * is an element node, it can be an element.
71 *
72 * @return the root of the tree that is currently being built, or that has been most recently built
73 * using this builder
74 */
75
76 /*@Nullable*/
77 public NodeInfo getCurrentRoot() {
78 NodeInfo physicalRoot = currentRoot;
79 if (physicalRoot instanceof DocumentImpl && ((DocumentImpl) physicalRoot).isImaginary()) {
80 return ((DocumentImpl) physicalRoot).getDocumentElement();
81 } else {
82 return physicalRoot;
83 }
84 }
85
86 public void reset() {
87 super.reset();
88 currentNode = null;
89 nodeFactory = DefaultNodeFactory.THE_INSTANCE;
90 depth = 0;
91 allocateSequenceNumbers = true;
92 nextNodeNumber = 1;
93 }
94
95 /**
96 * Set whether the builder should allocate sequence numbers to elements as they are added to the
97 * tree. This is normally done, because it provides a quick way of comparing document order. But
98 * nodes added using XQuery update are not sequence-numbered.
99 *
100 * @param allocate true if sequence numbers are to be allocated
101 */
102
103 public void setAllocateSequenceNumbers(boolean allocate) {
104 allocateSequenceNumbers = allocate;
105 }
106
107 /**
108 * Set the Node Factory to use. If none is specified, the Builder uses its own.
109 *
110 * @param factory the node factory to be used. This allows custom objects to be used to represent
111 * the elements in the tree.
112 */
113
114 public void setNodeFactory(NodeFactory factory) {
115 nodeFactory = factory;
116 }
117
118 /**
119 * Open the stream of Receiver events
120 */
121
122 public void open() {
123 started = true;
124 depth = 0;
125 size[depth] = 0;
126 if (arrays == null) {
127 arrays = new ArrayList<NodeImpl[]>(20);
128 }
129 super.open();
130 }
131
132
133 /**
134 * Start of a document node.
135 * This event is ignored: we simply add the contained elements to the current document
136 */
137
138 public void startDocument(int properties) throws XPathException {
139 DocumentImpl doc = new DocumentImpl();
140 currentRoot = doc;
141 doc.setSystemId(getSystemId());
142 doc.setBaseURI(getBaseURI());
143 doc.setConfiguration(config);
144 currentNode = doc;
145 depth = 0;
146 size[depth] = 0;
147 if (arrays == null) {
148 arrays = new ArrayList<NodeImpl[]>(20);
149 }
150 doc.setRawSequenceNumber(0);
151 if (lineNumbering) {
152 doc.setLineNumbering();
153 }
154 contentStarted = true;
155 }
156
157 /**
158 * Notify the end of the document
159 */
160
161 public void endDocument() throws XPathException {
162 //System.err.println("End document depth=" + depth);
163 currentNode.compact(size[depth]);
164 }
165
166 /**
167 * Close the stream of Receiver events
168 */
169
170 public void close() throws XPathException {
171 // System.err.println("TreeBuilder: " + this + " End document");
172 if (currentNode == null) {
173 return; // can be called twice on an error path
174 }
175 currentNode.compact(size[depth]);
176 currentNode = null;
177
178 // we're not going to use this Builder again so give the garbage collector
179 // something to play with
180 arrays = null;
181
182 super.close();
183 nodeFactory = DefaultNodeFactory.THE_INSTANCE;
184 }
185
186 /**
187 * Notify the start of an element
188 */
189
190 public void startElement(NodeName nodeName, SchemaType type, Location location, int properties) throws XPathException {
191 //System.err.println("LinkedTreeBuilder: " + this + " Start element depth=" + depth);
192 if (currentNode == null) {
193 startDocument(0);
194 ((DocumentImpl) currentRoot).setImaginary(true);
195 }
196 elementNodeName = nodeName;
197 elementType = type;
198 isNilled = (properties & ReceiverOptions.NILLED_ELEMENT) != 0;
199 pendingLocation = location;
200 namespacesUsed = 0;
201 attributes = null;
202 contentStarted = false;
203 isTopWithinEntity = location instanceof ReceivingContentHandler.LocalLocator &&
204 ((ReceivingContentHandler.LocalLocator) location).levelInEntity == 0;
205 }
206
207 public void namespace(NamespaceBindingSet namespaceBindings, int properties) {
208 if (contentStarted) {
209 throw new IllegalStateException("namespace() called after startContent()");
210 }
211 if (namespaces == null) {
212 namespaces = new NamespaceBinding[5];
213 }
214 for (NamespaceBinding ns : namespaceBindings) {
215 if (namespacesUsed == namespaces.length) {
216 namespaces = Arrays.copyOf(namespaces, namespaces.length * 2);
217 }
218 namespaces[namespacesUsed++] = ns;
219 }
220 }
221
222 public void attribute(NodeName attName, SimpleType typeCode, /*@NotNull*/ CharSequence value, Location locationId, int properties)
223 throws XPathException {
224 properties &= ~ReceiverOptions.DISABLE_ESCAPING;
225 if (contentStarted) {
226 throw new IllegalStateException("attribute() called after startContent()");
227 }
228 if (attributes == null) {
229 attributes = new AttributeCollectionImpl(config);
230 }
231 if (attName.hasURI(NamespaceConstant.XML) && attName.getLocalPart().equals("id")) {
232 value = Whitespace.trim(value);
233 }
234 attributes.addAttribute(attName, typeCode, value.toString(), locationId, properties);
235 }
236
237 public void startContent() throws XPathException {
238 // System.err.println("TreeBuilder: " + this + " startContent()");
239 if (contentStarted) {
240 throw new IllegalStateException("startContent() called more than once");
241 }
242 contentStarted = true;
243 if (attributes == null) {
244 attributes = AttributeCollectionImpl.EMPTY_ATTRIBUTE_COLLECTION;
245 } else {
246 attributes.compact();
247 }
248
249 NamespaceBinding[] nslist = namespaces;
250 if (nslist == null || namespacesUsed == 0) {
251 nslist = EMPTY_NAMESPACE_LIST;
252 }
253
254 ElementImpl elem = nodeFactory.makeElementNode(
255 currentNode, elementNodeName, elementType, isNilled,
256 attributes, nslist, namespacesUsed,
257 pipe,
258 pendingLocation, allocateSequenceNumbers ? nextNodeNumber++ : -1);
259
260 namespacesUsed = 0;
261 attributes = null;
262
263 // the initial array used for pointing to children will be discarded when the exact number
264 // of children in known. Therefore, it can be reused. So we allocate an initial array from
265 // a pool of reusable arrays. A nesting depth of >20 is so rare that we don't bother.
266
267 while (depth >= arrays.size()) {
268 arrays.add(new NodeImpl[20]);
269 }
270 elem.setChildren(arrays.get(depth));
271
272 currentNode.addChild(elem, size[depth]++);
273 if (depth >= size.length - 1) {
274 size = Arrays.copyOf(size, size.length * 2);
275 }
276 size[++depth] = 0;
277 namespacesUsed = 0;
278
279 if (currentNode instanceof TreeInfo) {
280 ((DocumentImpl) currentNode).setDocumentElement(elem);
281 }
282
283 if (isTopWithinEntity) {
284 currentNode.getPhysicalRoot().markTopWithinEntity(elem);
285 }
286
287 currentNode = elem;
288 }
289
290 /**
291 * Notify the end of an element
292 */
293
294 public void endElement() throws XPathException {
295 //System.err.println("End element depth=" + depth);
296 if (!contentStarted) {
297 throw new IllegalStateException("missing call on startContent()");
298 }
299 currentNode.compact(size[depth]);
300 depth--;
301 currentNode = (ParentNodeImpl) currentNode.getParent();
302 }
303
304 /**
305 * Notify a text node. Adjacent text nodes must have already been merged
306 */
307
308 public void characters(/*@NotNull*/ CharSequence chars, Location locationId, int properties) throws XPathException {
309 // System.err.println("Characters: " + chars.toString() + " depth=" + depth);
310 if (!contentStarted) {
311 throw new IllegalStateException("missing call on startContent()");
312 }
313 if (chars.length() > 0) {
314 NodeInfo prev = currentNode.getNthChild(size[depth] - 1);
315 if (prev instanceof TextImpl) {
316 ((TextImpl) prev).appendStringValue(chars.toString());
317 } else {
318 TextImpl n = nodeFactory.makeTextNode(currentNode, chars);
319 //TextImpl n = new TextImpl(chars.toString());
320 currentNode.addChild(n, size[depth]++);
321 }
322 }
323 }
324
325 /**
326 * Notify a processing instruction
327 */
328
329 public void processingInstruction(String name, /*@NotNull*/ CharSequence remainder, Location locationId, int properties) {
330 if (!contentStarted) {
331 throw new IllegalStateException("missing call on startContent()");
332 }
333 ProcInstImpl pi = new ProcInstImpl(name, remainder.toString());
334 currentNode.addChild(pi, size[depth]++);
335 pi.setLocation(locationId.getSystemId(), locationId.getLineNumber(), locationId.getColumnNumber());
336 }
337
338 /**
339 * Notify a comment
340 */
341
342 public void comment(/*@NotNull*/ CharSequence chars, Location locationId, int properties) throws XPathException {
343 if (!contentStarted) {
344 throw new IllegalStateException("missing call on startContent()");
345 }
346 CommentImpl comment = new CommentImpl(chars.toString());
347 currentNode.addChild(comment, size[depth]++);
348 comment.setLocation(locationId.getSystemId(), locationId.getLineNumber(), locationId.getColumnNumber());
349 }
350
351 /**
352 * Get the current document or element node
353 *
354 * @return the most recently started document or element node (to which children are currently being added)
355 * In the case of elements, this is only available after startContent() has been called
356 */
357
358 /*@Nullable*/
359 public ParentNodeImpl getCurrentParentNode() {
360 return currentNode;
361 }
362
363 /**
364 * Get the current text, comment, or processing instruction node
365 *
366 * @return if any text, comment, or processing instruction nodes have been added to the current parent
367 * node, then return that text, comment, or PI; otherwise return null
368 */
369
370 /*@NotNull*/
371 public NodeImpl getCurrentLeafNode() {
372 return currentNode.getLastChild();
373 }
374
375
376 /**
377 * graftElement() allows an element node to be transferred from one tree to another.
378 * This is a dangerous internal interface which is used only to contruct a stylesheet
379 * tree from a stylesheet using the "literal result element as stylesheet" syntax.
380 * The supplied element is grafted onto the current element as its only child.
381 *
382 * @param element the element to be grafted in as a new child.
383 */
384
385 public void graftElement(ElementImpl element) {
386 currentNode.addChild(element, size[depth]++);
387 }
388
389 /**
390 * Set an unparsed entity URI for the document
391 */
392
393 public void setUnparsedEntity(String name, String uri, String publicId) {
394 if (((DocumentImpl) currentRoot).getUnparsedEntity(name) == null) {
395 // bug 2187
396 ((DocumentImpl) currentRoot).setUnparsedEntity(name, uri, publicId);
397 }
398 }
399
400 /**
401 * Get a builder monitor for this builder. This must be called immediately after opening the builder,
402 * and all events to the builder must thenceforth be sent via the BuilderMonitor.
403 *
404 * @return a new BuilderMonitor appropriate to this kind of Builder; or null if the Builder does
405 * not provide this service
406 */
407
408 /*@NotNull*/
409 public BuilderMonitor getBuilderMonitor() {
410 return new LinkedBuilderMonitor(this);
411 }
412
413 //////////////////////////////////////////////////////////////////////////////
414 // Inner class DefaultNodeFactory. This creates the nodes in the tree.
415 // It can be overridden, e.g. when building the stylesheet tree
416 //////////////////////////////////////////////////////////////////////////////
417
418 private static class DefaultNodeFactory implements NodeFactory {
419
420 public static DefaultNodeFactory THE_INSTANCE = new DefaultNodeFactory();
421
422 /*@NotNull*/
423 public ElementImpl makeElementNode(
424 /*@NotNull*/ NodeInfo parent,
425 /*@NotNull*/ NodeName nodeName,
426 SchemaType elementType,
427 boolean isNilled,
428 AttributeCollectionImpl attlist,
429 NamespaceBinding[] namespaces,
430 int namespacesUsed,
431 /*@NotNull*/ PipelineConfiguration pipe,
432 Location locationId,
433 int sequenceNumber)
434
435 {
436 ElementImpl e = new ElementImpl();
437 if (namespacesUsed > 0) {
438 e.setNamespaceDeclarations(namespaces, namespacesUsed);
439 }
440
441 e.initialise(nodeName, elementType, attlist, parent, sequenceNumber);
442 if (isNilled) {
443 e.setNilled();
444 }
445 if (locationId != ExplicitLocation.UNKNOWN_LOCATION && sequenceNumber >= 0) {
446 String baseURI = locationId.getSystemId();
447 int lineNumber = locationId.getLineNumber();
448 int columnNumber = locationId.getColumnNumber();
449 e.setLocation(baseURI, lineNumber, columnNumber);
450 }
451 return e;
452 }
453
454 /**
455 * Make a text node
456 *
457 * @param parent the parent element
458 * @param content the content of the text node
459 * @return the constructed text node
460 */
461 public TextImpl makeTextNode(NodeInfo parent, CharSequence content) {
462 return new TextImpl(content.toString());
463 }
464 }
465
466
467 }
468