Debian Codegraph @

net/sf/saxon/om/SequenceTool.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.om;
9
10 import net.sf.saxon.event.Receiver;
11 import net.sf.saxon.event.ReceiverOptions;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.Location;
14 import net.sf.saxon.functions.Count;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.iter.EmptyIterator;
17 import net.sf.saxon.tree.iter.UnfailingIterator;
18 import net.sf.saxon.tree.util.FastStringBuffer;
19 import net.sf.saxon.tree.wrapper.VirtualNode;
20 import net.sf.saxon.type.*;
21 import net.sf.saxon.value.*;
22
23 /**
24 * Utility class for manipulating sequences. Some of these methods should be regarded
25 * as temporary scaffolding while the model is in transition.
26 */
27 public class SequenceTool {
28
29 /**
30 * Constant returned by compareTo() method to indicate an indeterminate ordering between two values
31 */
32
33 public static final int INDETERMINATE_ORDERING = Integer.MIN_VALUE;
34
35 /**
36 * Produce a GroundedValue containing the same values as a supplied sequence.
37 *
38 * @param iterator the supplied sequence. The iterator may or may not be consumed as a result of
39 * passing it to this method.
40 * @return a GroundedValue containing the same items
41 * @throws XPathException if a failure occurs reading the input iterator
42 */
43
44 public static <T extends Item<?>> GroundedValue<T> toGroundedValue(SequenceIterator<T> iterator) throws XPathException {
45 return iterator.materialize();
46 }
47
48 /**
49 * Produce a Sequence containing the same values as a supplied sequence; the input is
50 * read progressively as required, and saved in a buffer as it is read in case it is needed
51 * again. But if the iterator is already backed by a grounded value, we return that value.
52 *
53 * @param iterator the supplied sequence. The iterator may or may not be consumed as a result of
54 * passing it to this method.
55 * @return a Sequence containing the same items
56 * @throws XPathException if a failure occurs reading the input iterator
57 */
58
59 public static <T extends Item<?>> Sequence<T> toMemoSequence(SequenceIterator<T> iterator) throws XPathException {
60 if (iterator instanceof EmptyIterator) {
61 return EmptySequence.getInstance();
62 } else if ((iterator.getProperties() & SequenceIterator.GROUNDED) != 0) {
63 return iterator.materialize();
64 } else {
65 return new MemoSequence<>(iterator);
66 }
67 }
68
69
70 /**
71 * Construct a sequence capable of returning the same items as an iterator,
72 * without incurring the cost of evaluating the iterator and storing all
73 * the items.
74 *
75 * @param iterator the supplied sequence. The iterator may or may not be consumed as a result of
76 * passing it to this method.
77 * @return a Sequence containing the same items as the supplied iterator
78 * @throws XPathException if a failure occurs reading the input iterator
79 */
80
81 public static <T extends Item<?>> Sequence<T> toLazySequence(SequenceIterator<T> iterator) throws XPathException {
82 if ((iterator.getProperties() & SequenceIterator.GROUNDED) != 0 &&
83 !(iterator instanceof RangeIterator) &&
84 !(iterator instanceof ReverseRangeIterator)) {
85 return iterator.materialize();
86 } else {
87 return new LazySequence<>(iterator);
88 }
89 }
90
91 public static Sequence<?> toLazySequence2(SequenceIterator<?> iterator) throws XPathException {
92 if ((iterator.getProperties() & SequenceIterator.GROUNDED) != 0 &&
93 !(iterator instanceof RangeIterator) &&
94 !(iterator instanceof ReverseRangeIterator)) {
95 return iterator.materialize();
96 } else {
97 return new LazySequence<>(iterator);
98 }
99 }
100
101 public static boolean isUnrepeatable(Sequence<?> seq) {
102 return seq instanceof LazySequence ||
103 (seq instanceof Closure && !(seq instanceof MemoClosure || seq instanceof SingletonClosure));
104 }
105
106 /**
107 * Get the length of a sequence (the number of items it contains)
108 *
109 * @param sequence the sequence
110 * @return the length in items
111 * @throws XPathException if an error occurs (due to lazy evaluation)
112 */
113
114 public static int getLength(Sequence<?> sequence) throws XPathException {
115 if (sequence instanceof GroundedValue) {
116 return ((GroundedValue) sequence).getLength();
117 }
118 return Count.count(sequence.iterate());
119 }
120
121 /**
122 * Ask whether the length of a sequence is exactly N
123 *
124 * @param iter an iterator over the sequence in question (which is typically consumed)
125 * @param length the supposed length
126 * @return true if and only if the length of the sequence is the supposed length
127 */
128
129 public static boolean hasLength(SequenceIterator iter, int length) throws XPathException {
130 if ((iter.getProperties() & SequenceIterator.LAST_POSITION_FINDER) != 0) {
131 return ((LastPositionFinder) iter).getLength() == length;
132 } else {
133 int n = 0;
134 while (iter.next() != null) {
135 if (n++ == length) {
136 iter.close();
137 return false;
138 }
139 }
140 return length == 0;
141 }
142 }
143
144
145 /**
146 * Determine whether two sequences have the same number of items. This is more efficient
147 * than comparing the counts, because the longer sequence is evaluated only as far as the
148 * length of the shorter sequence. The method consumes the supplied iterators.
149 *
150 * @param a iterator over the first sequence
151 * @param b iterator over the second sequece
152 * @return true if the lengths of the two sequences are the same
153 */
154
155 public static boolean sameLength(SequenceIterator a, SequenceIterator b) throws XPathException {
156 if ((a.getProperties() & SequenceIterator.LAST_POSITION_FINDER) != 0) {
157 return hasLength(b, ((LastPositionFinder) a).getLength());
158 } else if ((b.getProperties() & SequenceIterator.LAST_POSITION_FINDER) != 0) {
159 return hasLength(a, ((LastPositionFinder) b).getLength());
160 } else {
161 while (true) {
162 Item itA = a.next();
163 Item itB = b.next();
164 if (itA == null || itB == null) {
165 if (itA != null) {
166 a.close();
167 }
168 if (itB != null) {
169 b.close();
170 }
171 return itA == null && itB == null;
172 }
173 }
174 }
175 }
176
177 /**
178 * Get the item at a given offset in a sequence. Uses zero-base indexing
179 *
180 * @param sequence the input sequence
181 * @param index the 0-based subscript
182 * @return the n'th item if it exists, or null otherwise
183 * @throws XPathException for example if the value is a closure that needs to be
184 * evaluated, and evaluation fails
185 */
186
187 public static <T extends Item<?>> T itemAt(Sequence<T> sequence, int index) throws XPathException {
188 if (sequence instanceof Item && index == 0) {
189 return (T) sequence;
190 }
191 return sequence.materialize().itemAt(index);
192 }
193
194 /**
195 * Static method to make an Item from a Value
196 *
197 * @param sequence the value to be converted
198 * @return null if the value is an empty sequence; or the only item in the value
199 * if it is a singleton sequence
200 * @throws net.sf.saxon.trans.XPathException if the supplied Sequence contains multiple items
201 */
202
203 /*@Nullable*/
204 public static <T extends Item<?>> T asItem(Sequence<T> sequence) throws XPathException {
205 if (sequence instanceof Item) {
206 return (T) sequence;
207 }
208 SequenceIterator<T> iter = sequence.iterate();
209 T first = iter.next();
210 if (first == null) {
211 return null;
212 }
213 if (iter.next() != null) {
214 throw new XPathException("Sequence contains more than one item");
215 }
216 return first;
217 }
218
219 /**
220 * Convert an XPath value to a Java object.
221 * An atomic value is returned as an instance
222 * of the best available Java class. If the item is a node, the node is "unwrapped",
223 * to return the underlying node in the original model (which might be, for example,
224 * a DOM or JDOM node).
225 *
226 * @param item the item to be converted
227 * @return the value after conversion
228 * @throws net.sf.saxon.trans.XPathException if an error occurs: for example, if the XPath value is
229 * an integer and is too big to fit in a Java long
230 */
231
232 public static Object convertToJava(/*@NotNull*/ Item item) throws XPathException {
233 if (item instanceof NodeInfo) {
234 Object node = item;
235 while (node instanceof VirtualNode) {
236 // strip off any layers of wrapping
237 node = ((VirtualNode) node).getRealNode();
238 }
239 return node;
240 } else if (item instanceof Function) {
241 return item;
242 } else if (item instanceof ExternalObject) {
243 return ((ExternalObject) item).getObject();
244 } else {
245 AtomicValue value = (AtomicValue) item;
246 switch (value.getItemType().getPrimitiveType()) {
247 case StandardNames.XS_STRING:
248 case StandardNames.XS_UNTYPED_ATOMIC:
249 case StandardNames.XS_ANY_URI:
250 case StandardNames.XS_DURATION:
251 return value.getStringValue();
252 case StandardNames.XS_BOOLEAN:
253 return ((BooleanValue) value).getBooleanValue() ? Boolean.TRUE : Boolean.FALSE;
254 case StandardNames.XS_DECIMAL:
255 return ((BigDecimalValue) value).getDecimalValue();
256 case StandardNames.XS_INTEGER:
257 return ((NumericValue) value).longValue();
258 case StandardNames.XS_DOUBLE:
259 return ((DoubleValue) value).getDoubleValue();
260 case StandardNames.XS_FLOAT:
261 return ((FloatValue) value).getFloatValue();
262 case StandardNames.XS_DATE_TIME:
263 return ((DateTimeValue) value).getCalendar().getTime();
264 case StandardNames.XS_DATE:
265 return ((DateValue) value).getCalendar().getTime();
266 case StandardNames.XS_TIME:
267 return value.getStringValue();
268 case StandardNames.XS_BASE64_BINARY:
269 return ((Base64BinaryValue) value).getBinaryValue();
270 case StandardNames.XS_HEX_BINARY:
271 return ((HexBinaryValue) value).getBinaryValue();
272 default:
273 return item;
274 }
275 }
276 }
277
278 /**
279 * Get the string value of a sequence. For an item, this is same as the result
280 * of calling the XPath string() function. For a sequence of more than one item,
281 * it is the concatenation of the individual string values of the items in the sequence,
282 * space-separated.
283 *
284 * @param sequence the input sequence
285 * @return a string representation of the items in the supplied sequence
286 * @throws XPathException if the sequence contains an item with no string value,
287 * for example a function item
288 */
289
290 public static <T extends Item<?>> String getStringValue(Sequence<T> sequence) throws XPathException {
291 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
292 sequence.iterate().forEachOrFail(item -> {
293 if (!fsb.isEmpty()) {
294 fsb.append(' ');
295 }
296 fsb.append(item.getStringValueCS());
297 });
298 return fsb.toString();
299 }
300
301 /**
302 * Get the item type of the items in a sequence. If the sequence is heterogeneous,
303 * the method returns the lowest common supertype. If the sequence is empty, it returns
304 * ErrorType (the type to which no instance can belong)
305 *
306 * @param sequence the input sequence
307 * @param th the Type Hierarchy cache
308 * @return the lowest common supertype of the types of the items in the sequence
309 */
310
311 public static ItemType getItemType(Sequence<?> sequence, TypeHierarchy th) {
312 if (sequence instanceof Item) {
313 return Type.getItemType((Item) sequence, th);
314 } else if (sequence instanceof GroundedValue) {
315 try {
316 ItemType type = null;
317 SequenceIterator iter = sequence.iterate();
318 Item item;
319 while ((item = iter.next()) != null) {
320 if (type == null) {
321 type = Type.getItemType(item, th);
322 } else {
323 type = Type.getCommonSuperType(type, Type.getItemType(item, th), th);
324 }
325 if (type == AnyItemType.getInstance()) {
326 break;
327 }
328 }
329 return type == null ? ErrorType.getInstance() : type;
330 } catch (XPathException err) {
331 return AnyItemType.getInstance();
332 }
333 } else {
334 return AnyItemType.getInstance();
335 }
336 }
337
338 /**
339 * Get the UType of the items in a sequence. If the sequence is heterogeneous,
340 * the method returns the lowest common supertype. If the sequence is empty, it returns
341 * ErrorType (the type to which no instance can belong)
342 *
343 * @param sequence the input sequence
344 * @return the lowest common supertype of the types of the items in the sequence
345 */
346
347 public static UType getUType(Sequence<?> sequence) {
348 if (sequence instanceof Item) {
349 return UType.getUType((Item) sequence);
350 } else if (sequence instanceof GroundedValue) {
351 UType type = UType.VOID;
352 UnfailingIterator iter = ((GroundedValue) sequence).iterate();
353 Item item;
354 while ((item = iter.next()) != null) {
355 type = type.union(UType.getUType(item));
356 if (type == UType.ANY) {
357 break;
358 }
359 }
360 return type;
361 } else {
362 return UType.ANY;
363 }
364 }
365
366
367 /**
368 * Get the cardinality of a sequence
369 *
370 * @param sequence the supplied sequence
371 * @return the cardinality, as one of the constants {@link StaticProperty#ALLOWS_ZERO} (for an empty sequence)
372 * {@link StaticProperty#EXACTLY_ONE} (for a singleton), or {@link StaticProperty#ALLOWS_ONE_OR_MORE} (for
373 * a sequence with more than one item)
374 */
375
376 public static int getCardinality(Sequence<?> sequence) {
377 if (sequence instanceof Item) {
378 return StaticProperty.EXACTLY_ONE;
379 }
380 if (sequence instanceof GroundedValue) {
381 int len = ((GroundedValue) sequence).getLength();
382 switch (len) {
383 case 0:
384 return StaticProperty.ALLOWS_ZERO;
385 case 1:
386 return StaticProperty.EXACTLY_ONE;
387 default:
388 return StaticProperty.ALLOWS_ONE_OR_MORE;
389 }
390 }
391 try {
392 SequenceIterator<?> iter = sequence.iterate();
393 Item item = iter.next();
394 if (item == null) {
395 return StaticProperty.ALLOWS_ZERO;
396 }
397 item = iter.next();
398 return item == null ? StaticProperty.EXACTLY_ONE : StaticProperty.ALLOWS_ONE_OR_MORE;
399 } catch (XPathException err) {
400 return StaticProperty.ALLOWS_ONE_OR_MORE;
401 }
402 }
403
404 /**
405 * Get a sequence type to which a given value conforms
406 * @param value the given value
407 * @param th the type hierarchy cache
408 * @return the best available sequence type to which the supplied value conforms
409 */
410
411 public static SequenceType getSequenceType(Sequence<?> value, TypeHierarchy th) {
412 return SequenceType.makeSequenceType(getItemType(value, th), getCardinality(value));
413 }
414
415
416 /**
417 * Process a supplied value by copying it to the current output destination
418 *
419 * @param value the sequence to be processed
420 * @param context The dynamic context, giving access to the current node,
421 * the current variables, etc.
422 * @param locationId (can be set to -1 if absent) information about the location of the value,
423 * which can be resolved by reference to the PipelineConfiguration of the current output
424 * destination
425 * @throws net.sf.saxon.trans.XPathException if an error occurs (for example if the value is
426 * a closure that needs to be evaluated)
427 */
428
429 public static void process(Sequence<?> value, XPathContext context, Location locationId) throws XPathException {
430 Receiver out = context.getReceiver();
431 value.iterate().forEachOrFail(it -> out.append(it, locationId, ReceiverOptions.ALL_NAMESPACES));
432 }
433
434 /**
435 * Make an array of general-purpose Sequence objects of a given length
436 * @param length the length of the returned array
437 */
438
439 public static Sequence<?>[] makeSequenceArray(int length) {
440 return (Sequence<?>[])new Sequence[length];
441 }
442
443 /**
444 * Make an array of general-purpose Sequence objects with supplied contents
445 */
446
447 public static Sequence<?>[] fromItems(Item<?>... items) {
448 Sequence<?>[] seq = (Sequence<?>[]) new Sequence[items.length];
449 System.arraycopy(items, 0, seq, 0, items.length);
450 return seq;
451 }
452
453 }
454