| 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.om; |
| 9 | |
| 10 | import net.sf.saxon.expr.parser.ExpressionTool; |
| 11 | import net.sf.saxon.trans.XPathException; |
| 12 | import net.sf.saxon.tree.iter.GroundedIterator; |
| 13 | import net.sf.saxon.tree.iter.UnfailingIterator; |
| 14 | import net.sf.saxon.value.EmptySequence; |
| 15 | import net.sf.saxon.value.SequenceExtent; |
| 16 | |
| 17 | import java.util.*; |
| 18 | |
| 19 | /** |
| 20 | * A chain is an implementation of Sequence that represents the concatenation of |
| 21 | * a number of subsequences. |
| 22 | * <p>The most common use case is a recursive function that appends one item to a |
| 23 | * sequence each time it is called. Each call of this function will create a Chain |
| 24 | * with two subsequences, the first being a Chain and the second an individual item. |
| 25 | * The design of the class is constrained by the need to handle this extreme case.</p> |
| 26 | * <p>Firstly, the iterator for the class cannot use simple recursion to navigate the |
| 27 | * tree because it will often be too deep, causing StackOverflow. So it maintains its |
| 28 | * own Stack (on the Java heap).</p> |
| 29 | * <p>Secondly, even using the heap will run out of space at about a million entries. |
| 30 | * To prevent this, any Chains of size less than thirty items are amalgamated into |
| 31 | * chunks of 30. Building larger chunks than this would cause insertion operations |
| 32 | * to have linear performance (and thus the total cost of sequence construction |
| 33 | * would be quadratic). The figure of 30 was chosen because elapsed time is almost |
| 34 | * as good as with smaller chunks, and memory use during navigation is substantially |
| 35 | * reduced.</p> |
| 36 | * <p>A Chain has two phases in its life-cycle. In the first phase, the Chain is mutable; |
| 37 | * it can be extended using append() calls. In the second phase, the Chain is immutable; |
| 38 | * further append() operations are not allowed. The transition from the first to the |
| 39 | * second phase occurs when any of the methods itemAt(), reduce(), or subsequence() |
| 40 | * is called.</p> |
| 41 | */ |
| 42 | public class Chain implements GroundedValue<Item<?>> { |
| 43 | |
| 44 | private List<GroundedValue<?>> children = new ArrayList<>(); |
| 45 | private List<Item<?>> extent = null; |
| 46 | |
| 47 | /** |
| 48 | * Create a chain from a list of grounded values |
| 49 | * @param children the list of grounded values. The implementation may or may not copy |
| 50 | * this list, and it may or may not modify the list during execution |
| 51 | * of the {@link #append(Item)} method. The caller must not attempt to |
| 52 | * modify the list after return from this constructor. |
| 53 | */ |
| 54 | |
| 55 | public Chain(List<GroundedValue<?>> children) { |
| 56 | this.children = children; |
| 57 | |
| 58 | int size = 0; |
| 59 | boolean copy = false; |
| 60 | for (GroundedValue gv : children) { |
| 61 | if (gv instanceof Chain) { |
| 62 | if (((Chain) gv).children.size() < 30) { |
| 63 | size += ((Chain) gv).children.size(); |
| 64 | copy = true; |
| 65 | } else { |
| 66 | size++; |
| 67 | } |
| 68 | } else { |
| 69 | size++; |
| 70 | } |
| 71 | } |
| 72 | if (copy) { |
| 73 | this.children = new ArrayList<>(size); |
| 74 | for (GroundedValue<?> gv : children) { |
| 75 | if (gv instanceof Chain) { |
| 76 | if (((Chain) gv).children.size() < 30) { |
| 77 | this.children.addAll(((Chain) gv).children); |
| 78 | } else { |
| 79 | this.children.add(gv); |
| 80 | } |
| 81 | } else { |
| 82 | this.children.add(gv); |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | public Item<?> head() { |
| 89 | if (extent != null) { |
| 90 | return extent.isEmpty() ? null : extent.get(0); |
| 91 | } |
| 92 | for (GroundedValue<?> seq : children) { |
| 93 | Item<?> head = seq.head(); |
| 94 | if (head != null) { |
| 95 | return head; |
| 96 | } |
| 97 | } |
| 98 | return null; |
| 99 | } |
| 100 | |
| 101 | public UnfailingIterator<Item<?>> iterate() { |
| 102 | if (extent != null) { |
| 103 | return new net.sf.saxon.tree.iter.ListIterator<>(extent); |
| 104 | } else { |
| 105 | return new ChainIterator(this); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Add a single item to the end of this sequence. This method must only be called while the value |
| 111 | * is being constructed, since the sequence thereafter is immutable. |
| 112 | * |
| 113 | * @param item the item to be added |
| 114 | */ |
| 115 | |
| 116 | |
| 117 | public void append(Item item) { |
| 118 | if (extent != null) { |
| 119 | throw new IllegalStateException(); |
| 120 | } |
| 121 | if (item != null) { |
| 122 | //noinspection unchecked |
| 123 | children.add((GroundedValue<?>)item); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * Consolidate the sequence. This reduces it to a form in which the chain wraps a single sequenceExtent, |
| 129 | * making it easy to perform operations such as subsequence() and itemAt() efficiently. |
| 130 | */ |
| 131 | |
| 132 | private void consolidate() { |
| 133 | if (extent == null) { |
| 134 | extent = iterate().toList(); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Get the n'th item in the value, counting from 0 |
| 140 | * |
| 141 | * @param n the index of the required item, with 0 representing the first item in the sequence |
| 142 | * @return the n'th item if it exists, or null otherwise |
| 143 | */ |
| 144 | public Item<?> itemAt(int n) { |
| 145 | if (n == 0) { |
| 146 | return head(); |
| 147 | } else { |
| 148 | consolidate(); |
| 149 | if (n >= 0 && n < extent.size()) { |
| 150 | return extent.get(n); |
| 151 | } else { |
| 152 | return null; |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Get a subsequence of the value |
| 159 | * |
| 160 | * @param start the index of the first item to be included in the result, counting from zero. |
| 161 | * A negative value is taken as zero. If the value is beyond the end of the sequence, an empty |
| 162 | * sequence is returned |
| 163 | * @param length the number of items to be included in the result. Specify Integer.MAX_VALUE to |
| 164 | * get the subsequence up to the end of the base sequence. If the value is negative, an empty sequence |
| 165 | * is returned. If the value goes off the end of the sequence, the result returns items up to the end |
| 166 | * of the sequence |
| 167 | * @return the required subsequence. |
| 168 | */ |
| 169 | public GroundedValue<Item<?>> subsequence(int start, int length) { |
| 170 | consolidate(); |
| 171 | int newStart; |
| 172 | if (start < 0) { |
| 173 | start = 0; |
| 174 | } else if (start >= extent.size()) { |
| 175 | return EmptySequence.getInstance(); |
| 176 | } |
| 177 | newStart = start; |
| 178 | int newEnd; |
| 179 | if (length == Integer.MAX_VALUE) { |
| 180 | newEnd = extent.size(); |
| 181 | } else if (length < 0) { |
| 182 | return EmptySequence.getInstance(); |
| 183 | } else { |
| 184 | newEnd = newStart + length; |
| 185 | if (newEnd > extent.size()) { |
| 186 | newEnd = extent.size(); |
| 187 | } |
| 188 | } |
| 189 | return new SequenceExtent<>(extent.subList(newStart, newEnd)); |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Get the size of the value (the number of items) |
| 194 | * |
| 195 | * @return the number of items in the sequence |
| 196 | */ |
| 197 | public int getLength() { |
| 198 | if (extent != null) { |
| 199 | return extent.size(); |
| 200 | } else { |
| 201 | int n = 0; |
| 202 | for (GroundedValue v : children) { |
| 203 | n += v.getLength(); |
| 204 | } |
| 205 | return n; |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Get the effective boolean value of this sequence |
| 211 | * |
| 212 | * @return the effective boolean value |
| 213 | * @throws net.sf.saxon.trans.XPathException |
| 214 | * if the sequence has no effective boolean value (for example a sequence of two integers) |
| 215 | */ |
| 216 | public boolean effectiveBooleanValue() throws XPathException { |
| 217 | return ExpressionTool.effectiveBooleanValue(iterate()); |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * Get the string value of this sequence. The string value of an item is the result of applying the string() |
| 222 | * function. The string value of a sequence is the space-separated result of applying the string-join() function |
| 223 | * using a single space as the separator |
| 224 | * |
| 225 | * @return the string value of the sequence. |
| 226 | * @throws net.sf.saxon.trans.XPathException |
| 227 | * if the sequence contains items that have no string value (for example, function items) |
| 228 | */ |
| 229 | public String getStringValue() throws XPathException { |
| 230 | return SequenceTool.getStringValue(this); |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * Get the string value of this sequence. The string value of an item is the result of applying the string() |
| 235 | * function. The string value of a sequence is the space-separated result of applying the string-join() function |
| 236 | * using a single space as the separator |
| 237 | * |
| 238 | * @return the string value of the sequence. |
| 239 | * @throws net.sf.saxon.trans.XPathException |
| 240 | * if the sequence contains items that have no string value (for example, function items) |
| 241 | */ |
| 242 | public CharSequence getStringValueCS() throws XPathException { |
| 243 | return SequenceTool.getStringValue(this); |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * Reduce the sequence to its simplest form. If the value is an empty sequence, the result will be |
| 248 | * EmptySequence.getInstance(). If the value is a single atomic value, the result will be an instance |
| 249 | * of AtomicValue. If the value is a single item of any other kind, the result will be an instance |
| 250 | * of SingletonItem. Otherwise, the result will typically be unchanged. |
| 251 | * |
| 252 | * @return the simplified sequence |
| 253 | */ |
| 254 | public GroundedValue<Item<?>> reduce() { |
| 255 | consolidate(); |
| 256 | return SequenceExtent.makeSequenceExtent(extent); |
| 257 | } |
| 258 | |
| 259 | private static class ChainIterator implements UnfailingIterator<Item<?>>, GroundedIterator<Item<?>> { |
| 260 | |
| 261 | private class ChainPosition { |
| 262 | Chain chain; |
| 263 | int offset; |
| 264 | |
| 265 | public ChainPosition(Chain chain, int offset) { |
| 266 | this.chain = chain; |
| 267 | this.offset = offset; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | private Queue<UnfailingIterator<Item<?>>> queue = new LinkedList<>(); |
| 272 | |
| 273 | private Stack<ChainPosition> stack; |
| 274 | |
| 275 | private Chain thisChain; |
| 276 | |
| 277 | public ChainIterator(Chain thisChain) { |
| 278 | this.thisChain = thisChain; |
| 279 | stack = new Stack<>(); |
| 280 | stack.push(new ChainPosition(thisChain, 0)); |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Get the next item in the sequence. |
| 285 | * <p>The coding of this method is designed to avoid recursion, since it is not uncommon for the tree |
| 286 | * of Chain objects to be as deep as the length of the sequence it represents, and this inevitably |
| 287 | * leads to stack overflow. So the method maintains its own stack (on the Java heap).</p> |
| 288 | * |
| 289 | * @return the next item, or null if there are no more items. |
| 290 | */ |
| 291 | |
| 292 | public Item<?> next() { |
| 293 | |
| 294 | // If there are iterators on the queue waiting to be processed, then take the first |
| 295 | // item from the first iterator on the queue. |
| 296 | while (!queue.isEmpty()) { |
| 297 | UnfailingIterator<Item<?>> ui = queue.peek(); |
| 298 | while (ui != null) { |
| 299 | Item<?> current = ui.next(); |
| 300 | if (current != null) { |
| 301 | return current; |
| 302 | } else { |
| 303 | queue.remove(); |
| 304 | ui = queue.peek(); |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // Otherwise, or after attempting to process the iterators on the queue, look at the |
| 310 | // stack of Chain objects and get the next item from the top-most Chain. If this is itself |
| 311 | // a Chain, then add it to the stack and repeat. If this Chain is exhausted, then pop it off the |
| 312 | // stack and repeat. |
| 313 | |
| 314 | while (!stack.isEmpty()) { |
| 315 | ChainPosition cp = stack.peek(); |
| 316 | if (cp.offset >= cp.chain.children.size()) { |
| 317 | stack.pop(); |
| 318 | continue; |
| 319 | } |
| 320 | GroundedValue<?> gv = cp.chain.children.get(cp.offset++); |
| 321 | if (gv instanceof Chain) { |
| 322 | stack.push(new ChainPosition((Chain) gv, 0)); |
| 323 | } else if (gv instanceof Item) { |
| 324 | return (Item<?>)gv; |
| 325 | } else { |
| 326 | queue.offer((UnfailingIterator<Item<?>>)gv.iterate()); |
| 327 | return next(); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // If we get here, there is no more data available |
| 332 | |
| 333 | return null; |
| 334 | } |
| 335 | |
| 336 | public void close() { |
| 337 | |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * Get properties of this iterator, as a bit-significant integer. |
| 342 | * |
| 343 | * @return the properties of this iterator. This will be some combination of |
| 344 | * properties such as {@link SequenceIterator#GROUNDED}, {@link SequenceIterator#LAST_POSITION_FINDER}, |
| 345 | * and {@link SequenceIterator#LOOKAHEAD}. It is always |
| 346 | * acceptable to return the value zero, indicating that there are no known special properties. |
| 347 | * It is acceptable for the properties of the iterator to change depending on its state. |
| 348 | */ |
| 349 | |
| 350 | public int getProperties() { |
| 351 | return SequenceIterator.GROUNDED; |
| 352 | } |
| 353 | |
| 354 | /** |
| 355 | * Return a GroundedValue containing all the items in the sequence returned by this |
| 356 | * SequenceIterator. This should be an "in-memory" value, not a Closure. |
| 357 | * |
| 358 | * @return the corresponding Value |
| 359 | */ |
| 360 | |
| 361 | public GroundedValue<Item<?>> materialize() { |
| 362 | return thisChain; |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Return a GroundedValue containing all the remaining items in the sequence returned by this |
| 367 | * SequenceIterator, starting at the current position. This should be an "in-memory" value, not a Closure. |
| 368 | * |
| 369 | * @return the corresponding Value |
| 370 | * @throws XPathException in the cases of subclasses (such as the iterator over a MemoClosure) |
| 371 | * which cause evaluation of expressions while materializing the value. |
| 372 | */ |
| 373 | |
| 374 | public GroundedValue<Item<?>> getResidue() throws XPathException { |
| 375 | return new SequenceExtent<>(this); |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | |
| 380 | } |
| 381 |