Debian Codegraph @

net/sf/saxon/trans/KeyManager.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.trans;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.RetainedStaticContext;
14 import net.sf.saxon.functions.IntegratedFunctionLibrary;
15 import net.sf.saxon.functions.IsIdRef;
16 import net.sf.saxon.functions.SystemFunction;
17 import net.sf.saxon.lib.ConversionRules;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.pattern.BasePatternWithPredicate;
20 import net.sf.saxon.pattern.MultipleNodeKindTest;
21 import net.sf.saxon.pattern.NodeTestPattern;
22 import net.sf.saxon.pattern.Pattern;
23 import net.sf.saxon.sxpath.IndependentContext;
24 import net.sf.saxon.trace.ExpressionPresenter;
25 import net.sf.saxon.tree.iter.EmptyIterator;
26 import net.sf.saxon.tree.iter.ListIterator;
27 import net.sf.saxon.type.BuiltInAtomicType;
28 import net.sf.saxon.type.Converter;
29 import net.sf.saxon.type.UType;
30 import net.sf.saxon.value.AtomicValue;
31 import net.sf.saxon.value.DoubleValue;
32 import net.sf.saxon.value.NumericValue;
33 import net.sf.saxon.z.IntHashMap;
34
35 import java.lang.ref.WeakReference;
36 import java.util.*;
37
38 import static net.sf.saxon.trans.KeyIndex.Status.*;
39
40
41 /**
42 * KeyManager manages the set of key definitions in a stylesheet, and the indexes
43 * associated with these key definitions. It handles xsl:sort-key as well as xsl:key
44 * definitions.
45 * <p>The memory management in this class is subtle, with extensive use of weak references.
46 * The idea is that an index should continue to exist in memory so long as both the compiled
47 * stylesheet and the source document exist in memory: if either is removed, the index should
48 * go too. The document itself holds no reference to the index. The compiled stylesheet (which
49 * owns the KeyManager) holds a weak reference to the index. The index, of course, holds strong
50 * references to the nodes in the document. The Controller holds a strong reference to the
51 * list of indexes used for each document, so that indexes remain in memory for the duration
52 * of a transformation even if the documents themselves are garbage collected.</p>
53 * <p>Potentially there is a need for more than one index for a given key name, depending
54 * on the primitive type of the value provided to the key() function. An index is built
55 * corresponding to the type of the requested value; if subsequently the key() function is
56 * called with the same name and a different type of value, then a new index is built.</p>
57 * <p>For XSLT-defined keys, equality matching follows the rules of the eq operator, which means
58 * that untypedAtomic values are treated as strings. In backwards compatibility mode, <i>all</i>
59 * values are converted to strings.</p>
60 * <p>This class is also used for internal indexes constructed (a) to support the idref() function,
61 * and (b) (in Saxon-EE only) to support filter expressions of the form /a/b/c[d=e], where the
62 * path expression being filtered must be a single-document context-free path rooted at a document node,
63 * where exactly one of d and e must be dependent on the focus, and where certain other conditions apply
64 * such as the filter predicate not being positional. The operator in this case may be either "=" or "eq".
65 * If it is "eq", then the semantics are very similar to xsl:key indexes, except that use of non-comparable
66 * types gives an error rather than a non-match. If the operator is "=", however, then the rules for
67 * handling untypedAtomic values are different: these must be converted to the type of the other operand.
68 * In this situation the following rules apply. Assume that the predicate is [use=value], where use is
69 * dependent on the focus (the indexed value), and value is the sought value.</p>
70 * <ul>
71 * <li>If value is a type other than untypedAtomic, say T, then we build an index for type T, in which any
72 * untypedAtomic values that arise in evaluating "use" are converted to type T. A conversion failure results
73 * in an error. A value of a type that is not comparable to T also results in an error.</li>
74 * <li>If value is untypedAtomic, then we build an index for every type actually encountered in evaluating
75 * the use expression (treating untypedAtomic as string), and then search each of these indexes. (Note that
76 * it is not an error if the use expression returns a mixture of say numbers and dates, provided that the
77 * sought value is untypedAtomic).</li>
78 * </ul>
79 *
80 * @author Michael H. Kay
81 */
82
83 public class KeyManager {
84
85 private PackageData packageData;
86
87 private HashMap<StructuredQName, KeyDefinitionSet> keyDefinitions;
88 // one entry for each named key; the entry contains
89 // a KeyDefinitionSet holding the key definitions with that name
90 private transient WeakHashMap<TreeInfo, WeakReference<IntHashMap<KeyIndex>>> docIndexes;
91 // one entry for each document that is in memory;
92 // the entry contains a HashMap mapping the fingerprint of the key name plus the primitive item type
93 // to the HashMap that is the actual index of key/value pairs.
94
95 /**
96 * Create a KeyManager and initialise variables
97 *
98 * @param config the Saxon configuration
99 * @param pack the package in which these keys are available
100 */
101
102 public KeyManager(Configuration config, PackageData pack) {
103 packageData = pack;
104 keyDefinitions = new HashMap<>(10);
105 docIndexes = new WeakHashMap<>(10);
106 // Create a key definition for the idref() function
107 registerIdrefKey(config);
108 }
109
110 /**
111 * An internal key definition is used to support the idref() function. The key definition
112 * is equivalent to xsl:key match="element(*, xs:IDREF) | element(*, IDREFS) |
113 * attribute(*, xs:IDREF) | attribute(*, IDREFS)" use="tokenize(string(.))". This method creates this
114 * key definition.
115 *
116 * @param config The configuration. This is needed because the patterns that are
117 * generated need access to schema information.
118 */
119
120 private synchronized void registerIdrefKey(Configuration config) {
121 final StructuredQName qName = StandardNames.getStructuredQName(StandardNames.XS_IDREFS);
122 SymbolicName symbolicName = new SymbolicName(StandardNames.XSL_KEY, qName);
123 if (getKeyDefinitionSet(qName) == null) {
124 BasePatternWithPredicate pp = new BasePatternWithPredicate(
125 new NodeTestPattern(new MultipleNodeKindTest(UType.ELEMENT_OR_ATTRIBUTE)),
126 IntegratedFunctionLibrary.makeFunctionCall(new IsIdRef(), new Expression[]{})
127 );
128 try {
129 IndependentContext sc = new IndependentContext(config);
130 sc.setPackageData(packageData);
131 sc.setXPathLanguageLevel(31);
132 RetainedStaticContext rsc = new RetainedStaticContext(sc);
133 Expression sf = SystemFunction.makeCall("string", rsc, new ContextItemExpression());
134 Expression use = SystemFunction.makeCall("tokenize", rsc, sf); // Use the new tokenize#1
135 KeyDefinition key = new KeyDefinition(symbolicName, pp, use, null, null);
136 key.setPackageData(packageData);
137 key.setIndexedItemType(BuiltInAtomicType.STRING);
138 addKeyDefinition(qName, key, true, config);
139 } catch (XPathException err) {
140 throw new AssertionError(err); // shouldn't happen
141 }
142 }
143 }
144
145 /**
146 * Pre-register a key definition. This simply registers that a key with a given name exists,
147 * without providing any details.
148 *
149 * @param keyName the name of the key to be pre-registered
150 */
151
152 public synchronized void preRegisterKeyDefinition(StructuredQName keyName) {
153 KeyDefinitionSet keySet = keyDefinitions.get(keyName);
154 if (keySet == null) {
155 keySet = new KeyDefinitionSet(keyName, keyDefinitions.size());
156 keyDefinitions.put(keyName, keySet);
157 }
158 }
159
160 /**
161 * Register a key definition. Note that multiple key definitions with the same name are
162 * allowed
163 *
164 * @param keyName Structured QName representing the name of the key
165 * @param keydef The details of the key's definition
166 * @param reusable Set to true if indexes using this key definition can be used across multiple transformations, false if
167 * the indexes need to be rebuilt for each transformation. Indexes are not reusable if the key definition contains references
168 * to global variables or parameters, or calls used-defined functions or templates that might contain such references.
169 * @param config The configuration
170 * @throws XPathException if this key definition is inconsistent with existing key definitions having the same name
171 */
172
173 public synchronized void addKeyDefinition(StructuredQName keyName, KeyDefinition keydef, boolean reusable, Configuration config) throws XPathException {
174 KeyDefinitionSet keySet = keyDefinitions.get(keyName);
175 if (keySet == null) {
176 keySet = new KeyDefinitionSet(keyName, keyDefinitions.size());
177 keyDefinitions.put(keyName, keySet);
178 }
179 keySet.addKeyDefinition(keydef);
180
181 if (!reusable) {
182 keySet.setReusable(false);
183 }
184
185 boolean backwardsCompatible = keySet.isBackwardsCompatible();
186
187 if (backwardsCompatible) {
188 // In backwards compatibility mode, convert all the use-expression results to sequences of strings
189 List<KeyDefinition> v = keySet.getKeyDefinitions();
190 for (KeyDefinition kd : v) {
191 kd.setBackwardsCompatible(true);
192 if (!kd.getBody().getItemType().equals(BuiltInAtomicType.STRING)) {
193 Expression exp = new AtomicSequenceConverter(kd.getBody(), BuiltInAtomicType.STRING);
194 ((AtomicSequenceConverter) exp).allocateConverterStatically(config, false);
195 kd.setBody(exp);
196 }
197 }
198 }
199
200 }
201
202 /**
203 * Get all the key definitions that match a particular name
204 *
205 * @param qName The name of the required key
206 * @return The set of key definitions of the named key if there are any, or null otherwise.
207 */
208
209 public KeyDefinitionSet getKeyDefinitionSet(StructuredQName qName) {
210 return keyDefinitions.get(qName);
211 }
212
213 /**
214 * Look for a key definition that matches a proposed new key
215 *
216 * @param finder matches/selects the nodes to be indexed
217 * @param use computes the value on which the nodes are indexed
218 * @param collationName collation to be used
219 * @return a KeyDefinitionSet containing a key with the required characteristics if there
220 * is one, or null otherwise
221 */
222
223 public KeyDefinitionSet findKeyDefinition(Pattern finder, Expression use, String collationName) {
224 for (KeyDefinitionSet keySet : keyDefinitions.values()) {
225 if (keySet.getKeyDefinitions().size() == 1) {
226 for (KeyDefinition keyDef : keySet.getKeyDefinitions()) {
227 if (keyDef.getMatch().isEqual(finder) &&
228 keyDef.getUse().isEqual(use) &&
229 keyDef.getCollationName().equals(collationName)) {
230 return keySet;
231 }
232 }
233 }
234 }
235 return null;
236 }
237
238 /**
239 * Build the index for a particular document for a named key
240 *
241 * @param keySet The set of key definitions with this name
242 * @param doc The source document in question
243 * @param context The dynamic context
244 * @return the index in question, as a Map mapping a key value onto a List of nodes
245 * @throws XPathException if a dynamic error is encountered
246 */
247
248 private synchronized KeyIndex buildIndex(KeyDefinitionSet keySet,
249 TreeInfo doc,
250 XPathContext context) throws XPathException {
251 //System.err.println("Building index " + keySet.getKeyName() + " for doc " + doc.getDocumentNumber() + " in thread " + Thread.currentThread().getId());
252 KeyIndex index = new KeyIndex(keySet.isRangeKey());
253 index.buildIndex(keySet, doc, context);
254 //System.err.println("Done building index " + keySet.getKeyName() + " for doc " + doc.getDocumentNumber() + " in thread " + Thread.currentThread().getId());
255
256 return index;
257 }
258
259 private void buildIndex(KeyIndex index,
260 KeyDefinitionSet keySet,
261 TreeInfo doc,
262 XPathContext context) throws XPathException {
263 index.buildIndex(keySet, doc, context);
264 }
265
266 private static int getContextDepth(XPathContext c) {
267 int i = 0;
268 while (c != null) {
269 c = c.getCaller();
270 i++;
271 }
272 return i;
273 }
274
275
276 /**
277 * Get the nodes with a given key value
278 *
279 * @param keySet The set of key definitions identified by the key name used in the call to the key() function
280 * @param doc The source document in question
281 * @param soughtValue The required key value
282 * @param context The dynamic context, needed only the first time when the key is being built
283 * @return an iteration of the selected nodes, always in document order with no duplicates
284 * @throws XPathException if a dynamic error is encountered
285 */
286
287 public SequenceIterator<NodeInfo> selectByKey(
288 KeyDefinitionSet keySet,
289 TreeInfo doc,
290 AtomicValue soughtValue,
291 XPathContext context) throws XPathException {
292 if (soughtValue == null) {
293 return EmptyIterator.OfNodes.THE_INSTANCE;
294 }
295
296 if (keySet.isBackwardsCompatible()) {
297 // if backwards compatibility is in force, treat all values as strings
298 final ConversionRules rules = context.getConfiguration().getConversionRules();
299 soughtValue = Converter.convert(soughtValue, BuiltInAtomicType.STRING, rules).asAtomic();
300 } else {
301 // If the key value is numeric, promote it to a double
302 // Note: this could result in two decimals comparing equal because they convert to the same double
303
304 BuiltInAtomicType itemType = soughtValue.getPrimitiveType();
305 if (itemType.equals(BuiltInAtomicType.INTEGER) ||
306 itemType.equals(BuiltInAtomicType.DECIMAL) ||
307 itemType.equals(BuiltInAtomicType.FLOAT)) {
308 soughtValue = new DoubleValue(((NumericValue) soughtValue).getDoubleValue());
309 }
310 }
311
312 // No special action needed for anyURI to string promotion (it just seems to work: tests idky44, 45)
313
314 KeyIndex index = obtainIndex(keySet, doc, context);
315
316 List<NodeInfo> nodes = index.get(soughtValue);
317 if (nodes == null) {
318 return EmptyIterator.OfNodes.THE_INSTANCE;
319 } else {
320 return new ListIterator<>(nodes);
321 }
322
323 }
324
325 /**
326 * Get the nodes with a given composite key value
327 *
328 * @param keySet The set of key definitions identified by the key name used in the call to the key() function
329 * @param doc The source document in question
330 * @param soughtValue The required key value
331 * @param context The dynamic context, needed only the first time when the key is being built
332 * @return an iteration of the selected nodes, always in document order with no duplicates
333 * @throws XPathException if a dynamic error is encountered
334 */
335
336 public SequenceIterator selectByCompositeKey(
337 KeyDefinitionSet keySet,
338 TreeInfo doc,
339 SequenceIterator<?> soughtValue,
340 XPathContext context) throws XPathException {
341
342
343 KeyIndex index = obtainIndex(keySet, doc, context);
344
345 List<NodeInfo> nodes = index.getComposite(soughtValue);
346 if (nodes == null) {
347 return EmptyIterator.emptyIterator();
348 } else {
349 return new ListIterator<>(nodes);
350 }
351
352 }
353
354 /**
355 * Get the index supporting a particular key definition for a particular document. The index is created
356 * if it does not already exist.
357 *
358 * @param keySet the set of xsl:key definitions making up this key
359 * @param doc the document to which the index applies
360 * @param context the dynamic evaluation context
361 * @return the relevant index
362 * @throws XPathException if any failure occurs
363 */
364
365 public KeyIndex obtainIndex(KeyDefinitionSet keySet, TreeInfo doc, XPathContext context) throws XPathException {
366 if (keySet.isReusable()) {
367 return obtainSharedIndex(keySet, doc, context);
368 } else {
369 return obtainLocalIndex(keySet, doc, context);
370 }
371 }
372
373 private KeyIndex obtainSharedIndex(KeyDefinitionSet keySet, TreeInfo doc, XPathContext context) throws XPathException {
374 KeyIndex index;
375 int keySetNumber = keySet.getKeySetNumber();
376
377 index = getSharedIndex(doc, keySetNumber);
378 if (index != null) {
379 KeyIndex.Status status = index.getStatus();
380 if (status == UNDER_CONSTRUCTION) {
381 if (index.isCreatedInThisThread()) {
382 XPathException de = new XPathException(
383 "Key definition " + keySet.getKeyName().getDisplayName() + " is circular");
384 de.setXPathContext(context);
385 de.setErrorCode("XTDE0640");
386 throw de;
387 } else {
388 // if the index is under construction in another thread, then we plough on regardless.
389 // Both threads will construct the index, but only one will be saved
390 index = null;
391 }
392 } else if (status == FAILED) {
393 throw new XPathException("Construction of index for key " + keySet.getKeyName().getDisplayName() + " was unsuccessful");
394 }
395 }
396
397 // If the index does not yet exist, then create it.
398 if (index == null) {
399 // Mark the index as being under construction, in case the definition is circular
400 index = new KeyIndex(keySet.isRangeKey());
401 synchronized(this) {
402 index.setStatus(UNDER_CONSTRUCTION);
403 KeyIndex index2 = putSharedIndex(doc, keySetNumber, index, context);
404 if (index2.getStatus() == BUILT) {
405 // last chance to bail out - another thread got there first
406 return index2;
407 } else {
408 index = index2;
409 }
410 }
411 // Now we build the index (which isn't synchronized because it doesn't write to any shared data)
412 buildIndex(index, keySet, doc, context);
413 // On completion we synchronize again, and decide whether to use this index, or one that was
414 // completed earlier by a different thread.
415 synchronized(this) {
416 index.setStatus(BUILT);
417 index = putSharedIndex(doc, keySetNumber, index, context);
418 }
419 }
420 return index;
421 }
422
423 private KeyIndex obtainLocalIndex(KeyDefinitionSet keySet, TreeInfo doc, XPathContext context) throws XPathException {
424 KeyIndex index;
425 int keySetNumber = keySet.getKeySetNumber();
426
427 // We don't synchronize the index construction (see bug 3984) because holding synchronization
428 // locks while executing user code (the xsl:key/@use expression) can easily lead to deadlock.
429 // Instead, we check if a completely constructed index exists; if it does, we use it. If an
430 // index exists that is currently under construction, then if it's under construction in this
431 // thread, we report a circularity. If it's being constructed by a different thread, then
432 // we continue constructing the index, and at the end, the index that completes construction
433 // first is used by all threads (which involves synchronizing for a very short time).
434
435 index = getLocalIndex(doc, keySetNumber, context);
436 if (index != null) {
437 KeyIndex.Status status = index.getStatus();
438 if (status == UNDER_CONSTRUCTION) {
439 if (index.isCreatedInThisThread()) {
440 XPathException de = new XPathException(
441 "Key definition " + keySet.getKeyName().getDisplayName() + " is circular");
442 de.setXPathContext(context);
443 de.setErrorCode("XTDE0640");
444 throw de;
445 } else {
446 // if the index is under construction in another thread, then we plough on regardless.
447 // Both threads will construct the index, but only one will be saved
448 index = null;
449 }
450 } else if (status == FAILED) {
451 throw new XPathException("Construction of index for key " + keySet.getKeyName().getDisplayName() + " was unsuccessful");
452 }
453 }
454
455 // If the index does not yet exist, then create it.
456 if (index == null) {
457 // Mark the index as being under construction, in case the definition is circular
458 // putLocalIndex(doc, keySetNumber, underConstruction, context);
459 index = new KeyIndex(keySet.isRangeKey());
460 synchronized(this) {
461 index.setStatus(UNDER_CONSTRUCTION);
462 KeyIndex index2 = putLocalIndex(doc, keySetNumber, index, context);
463 if (index2.getStatus() == BUILT) {
464 // last chance to bail out - another thread got there first
465 return index2;
466 } else {
467 index = index2;
468 }
469 }
470 // Now we build the index (which isn't synchronized because it doesn't write to any shared data)
471 buildIndex(index, keySet, doc, context);
472 // On completion we synchronize again, and decide whether to use this index, or one that was
473 // completed earlier by a different thread.
474 synchronized(this) {
475 index.setStatus(BUILT);
476 index = putLocalIndex(doc, keySetNumber, index, context);
477 }
478 }
479 return index;
480 }
481
482 /**
483 * Save the index associated with a particular key, a particular item type,
484 * and a particular document. This needs to be done in such a way that the index is
485 * discarded by the garbage collector if the document is discarded. We therefore use a
486 * WeakHashMap indexed on the DocumentInfo, which returns HashMap giving the index for
487 * each key fingerprint. This index is itself another HashMap.
488 *
489 * <p>The methods need to be synchronized because several concurrent transformations (which share
490 * the same KeyManager) may be creating indexes for the same or different documents at the same
491 * time. In addition, multiple threads within the same transformation may be active.</p>
492 *
493 * @param doc the document being indexed
494 * @param keyFingerprint represents the name of the key definition
495 * @param index the index being saved
496 * @param context the dynamic evaluation context
497 */
498
499 private synchronized KeyIndex putSharedIndex(TreeInfo doc, int keyFingerprint, KeyIndex index, XPathContext context) {
500 if (docIndexes == null) {
501 // it's transient, so it will be null when reloading a compiled stylesheet
502 docIndexes = new WeakHashMap<>(10);
503 }
504 WeakReference<IntHashMap<KeyIndex>> indexRef = docIndexes.get(doc);
505 IntHashMap<KeyIndex> indexList;
506 if (indexRef == null || indexRef.get() == null) {
507 indexList = new IntHashMap<>(10);
508 // Ensure there is a firm reference to the indexList for the duration of a transformation
509 // But for keys associated with temporary trees, or documents that have been discarded from
510 // the document pool, keep the reference within the document node itself.
511 Controller controller = context.getController();
512 if (controller.getDocumentPool().contains(doc)) {
513 context.getController().setUserData(doc, "saxon:key-index-list", indexList);
514 } else {
515 doc.setUserData("saxon:key-index-list", indexList);
516 }
517 docIndexes.put(doc, new WeakReference<>(indexList));
518 } else {
519 indexList = indexRef.get();
520 }
521 KeyIndex result = indexList.get(keyFingerprint);
522 if (result == null || result.getStatus() != BUILT) {
523 // Use this index in preference to one that is under construction in another thread
524 indexList.put(keyFingerprint, index);
525 result = index;
526 }
527 return result;
528 }
529
530 /**
531 * Save the index associated with a particular key, a particular item type,
532 * and a particular document. This version of the method is used for indexes that are
533 * not reusable across transformations, because the key depends on transformation-specific
534 * data such as global variables or parameters.
535 * The method still need to be synchronized because several threads within a transformation
536 * may be creating indexes for the same or different documents at the same
537 * time.
538 *
539 * @param doc the document being indexed
540 * @param keyFingerprint represents the name of the key definition
541 * @param index the index being saved
542 * @param context the dynamic evaluation context
543 */
544
545 private synchronized KeyIndex putLocalIndex(TreeInfo doc, int keyFingerprint, KeyIndex index, XPathContext context) {
546 Controller controller = context.getController();
547 IntHashMap<Map<Long, KeyIndex>> masterIndex = controller.getLocalIndexes();
548 Map<Long, KeyIndex> docIndexes = masterIndex.get(keyFingerprint);
549 if (docIndexes == null) {
550 docIndexes = new HashMap<>();
551 masterIndex.put(keyFingerprint, docIndexes);
552 }
553 KeyIndex result = docIndexes.get(doc.getDocumentNumber());
554 if (result == null || result.getStatus() != BUILT) {
555 // Use this index in preference to one that is under construction in another thread
556 docIndexes.put(doc.getDocumentNumber(), index);
557 result = index;
558 }
559 return result;
560 }
561
562
563 /**
564 * Get the shared index associated with a particular key, a particular source document,
565 * and a particular primitive item type
566 *
567 * @param doc the document whose index is required
568 * @param keyFingerprint the name of the key definition
569 * @return either an index (as a HashMap), or the dummy map "under construction", or null
570 */
571
572 private synchronized KeyIndex getSharedIndex(TreeInfo doc, int keyFingerprint) {
573 if (docIndexes == null) {
574 // it's transient, so it will be null when reloading a compiled stylesheet
575 docIndexes = new WeakHashMap<>(10);
576 }
577 WeakReference<IntHashMap<KeyIndex>> ref = docIndexes.get(doc);
578 if (ref == null) {
579 return null;
580 }
581 IntHashMap<KeyIndex> indexList = ref.get();
582 if (indexList == null) {
583 return null;
584 }
585 return indexList.get(keyFingerprint);
586 }
587
588 /**
589 * Get the non-shared index associated with a particular key, a particular source document,
590 * and a particular primitive item type
591 *
592 * @param doc the document whose index is required
593 * @param keyFingerprint the name of the key definition
594 * @param context the dynamic evaluation context
595 * @return either an index (as a HashMap), or the dummy map "under construction", or null
596 */
597
598 private synchronized KeyIndex getLocalIndex(TreeInfo doc, int keyFingerprint, XPathContext context) {
599 Controller controller = context.getController();
600 IntHashMap<Map<Long, KeyIndex>> masterIndex = controller.getLocalIndexes();
601 Map<Long, KeyIndex> docIndexes = masterIndex.get(keyFingerprint);
602 if (docIndexes == null) {
603 return null;
604 } else {
605 return docIndexes.get(doc.getDocumentNumber());
606 }
607 }
608
609
610 /**
611 * Clear all the indexes for a given document. This is currently done whenever updates
612 * are applied to the document, because updates can potentially invalidate the indexes.
613 *
614 * @param doc the document whose indexes are to be invalidated
615 */
616
617 public synchronized void clearDocumentIndexes(TreeInfo doc) {
618 docIndexes.remove(doc);
619 }
620
621 /**
622 * Get all the key definition sets
623 *
624 * @return a set containing all the key definition sets
625 */
626
627 public Collection<KeyDefinitionSet> getAllKeyDefinitionSets() {
628 return keyDefinitions.values();
629 }
630
631 /**
632 * Get the number of distinctly-named key definitions
633 *
634 * @return the number of key definition sets (where the key definitions in one set share the same name)
635 */
636
637 public int getNumberOfKeyDefinitions() {
638 return keyDefinitions.size();
639 }
640
641 /**
642 * Diagnostic output explaining the keys
643 *
644 * @param out the expression presenter that will display the information
645 */
646
647 public void exportKeys(ExpressionPresenter out, Map<Component, Integer> componentIdMap) throws XPathException {
648 for (Map.Entry<StructuredQName, KeyDefinitionSet> e : keyDefinitions.entrySet()) {
649 boolean reusable = e.getValue().isReusable();
650 List<KeyDefinition> list = e.getValue().getKeyDefinitions();
651 for (KeyDefinition kd : list) {
652 if (!kd.getObjectName().equals(StandardNames.getStructuredQName(StandardNames.XS_IDREFS))) {
653 kd.export(out, reusable, componentIdMap);
654 }
655 }
656 }
657 }
658 }
659