Debian Codegraph @

net/sf/saxon/expr/sort/SortedIterator.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.expr.sort;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.ErrorIterator;
12 import net.sf.saxon.expr.LastPositionFinder;
13 import net.sf.saxon.expr.XPathContext;
14 import net.sf.saxon.om.FocusTrackingIterator;
15 import net.sf.saxon.om.Item;
16 import net.sf.saxon.om.SequenceIterator;
17 import net.sf.saxon.om.StandardNames;
18 import net.sf.saxon.trans.NoDynamicContextException;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.iter.LookaheadIterator;
21
22 /**
23 * Class to do a sorted iteration
24 */
25
26 public class SortedIterator implements SequenceIterator<Item<?>>, LastPositionFinder, LookaheadIterator<Item<?>>, Sortable {
27
28 // the items to be sorted
29 protected SequenceIterator<?> base;
30
31 // the call-back function used to evaluate sort keys
32 protected SortKeyEvaluator sortKeyEvaluator;
33
34 // the comparators corresponding to these sort keys
35 protected AtomicComparer[] comparators;
36
37 // The items and keys are read into an array (nodeKeys) for sorting. This
38 // array contains one "record" representing each node: the "record" contains
39 // first, the Item itself, then an entry for each of its sort keys, in turn;
40 // the last sort key is the position of the Item in the original sequence.
41 protected ObjectToBeSorted[] values;
42
43 // The number of items to be sorted. -1 means not yet known.
44 protected int count = -1;
45
46 // The next item to be delivered from the sorted iteration
47 protected int position = 0;
48
49 // The context for the evaluation of sort keys
50 protected XPathContext context;
51
52 // The host language (XSLT, XQuery, XPath). Used only to decide which error code to use on dynamic errors.
53 private int hostLanguage;
54
55 protected SortedIterator() {
56 }
57
58 /**
59 * Create a sorted iterator
60 *
61 * @param context the dynamic XPath evaluation context
62 * @param base an iterator over the sequence to be sorted
63 * @param sortKeyEvaluator an object that allows the n'th sort key for a given item to be evaluated
64 * @param comparators an array of AtomicComparers, one for each sort key, for comparing sort key values
65 * @param createNewContext true if sort keys are computed relative to the item being sorted (as in XSLT but not XQuery)
66 */
67
68 public SortedIterator(XPathContext context, SequenceIterator<?> base,
69 SortKeyEvaluator sortKeyEvaluator, AtomicComparer[] comparators, boolean createNewContext) {
70
71 if (createNewContext) {
72 this.context = context.newMinorContext();
73 this.base = this.context.trackFocus(base);
74 this.context.setTemporaryOutputState(StandardNames.XSL_SORT);
75 //this.context.setCurrentOutputUri(null); //See bug 4160
76 } else {
77 this.base = base;
78 this.context = context;
79 }
80
81 this.sortKeyEvaluator = sortKeyEvaluator;
82 this.comparators = new AtomicComparer[comparators.length];
83 for (int n = 0; n < comparators.length; n++) {
84 this.comparators[n] = comparators[n].provideContext(context);
85 }
86
87 // Avoid doing the sort until the user wants the first item. This is because
88 // sometimes the user only wants to know whether the collection is empty.
89 }
90
91 /**
92 * Set the host language
93 *
94 * @param language the host language (for example {@link Configuration#XQUERY})
95 */
96
97 public void setHostLanguage(int language) {
98 hostLanguage = language;
99 }
100
101 /**
102 * Determine whether there are more items to come. Note that this operation
103 * is stateless and it is not necessary (or usual) to call it before calling
104 * next(). It is used only when there is an explicit need to tell if we
105 * are at the last element.
106 * <p>This method must not be called unless the result of getProperties() on the iterator
107 * includes the bit setting {@link net.sf.saxon.om.SequenceIterator#LOOKAHEAD}</p>
108 *
109 * @return true if there are more items in the sequence
110 */
111
112 public boolean hasNext() {
113 if (position < 0) {
114 return false;
115 }
116 if (count < 0) {
117 // haven't started sorting yet
118 if (base instanceof LookaheadIterator) {
119 return ((LookaheadIterator) base).hasNext();
120 } else {
121 try {
122 doSort();
123 return count > 0;
124 } catch (XPathException err) {
125 // can't return the exception now; but we can rely on the fact that
126 // (a) it wouldn't have failed unless there was something to sort, and
127 // (b) it's going to fail again when next() is called
128 count = -1;
129 base = new FocusTrackingIterator<>(new ErrorIterator(err));
130 return true;
131 }
132 }
133 } else {
134 return position < count;
135 }
136 }
137
138 /**
139 * Get the next item, in sorted order
140 */
141
142 /*@Nullable*/
143 public Item next() throws XPathException {
144 if (position < 0) {
145 return null;
146 }
147 if (count < 0) {
148 doSort();
149 }
150 if (position < count) {
151 return (Item) values[position++].value;
152 } else {
153 position = -1;
154 return null;
155 }
156 }
157
158 public int getLength() throws XPathException {
159 if (count < 0) {
160 doSort();
161 }
162 return count;
163 }
164
165 public void close() {
166 }
167
168 /**
169 * Get properties of this iterator, as a bit-significant integer.
170 *
171 * @return the properties of this iterator. This will be some combination of
172 * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER},
173 * and {@link #LOOKAHEAD}. It is always
174 * acceptable to return the value zero, indicating that there are no known special properties.
175 * It is acceptable for the properties of the iterator to change depending on its state.
176 */
177
178 public int getProperties() {
179 return LAST_POSITION_FINDER;
180 }
181
182 /**
183 * Create an array holding the items to be sorted and the values of their sort keys
184 *
185 * @throws XPathException if an error occurs for example in evaluating a sort key
186 */
187
188 protected void buildArray() throws XPathException {
189 int allocated;
190 if ((base.getProperties() & SequenceIterator.LAST_POSITION_FINDER) != 0) {
191 allocated = ((LastPositionFinder) base).getLength();
192 } else {
193 allocated = 100;
194 }
195
196 values = new ItemToBeSorted[allocated];
197 count = 0;
198
199 // initialise the array with data
200
201 Item item;
202 while ((item = base.next()) != null) {
203 if (count == allocated) {
204 allocated *= 2;
205 ObjectToBeSorted[] nk2 = new ObjectToBeSorted[allocated];
206 System.arraycopy(values, 0, nk2, 0, count);
207 values = nk2;
208 }
209 ItemToBeSorted itbs = new ItemToBeSorted(comparators.length);
210 values[count] = itbs;
211 itbs.value = item;
212 // TODO: delay evaluating the sort keys until we know they are needed. Often the 2nd and subsequent
213 // sort key values will never be used. The only problem is with sort keys that depend on position().
214 for (int n = 0; n < comparators.length; n++) {
215 itbs.sortKeyValues[n] = sortKeyEvaluator.evaluateSortKey(n, context);
216 }
217 // make the sort stable by adding the record number
218 itbs.originalPosition = count++;
219 }
220
221 // If there's lots of unused space, reclaim it
222
223 if (allocated * 2 < count || (allocated - count) > 2000) {
224 ObjectToBeSorted[] nk2 = new ObjectToBeSorted[count];
225 System.arraycopy(values, 0, nk2, 0, count);
226 values = nk2;
227 }
228 }
229
230 private void doSort() throws XPathException {
231 buildArray();
232 if (count < 2) {
233 return;
234 }
235
236 // sort the array
237
238 //QuickSort.sort(this, 0, count-1);
239 try {
240 GenericSorter.quickSort(0, count, this);
241 } catch (ClassCastException e) {
242 XPathException err = new XPathException("Non-comparable types found while sorting: " + e.getMessage());
243 if (hostLanguage == Configuration.XSLT) {
244 err.setErrorCode("XTDE1030");
245 } else {
246 err.setErrorCode("XPTY0004");
247 }
248 throw err;
249 }
250 //GenericSorter.mergeSort(0, count, this);
251 }
252
253 /**
254 * Compare two items in sorted sequence
255 * (needed to implement the Sortable interface)
256 *
257 * @return &lt;0 if obj[a]&lt;obj[b], 0 if obj[a]=obj[b], &gt;0 if obj[a]&gt;obj[b]
258 */
259
260 public int compare(int a, int b) {
261 try {
262 for (int i = 0; i < comparators.length; i++) {
263 int comp = comparators[i].compareAtomicValues(
264 values[a].sortKeyValues[i], values[b].sortKeyValues[i]);
265 if (comp != 0) {
266 // we have found a difference, so we can return
267 return comp;
268 }
269 }
270 } catch (NoDynamicContextException e) {
271 throw new AssertionError("Sorting without dynamic context: " + e.getMessage());
272 }
273
274 // all sort keys equal: return the items in their original order
275
276 return values[a].originalPosition - values[b].originalPosition;
277 }
278
279 /**
280 * Swap two items (needed to implement the Sortable interface)
281 */
282
283 public void swap(int a, int b) {
284 ObjectToBeSorted temp = values[a];
285 values[a] = values[b];
286 values[b] = temp;
287 }
288
289 }
290