Debian Codegraph @

net/sf/saxon/tree/tiny/TinyBuilder.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.*;
12 import net.sf.saxon.expr.parser.Location;
13 import net.sf.saxon.lib.Feature;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.util.FastStringBuffer;
17 import net.sf.saxon.type.SchemaType;
18 import net.sf.saxon.type.SimpleType;
19 import net.sf.saxon.type.Type;
20
21 import java.util.Arrays;
22
23
24 /**
25 * The TinyBuilder class is responsible for taking a stream of SAX events and constructing
26 * a Document tree, using the "TinyTree" implementation.
27 *
28 * @author Michael H. Kay
29 */
30
31 public class TinyBuilder extends Builder {
32
33 public static final int PARENT_POINTER_INTERVAL = 10;
34 // a lower value allocates more parent pointers which takes more space but reduces
35 // the length of parent searches
36
37 /*@Nullable*/ private TinyTree tree;
38
39 private int currentDepth = 0;
40 private int nodeNr = 0; // this is the local sequence within this document
41 private boolean ended = false;
42 private Statistics statistics;
43 private boolean markDefaultedAttributes = false;
44 private int textualElementEligibilityState = 0;
45
46 /**
47 * Create a TinyTree builder
48 *
49 * @param pipe information about the pipeline leading up to this Builder
50 */
51
52 public TinyBuilder(/*@NotNull*/ PipelineConfiguration pipe) {
53 super(pipe);
54 Configuration config = pipe.getConfiguration();
55 statistics = config.getTreeStatistics().TEMPORARY_TREE_STATISTICS;
56 //markDefaultedAttributes = true;
57 markDefaultedAttributes = config.isExpandAttributeDefaults() && config.getBooleanProperty(Feature.MARK_DEFAULTED_ATTRIBUTES);
58 //System.err.println("TinyBuilder " + this);
59 }
60
61 /**
62 * Set the size parameters for the tree
63 *
64 * @param stats an object holding the expected number of non-attribute nodes, the expected
65 * number of attributes, the expected number of namespace declarations, and the expected total length of
66 * character data
67 */
68
69 public void setStatistics(Statistics stats) {
70 statistics = stats;
71 }
72
73 /*@NotNull*/ private int[] prevAtDepth = new int[100];
74 // this array is scaffolding used while constructing the tree, it is
75 // not present in the final tree. For each level of the tree, it records the
76 // node number of the most recent node at that level.
77
78 /*@NotNull*/ private int[] siblingsAtDepth = new int[100];
79 // more scaffolding. For each level of the tree, this array records the
80 // number of siblings processed at that level. When this exceeds a threshold value,
81 // a dummy node is inserted into the arrays to contain a parent pointer: this it to
82 // prevent excessively long searches for a parent node, which is normally found by
83 // scanning the siblings. The value is then reset to zero.
84
85 private boolean isIDElement = false;
86
87 /**
88 * Get the tree being built by this builder
89 *
90 * @return the TinyTree
91 */
92
93 /*@Nullable*/
94 public TinyTree getTree() {
95 return tree;
96 }
97
98 /**
99 * Get the current depth in the tree
100 *
101 * @return the current depth
102 */
103
104 public int getCurrentDepth() {
105 return currentDepth;
106 }
107
108 /**
109 * Open the event stream
110 */
111
112 public void open() {
113 //System.err.println("TinyBuilder " + this + " open; " + started);
114 if (started) {
115 // this happens when using an IdentityTransformer
116 return;
117 }
118 if (tree == null) {
119 tree = new TinyTree(config, statistics);
120 currentDepth = 0;
121 if (lineNumbering) {
122 tree.setLineNumbering();
123 }
124 }
125 super.open();
126 }
127
128 /**
129 * Write a document node to the tree
130 */
131
132 public void startDocument(int properties) throws XPathException {
133 if ((started && !ended) || currentDepth > 0) {
134 // this happens when using an IdentityTransformer, or when copying a document node to form
135 // the content of an element
136 return;
137 }
138
139 started = true;
140 ended = false;
141
142 TinyTree tt = tree;
143 assert tt != null;
144 currentRoot = new TinyDocumentImpl(tt);
145 TinyDocumentImpl doc = (TinyDocumentImpl) currentRoot;
146 doc.setSystemId(getSystemId());
147 doc.setBaseURI(getBaseURI());
148
149 currentDepth = 0;
150
151 int nodeNr = tt.addDocumentNode((TinyDocumentImpl) currentRoot);
152 prevAtDepth[0] = nodeNr;
153 prevAtDepth[1] = -1;
154 siblingsAtDepth[0] = 0;
155 siblingsAtDepth[1] = 0;
156 tt.next[nodeNr] = -1;
157
158 currentDepth++;
159 }
160
161 /**
162 * Callback interface for SAX: not for application use
163 */
164
165 public void endDocument() throws XPathException {
166 // System.err.println("TinyBuilder: " + this + " End document");
167
168 // Add a stopper node to ensure no-one walks off the end of the array; but
169 // decrement numberOfNodes so the next node will overwrite it
170 tree.addNode(Type.STOPPER, 0, 0, 0, -1);
171 tree.numberOfNodes--;
172
173 if (currentDepth > 1) {
174 return;
175 }
176 // happens when copying a document node as the child of an element
177
178 if (ended) {
179 return; // happens when using an IdentityTransformer
180 }
181 ended = true;
182
183 prevAtDepth[currentDepth] = -1;
184 currentDepth--;
185
186 }
187
188 public void reset() {
189 super.reset();
190 tree = null;
191 currentDepth = 0;
192 nodeNr = 0;
193 ended = false;
194 statistics = config.getTreeStatistics().TEMPORARY_TREE_STATISTICS;
195 }
196
197 public void close() throws XPathException {
198 TinyTree tt = tree;
199 if (tt != null) {
200 tt.addNode(Type.STOPPER, 0, 0, 0, -1);
201 tt.condense(statistics);
202 }
203 super.close();
204 }
205
206 /**
207 * Notify the start tag of an element
208 */
209
210 public void startElement(/*@NotNull*/ NodeName elemName, SchemaType type, Location location, int properties) throws XPathException {
211
212 // if the number of siblings exceeds a certain threshold, add a parent pointer, in the form
213 // of a pseudo-node
214
215 //System.err.println("startElement " + elemName);
216 TinyTree tt = tree;
217 assert tt != null;
218 textualElementEligibilityState = 0;
219
220 if (siblingsAtDepth[currentDepth] > PARENT_POINTER_INTERVAL) {
221 nodeNr = tt.addNode(Type.PARENT_POINTER, currentDepth, prevAtDepth[currentDepth - 1], 0, 0);
222 int prev = prevAtDepth[currentDepth];
223 if (prev > 0) {
224 tt.next[prev] = nodeNr;
225 }
226 tt.next[nodeNr] = prevAtDepth[currentDepth - 1];
227 prevAtDepth[currentDepth] = nodeNr;
228 siblingsAtDepth[currentDepth] = 0;
229 }
230
231 // now add the element node itself
232 int fp = elemName.obtainFingerprint(namePool);
233 int prefixCode = tree.prefixPool.obtainPrefixCode(elemName.getPrefix());
234 int nameCode = (prefixCode << 20) | fp;
235 nodeNr = tt.addNode(Type.ELEMENT, currentDepth, -1, -1, nameCode);
236
237 isIDElement = (properties & ReceiverOptions.IS_ID) != 0;
238 int typeCode = type.getFingerprint();
239 if (typeCode != StandardNames.XS_UNTYPED) {
240
241 tt.setElementAnnotation(nodeNr, type);
242 if ((properties & ReceiverOptions.NILLED_ELEMENT) != 0) {
243 tt.setNilled(nodeNr);
244 }
245 if (!isIDElement && type.isIdType()) {
246 isIDElement = true;
247 }
248 }
249
250 if (currentDepth == 0) {
251 prevAtDepth[0] = nodeNr;
252 prevAtDepth[1] = -1;
253 //tree.next[0] = -1;
254 currentRoot = tt.getNode(nodeNr);
255 } else {
256 int prev = prevAtDepth[currentDepth];
257 if (prev > 0) {
258 tt.next[prev] = nodeNr;
259 }
260 tt.next[nodeNr] = prevAtDepth[currentDepth - 1]; // *O* owner pointer in last sibling
261 prevAtDepth[currentDepth] = nodeNr;
262 siblingsAtDepth[currentDepth]++;
263 }
264 currentDepth++;
265
266 if (currentDepth == prevAtDepth.length) {
267 prevAtDepth = Arrays.copyOf(prevAtDepth, currentDepth * 2);
268 siblingsAtDepth = Arrays.copyOf(siblingsAtDepth, currentDepth * 2);
269 }
270 prevAtDepth[currentDepth] = -1;
271 siblingsAtDepth[currentDepth] = 0;
272
273 // if (!pipe.isLocationIsCodeLocation() && location.getSystemId() != null) {
274 // tt.setSystemId(nodeNr, location.getSystemId());
275 // } else if (currentDepth == 1) {
276 // tt.setSystemId(nodeNr, systemId);
277 // }
278 if (isUseEventLocation() && location.getSystemId() != null) {
279 tt.setSystemId(nodeNr, location.getSystemId());
280 } else if (currentDepth == 1) {
281 tt.setSystemId(nodeNr, systemId);
282 }
283
284 if (lineNumbering) {
285 tt.setLineNumber(nodeNr, location.getLineNumber(), location.getColumnNumber());
286 }
287 if (location instanceof ReceivingContentHandler.LocalLocator &&
288 ((ReceivingContentHandler.LocalLocator)location).levelInEntity == 0 && currentDepth >= 1) {
289 tt.markTopWithinEntity(nodeNr);
290 }
291 }
292
293 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
294 assert tree != null;
295 for (NamespaceBinding ns : namespaceBindings) {
296 tree.addNamespace(nodeNr, ns);
297 }
298 }
299
300 //private static int counter = 0;
301
302 public void attribute(/*@NotNull*/ NodeName attName, SimpleType type, CharSequence value, Location locationId, int properties)
303 throws XPathException {
304 // System.err.println("attribute " + nameCode + "=" + value);
305 //if (counter++ % 1000 == 0) System.err.println("T.addAttribute# = " + counter);
306 int fp = attName.obtainFingerprint(namePool);
307 String prefix = attName.getPrefix();
308 int nameCode = prefix.isEmpty() ? fp : (tree.prefixPool.obtainPrefixCode(prefix) << 20) | fp;
309 assert tree != null;
310 assert currentRoot != null;
311 tree.addAttribute(currentRoot, nodeNr, nameCode, type, value, properties);
312 if (markDefaultedAttributes && ((properties & ReceiverOptions.DEFAULTED_ATTRIBUTE) != 0)) {
313 tree.markDefaultedAttribute(tree.numberOfAttributes - 1);
314 }
315 }
316
317 public void startContent() {
318 //System.err.println("startContent");
319 nodeNr++;
320 textualElementEligibilityState = 1;
321 }
322
323 /**
324 * Notify the end of an element node
325 */
326
327 public void endElement() throws XPathException {
328 assert tree != null;
329 //System.err.println("End element");
330
331 boolean eligibleAsTextualElement = textualElementEligibilityState == 2;
332 textualElementEligibilityState = 0;
333 prevAtDepth[currentDepth] = -1;
334 siblingsAtDepth[currentDepth] = 0;
335 currentDepth--;
336 if (isIDElement) {
337 // we're relying on the fact that an ID element has no element children!
338 tree.indexIDElement(currentRoot, prevAtDepth[currentDepth]);
339 isIDElement = false;
340 } else if (eligibleAsTextualElement &&
341 tree.nodeKind[nodeNr] == Type.TEXT &&
342 tree.nodeKind[nodeNr-1] == Type.ELEMENT &&
343 tree.alpha[nodeNr-1] == -1 &&
344 tree.beta[nodeNr-1] == -1) {
345 // Collapse a simple element with text content and no attributes or namespaces into a single node
346 // of type TRIVIAL_ELEMENT
347 //System.err.println("Created textual element");
348 tree.nodeKind[nodeNr-1] = Type.TEXTUAL_ELEMENT;
349 tree.alpha[nodeNr-1] = tree.alpha[nodeNr];
350 tree.beta[nodeNr-1] = tree.beta[nodeNr];
351 nodeNr--;
352 tree.numberOfNodes--;
353 if (currentDepth == 0) {
354 currentRoot = tree.getNode(nodeNr);
355 }
356 }
357 }
358
359 /**
360 * Get the last completed element node. This is used during checking of schema assertions,
361 * which happens while the tree is still under construction. It is also used when copying
362 * accumulator values to the new tree from a streamed input. This method is called immediately after
363 * a call on endElement(), and it returns the element that has just ended.
364 *
365 * @return the last completed element node, that is, the element whose endElement event is the most recent
366 * endElement event to be reported, or null if there is no such element
367 */
368
369 public TinyNodeImpl getLastCompletedElement() {
370 if (tree == null) {
371 return null;
372 }
373 return tree.getNode(currentDepth >= 0 ? prevAtDepth[currentDepth] : 0);
374 // Note: reading an incomplete tree needs care if it constructs a prior index, etc.
375 }
376
377
378 /**
379 * Notify a text node
380 */
381
382 public void characters(/*@NotNull*/ CharSequence chars, Location locationId, int properties) throws XPathException {
383 //System.err.println("characters: " + chars);
384 if (chars instanceof CompressedWhitespace &&
385 (properties & ReceiverOptions.WHOLE_TEXT_NODE) != 0) {
386 TinyTree tt = tree;
387 assert tt != null;
388 long lvalue = ((CompressedWhitespace) chars).getCompressedValue();
389 nodeNr = tt.addNode(Type.WHITESPACE_TEXT, currentDepth, (int)(lvalue >> 32), (int)lvalue, -1);
390
391 int prev = prevAtDepth[currentDepth];
392 if (prev > 0) {
393 tt.next[prev] = nodeNr;
394 }
395 tt.next[nodeNr] = prevAtDepth[currentDepth - 1]; // *O* owner pointer in last sibling
396 prevAtDepth[currentDepth] = nodeNr;
397 siblingsAtDepth[currentDepth]++;
398 if (lineNumbering) {
399 tt.setLineNumber(nodeNr, locationId.getLineNumber(), locationId.getColumnNumber());
400 }
401 return;
402 }
403
404 final int len = chars.length();
405 if (len > 0) {
406 nodeNr = makeTextNode(chars, len);
407 if (lineNumbering) {
408 tree.setLineNumber(nodeNr, locationId.getLineNumber(), locationId.getColumnNumber());
409 }
410 textualElementEligibilityState = textualElementEligibilityState == 1 ? 2 : 0;
411 }
412 }
413
414 /**
415 * Create a text node. Separate method so it can be overridden. If the current node
416 * on the tree is already a text node, the new text will be appended to it.
417 *
418 * @param chars the contents of the text node
419 * @param len the length of the text node
420 * @return the node number of the created text node, or the text node to which
421 * this text has been appended.
422 */
423
424 protected int makeTextNode(CharSequence chars, int len) {
425 TinyTree tt = tree;
426 assert tt != null;
427 int bufferStart = tt.getCharacterBuffer().length();
428 tt.appendChars(chars);
429 int n = tt.numberOfNodes - 1;
430 if (tt.nodeKind[n] == Type.TEXT && tt.depth[n] == currentDepth) {
431 // merge this text node with the previous text node
432 tt.beta[n] += len;
433 } else {
434 nodeNr = tt.addNode(Type.TEXT, currentDepth, bufferStart, len, -1);
435
436 int prev = prevAtDepth[currentDepth];
437 if (prev > 0) {
438 tt.next[prev] = nodeNr;
439 }
440 tt.next[nodeNr] = prevAtDepth[currentDepth - 1];
441 prevAtDepth[currentDepth] = nodeNr;
442 siblingsAtDepth[currentDepth]++;
443 }
444 return nodeNr;
445 }
446
447 /**
448 * Callback interface for SAX: not for application use
449 */
450
451 public void processingInstruction(String piname, /*@NotNull*/ CharSequence remainder, Location locationId, int properties) throws XPathException {
452 TinyTree tt = tree;
453 assert tt != null;
454
455 textualElementEligibilityState = 0;
456 if (tt.commentBuffer == null) {
457 tt.commentBuffer = new FastStringBuffer(FastStringBuffer.C256);
458 }
459 int s = tt.commentBuffer.length();
460 tt.commentBuffer.append(remainder.toString());
461 int nameCode = namePool.allocateFingerprint("", piname);
462
463 nodeNr = tt.addNode(Type.PROCESSING_INSTRUCTION, currentDepth, s, remainder.length(),
464 nameCode);
465
466 int prev = prevAtDepth[currentDepth];
467 if (prev > 0) {
468 tt.next[prev] = nodeNr;
469 }
470 tt.next[nodeNr] = prevAtDepth[currentDepth - 1]; // *O* owner pointer in last sibling
471 prevAtDepth[currentDepth] = nodeNr;
472 siblingsAtDepth[currentDepth]++;
473
474 tt.setSystemId(nodeNr, locationId.getSystemId());
475 if (lineNumbering) {
476 tt.setLineNumber(nodeNr, locationId.getLineNumber(), locationId.getColumnNumber());
477 }
478 }
479
480 /**
481 * Callback interface for SAX: not for application use
482 */
483
484 public void comment(/*@NotNull*/ CharSequence chars, Location locationId, int properties) throws XPathException {
485 TinyTree tt = tree;
486 assert tt != null;
487
488 textualElementEligibilityState = 0;
489 if (tt.commentBuffer == null) {
490 tt.commentBuffer = new FastStringBuffer(FastStringBuffer.C256);
491 }
492 int s = tt.commentBuffer.length();
493 tt.commentBuffer.append(chars.toString());
494 nodeNr = tt.addNode(Type.COMMENT, currentDepth, s, chars.length(), -1);
495
496 int prev = prevAtDepth[currentDepth];
497 if (prev > 0) {
498 tt.next[prev] = nodeNr;
499 }
500 tt.next[nodeNr] = prevAtDepth[currentDepth - 1]; // *O* owner pointer in last sibling
501 prevAtDepth[currentDepth] = nodeNr;
502 siblingsAtDepth[currentDepth]++;
503
504 if (lineNumbering) {
505 tt.setLineNumber(nodeNr, locationId.getLineNumber(), locationId.getColumnNumber());
506 }
507
508 }
509
510 /**
511 * Set an unparsed entity in the document
512 */
513
514 public void setUnparsedEntity(String name, String uri, String publicId) {
515 if (tree.getUnparsedEntity(name) == null) {
516 // bug 2187
517 tree.setUnparsedEntity(name, uri, publicId);
518 }
519 }
520
521 /*@NotNull*/
522 public BuilderMonitor getBuilderMonitor() {
523 return new TinyBuilderMonitor(this);
524 }
525
526 public boolean isPositionedAtElement() {
527 return tree.numberOfNodes > 0 && (tree.nodeKind[tree.numberOfNodes-1]&0x0f) == Type.ELEMENT;
528 }
529
530 /**
531 * Copy an element node and its subtree from another TinyTree instance
532 *
533 * @param sourceNode the element at the root of the subtree to be copied
534 */
535
536 public void bulkCopy(TinyElementImpl sourceNode, boolean copyNamespaces) {
537 TinyTree sourceTree = sourceNode.tree;
538 int oldNodeNr = sourceNode.nodeNr;
539 int newNodeNr = tree.numberOfNodes;
540 tree.bulkCopy(sourceTree, oldNodeNr, prevAtDepth, currentDepth);
541 int prev = prevAtDepth[currentDepth];
542 if (prev > 0) {
543 tree.next[prev] = newNodeNr;
544 }
545 tree.next[newNodeNr] = prevAtDepth[currentDepth - 1];
546 prevAtDepth[currentDepth] = newNodeNr;
547 siblingsAtDepth[currentDepth]++;
548 }
549
550 /**
551 * Graft an element node and its subtree from another tree instance
552 *
553 * @param node the external node to be grafted
554 */
555
556 public void graft(NodeInfo node, boolean copyNamespaces) {
557 int newNodeNr = tree.numberOfNodes;
558 tree.graft(node, newNodeNr, currentDepth, copyNamespaces);
559 int prev = prevAtDepth[currentDepth];
560 if (prev > 0) {
561 tree.next[prev] = newNodeNr;
562 }
563 tree.next[newNodeNr] = prevAtDepth[currentDepth - 1];
564 prevAtDepth[currentDepth] = newNodeNr;
565 siblingsAtDepth[currentDepth]++;
566 //tree.diagnosticDump();
567 }
568 }
569