Debian Codegraph @

net/sf/saxon/trans/KeyIndex.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2013 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.trans;
9
10 import net.sf.saxon.expr.Expression;
11 import net.sf.saxon.expr.XPathContext;
12 import net.sf.saxon.expr.XPathContextMajor;
13 import net.sf.saxon.expr.instruct.SlotManager;
14 import net.sf.saxon.expr.sort.AtomicMatchKey;
15 import net.sf.saxon.expr.sort.CodepointMatchKey;
16 import net.sf.saxon.expr.sort.LocalOrderComparer;
17 import net.sf.saxon.lib.ConversionRules;
18 import net.sf.saxon.lib.StringCollator;
19 import net.sf.saxon.om.NodeInfo;
20 import net.sf.saxon.om.SequenceIterator;
21 import net.sf.saxon.om.StandardNames;
22 import net.sf.saxon.om.TreeInfo;
23 import net.sf.saxon.pattern.Pattern;
24 import net.sf.saxon.tree.iter.ManualIterator;
25 import net.sf.saxon.type.BuiltInAtomicType;
26 import net.sf.saxon.type.StringConverter;
27 import net.sf.saxon.type.UType;
28 import net.sf.saxon.value.AtomicValue;
29 import net.sf.saxon.value.UntypedAtomicValue;
30
31 import java.util.*;
32
33 /**
34 * A key index is an index maintained to support xsl:key key definitions, including both user-defined
35 * keys and keys added by the optimizer. Each key index supports one key definition (a set of xsl:key
36 * declarations with the same name) applied to one document tree.
37 *
38 * <p>The index can support a mixture of atomic keys of different types; there is no error caused by comparing
39 * values of different types. This relies on the fact that XPathComparable values are identical for comparable
40 * values (e.g. integers and doubles), and distinct otherwise.</p>
41 *
42 * <p>With the XSLT xsl:key construct, untypedAtomic values are treated as strings. However, this structure is
43 * also used to support internally-generated keys with general comparison semantics, where untyped values
44 * are converted to the type of the other operand. To enable this to work, we maintain a list of all
45 * untypedAtomic keys present in the index; and if a search is made for some type like xs:date, we then go
46 * through this list converting each untypedAtomic value to a date and indexing it as such. In principle this
47 * can happen for an arbitrary number of data types, though it is unlikely in practice because not many
48 * types have overlapping lexical spaces.</p>
49 */
50 public class KeyIndex {
51
52 public enum Status {UNDER_CONSTRUCTION, BUILT, FAILED}
53
54 private Map <AtomicMatchKey, List<NodeInfo>> index;
55 private UType keyTypesPresent = UType.VOID;
56 private UType keyTypesConvertedFromUntyped = UType.STRING_LIKE;
57 private List <UntypedAtomicValue> untypedKeys;
58 private ConversionRules rules;
59 private int implicitTimezone;
60 private StringCollator collation;
61 private long creatingThread;
62 private Status status;
63
64 public KeyIndex(boolean isRangeKey) {
65 index = isRangeKey ? new TreeMap<>() : new HashMap<>(100);
66 creatingThread = Thread.currentThread().getId();
67 status = Status.UNDER_CONSTRUCTION;
68 }
69
70 /**
71 * Get the underlying map
72 * @return the underlying map
73 */
74
75 public Map <AtomicMatchKey, List<NodeInfo>> getUnderlyingMap() {
76 return index;
77 }
78
79 /**
80 * Ask if the index was created in the current thread
81 * @return true if this index was created in this thread
82 */
83
84 public boolean isCreatedInThisThread() {
85 return creatingThread == Thread.currentThread().getId();
86 }
87
88 /**
89 * Ask if the index is under construction
90 * @return true if the index is still under construction
91 */
92
93 public Status getStatus() {
94 return status;
95 }
96
97 /**
98 * Say whether the index is under construction
99 * @param status
100 */
101
102 public void setStatus(Status status) {
103 this.status = status;
104 }
105
106 /**
107 * Build the index for a particular document for a named key
108 *
109 *
110 * @param keySet The set of key definitions with this name
111 * @param doc The source document in question
112 * @param context The dynamic context
113 * @throws XPathException if a dynamic error is encountered
114 */
115
116
117
118
119 public void buildIndex(KeyDefinitionSet keySet,
120 TreeInfo doc,
121 XPathContext context) throws XPathException {
122
123 List<KeyDefinition> definitions = keySet.getKeyDefinitions();
124
125 // There may be multiple xsl:key definitions with the same name. Index them all.
126 for (int k = 0; k < definitions.size(); k++) {
127 constructIndex(doc, definitions.get(k), context, k == 0);
128 }
129 this.rules = context.getConfiguration().getConversionRules();
130 this.implicitTimezone = context.getImplicitTimezone();
131 this.collation = definitions.get(0).getCollation();
132 }
133
134 /**
135 * Process one key definition to add entries to the index
136 *
137 *
138 * @param doc the document to be indexed
139 * @param keydef the key definition used to build the index
140 * @param context the XPath dynamic evaluation context
141 * @param isFirst true if this is the first index to be built for this key
142 * @throws XPathException if a dynamic error is encountered
143 */
144
145 private void constructIndex(TreeInfo doc,
146 KeyDefinition keydef,
147 XPathContext context,
148 boolean isFirst) throws XPathException {
149 //System.err.println("build index for doc " + doc.getDocumentNumber());
150 Pattern match = keydef.getMatch();
151
152 //NodeInfo curr;
153 XPathContextMajor xc = context.newContext();
154 xc.setOrigin(keydef);
155 xc.setCurrentComponent(keydef.getDeclaringComponent());
156 xc.setTemporaryOutputState(StandardNames.XSL_KEY);
157
158 // The use expression (or sequence constructor) may contain local variables.
159 SlotManager map = keydef.getStackFrameMap();
160 if (map != null) {
161 xc.openStackFrame(map);
162 }
163
164 match.selectNodes(doc, xc).forEachOrFail(node -> processNode(node, keydef, xc, isFirst));
165
166 }
167
168 /**
169 * Process one matching node, adding entries to the index if appropriate
170 *
171 *
172 * @param node the node being processed
173 * @param keydef the key definition
174 * @param xc the context for evaluating expressions
175 * @param isFirst indicates whether this is the first key definition with a given key name (which means
176 * no sort of the resulting key entries is required)
177 * @throws XPathException if a dynamic error is encountered
178 */
179
180 private void processNode(NodeInfo node,
181 KeyDefinition keydef,
182 XPathContext xc,
183 boolean isFirst) throws XPathException {
184
185
186 // Make the node we are testing the context node,
187 // with context position and context size set to 1
188
189 ManualIterator<NodeInfo> si = new ManualIterator<>(node);
190 xc.setCurrentIterator(si);
191
192 StringCollator collation = keydef.getCollation();
193 int implicitTimezone = xc.getImplicitTimezone();
194
195 // Evaluate the "use" expression against this context node
196
197 Expression use = keydef.getUse();
198 SequenceIterator<?> useval = use.iterate(xc);
199 if (keydef.isComposite()) {
200 List<AtomicMatchKey> amks = new ArrayList<>(4);
201 useval.forEachOrFail(
202 keyVal -> amks.add(getCollationKey((AtomicValue)keyVal, collation, implicitTimezone))
203 );
204 addEntry(new CompositeAtomicMatchKey(amks), node, isFirst);
205 } else {
206 AtomicValue keyVal;
207 while ((keyVal = (AtomicValue) useval.next()) != null) {
208 if (keyVal.isNaN()) {
209 continue;
210 }
211 UType actualUType = keyVal.getUType();
212 if (!keyTypesPresent.subsumes(actualUType)) {
213 keyTypesPresent = keyTypesPresent.union(actualUType);
214 }
215 AtomicMatchKey amk = getCollationKey(keyVal, collation, implicitTimezone);
216 if (actualUType.equals(UType.UNTYPED_ATOMIC) && keydef.isConvertUntypedToOther()) {
217 if (untypedKeys == null) {
218 untypedKeys = new ArrayList<>(20);
219 }
220 untypedKeys.add((UntypedAtomicValue)keyVal);
221 }
222 addEntry(amk, node, isFirst);
223 }
224 }
225
226 }
227
228 private void addEntry(AtomicMatchKey val, NodeInfo curr, boolean isFirst) {
229 List<NodeInfo> nodes = index.get(val);
230 if (nodes == null) {
231 // this is the first node with this key value
232 nodes = new ArrayList<>(4);
233 index.put(val, nodes);
234 nodes.add(curr);
235 } else {
236 // this is not the first node with this key value.
237 // add the node to the list of nodes for this key,
238 // unless it's already there
239 if (isFirst) {
240 // if this is the first index definition that we're processing,
241 // then this node must be after all existing nodes in document
242 // order, or the same node as the last existing node
243 if (nodes.get(nodes.size() - 1) != curr) {
244 nodes.add(curr);
245 }
246 } else {
247 // otherwise, we need to insert the node at the correct
248 // position in document order. This code does an insertion sort:
249 // not ideal for performance, but it's very unusual to have more than
250 // one key definition for a key. We start looking at the end because
251 // it's most likely that the new node will come after all the others.
252 // See bug 2092 in saxonica.plan.io
253 LocalOrderComparer comparer = LocalOrderComparer.getInstance();
254 boolean found = false;
255 for (int i=nodes.size()-1; i>=0; i--) {
256 int d = comparer.compare(curr, nodes.get(i));
257 if (d>=0) {
258 if (d==0) {
259 // node already in list; do nothing
260 } else {
261 // add the node at this position
262 nodes.add(i+1, curr);
263 }
264 found = true;
265 break;
266 }
267 // else continue round the loop
268 }
269 // if we're still here, add the new node at the start
270 if (!found) {
271 nodes.add(0, curr);
272 }
273 }
274 }
275 }
276
277 /**
278 * Re-index untyped atomic values after conversion to a specific type. This
279 * happens when the "convertUntypedToOther" option is set (typically because this
280 * index is used to support a general comparison), and the sought value is of a type
281 * other that string or untyped atomic. We go through the index finding all untyped
282 * atomic values, converting each one to the sought type, and adding it to the index under
283 * this type.
284 * @param type the type to which untyped atomic values should be converted
285 * @throws XPathException if conversion of any untyped atomic value to the requested key type fails
286 */
287
288 public void reindexUntypedValues(BuiltInAtomicType type) throws XPathException {
289 UType uType = type.getUType();
290 if (UType.STRING_LIKE.subsumes(uType)) {
291 return;
292 }
293 if (UType.NUMERIC.subsumes(uType)) {
294 type = BuiltInAtomicType.DOUBLE;
295 uType = UType.DOUBLE;
296 }
297 StringConverter converter = type.getStringConverter(rules);
298 for (UntypedAtomicValue v : untypedKeys) {
299 AtomicMatchKey uk = getCollationKey(v, collation, implicitTimezone);
300 List<NodeInfo> nodes = index.get(uk);
301 AtomicValue convertedValue = converter.convertString(v.getStringValueCS()).asAtomic();
302 AtomicMatchKey amk = getCollationKey(convertedValue, collation, implicitTimezone);
303 for (NodeInfo node : nodes) {
304 addEntry(amk, node, false);
305 }
306 }
307
308 }
309
310 /**
311 * Ask whether the index is empty
312 * @return true if the index is empty
313 */
314
315 public boolean isEmpty() {
316 return index.isEmpty();
317 }
318
319 /**
320 * Get the nodes with a given key value
321 *
322 * @param soughtValue The required key value
323 * @return a list of the selected nodes, always in document order with no duplicates, or null
324 * to represent an empty list
325 * @throws XPathException if a dynamic error is encountered
326 */
327
328 public List<NodeInfo> get(AtomicValue soughtValue) throws XPathException {
329 if (untypedKeys != null && !keyTypesConvertedFromUntyped.subsumes(soughtValue.getUType())) {
330 reindexUntypedValues(soughtValue.getPrimitiveType());
331 }
332 return index.get(getCollationKey(soughtValue, collation, implicitTimezone));
333 }
334
335 /**
336 * Get the nodes with a given composite key value
337 *
338 * @param soughtValue The required composite key value
339 * @return a list of the selected nodes, always in document order with no duplicates, or null
340 * to represent an empty list
341 * @throws XPathException if a dynamic error is encountered
342 */
343
344 public List<NodeInfo> getComposite(SequenceIterator<?> soughtValue) throws XPathException {
345 List<AtomicMatchKey> amks = new ArrayList<>(4);
346 soughtValue.forEachOrFail(
347 keyVal -> amks.add(getCollationKey((AtomicValue)keyVal, collation, implicitTimezone)));
348 return index.get(new CompositeAtomicMatchKey(amks));
349 }
350
351 private static AtomicMatchKey getCollationKey(AtomicValue value, StringCollator collation, int implicitTimezone)
352 throws XPathException {
353 if (UType.STRING_LIKE.subsumes(value.getUType())) {
354 if (collation == null) {
355 return new CodepointMatchKey(value.getStringValue());
356 } else {
357 return collation.getCollationKey(value.getStringValue());
358 }
359 } else {
360 return value.getXPathComparable(false, collation, implicitTimezone);
361 }
362 }
363
364 private class CompositeAtomicMatchKey implements AtomicMatchKey {
365
366 private List<AtomicMatchKey> keys;
367
368 public CompositeAtomicMatchKey(List<AtomicMatchKey> keys) {
369 this.keys = keys;
370 }
371
372 /**
373 * Get an atomic value that encapsulates this match key. Needed to support the collation-key() function.
374 *
375 * @return an atomic value that encapsulates this match key
376 */
377 public AtomicValue asAtomic() {
378 throw new UnsupportedOperationException();
379 }
380
381 @Override
382 public boolean equals(Object obj) {
383 if (obj instanceof CompositeAtomicMatchKey &&
384 ((CompositeAtomicMatchKey)obj).keys.size() == keys.size()) {
385 List<AtomicMatchKey> keys2 = ((CompositeAtomicMatchKey)obj).keys;
386 for (int i=0; i<keys.size(); i++) {
387 if (!keys.get(i).equals(keys2.get(i))) {
388 return false;
389 }
390 }
391 return true;
392 }
393 return false;
394 }
395
396 @Override
397 public int hashCode() {
398 int h = 0x8ab27cd6;
399 for (AtomicMatchKey amk : keys) {
400 h ^= amk.hashCode();
401 h = h << 1;
402 }
403 return h;
404 }
405 }
406 }
407