Debian Codegraph @

net/sf/saxon/ma/map/HashTrieMap.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.ma.map;
9
10 import net.sf.saxon.expr.StaticProperty;
11 import net.sf.saxon.expr.sort.AtomicMatchKey;
12 import net.sf.saxon.ma.trie.ImmutableHashTrieMap;
13 import net.sf.saxon.ma.trie.ImmutableMap;
14 import net.sf.saxon.ma.trie.Tuple2;
15 import net.sf.saxon.om.GroundedValue;
16 import net.sf.saxon.om.Sequence;
17 import net.sf.saxon.om.SequenceTool;
18 import net.sf.saxon.trans.Err;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.iter.AtomicIterator;
21 import net.sf.saxon.tree.util.FastStringBuffer;
22 import net.sf.saxon.type.*;
23 import net.sf.saxon.value.AtomicValue;
24 import net.sf.saxon.value.Cardinality;
25 import net.sf.saxon.value.SequenceType;
26
27 import java.util.Iterator;
28
29 /**
30 * An immutable map. This implementation, which uses a hash trie, was introduced in Saxon 9.6
31 */
32 public class HashTrieMap implements MapItem {
33
34 public final static SequenceType SINGLE_MAP_TYPE = SequenceType.makeSequenceType(
35 MapType.ANY_MAP_TYPE, StaticProperty.EXACTLY_ONE);
36
37 // The underlying trie holds key-value pairs, but these do not correspond directly
38 // to the key value pairs in the XDM map. Instead, the key in the trie is an AtomicMatchKey
39 // based on the XDM key, which allows equality matching to differ from the Java-level
40 // equals method (to take account of collations, etc). The value in the trie is
41 // actually a tuple holding both the real key, and the value.
42
43 private ImmutableMap<AtomicMatchKey, KeyValuePair> imap;
44
45 // The following values are maintained incrementally when
46 // entries are added to the map. They are not changed when entries are removed,
47 // so the actual type may be narrower than these values suggest. The purpose of
48 // keeping this information is to try and avoid dynamic checking of the map
49 // contents against a required type wherever possible. We therefore have
50 // a guarantee that all entries in the map conform to the types maintained here;
51 // but there is no guarantee that they do not also conform to some more specific
52 // type.
53
54 // The set of UTypes of keys in the map
55 private UType keyUType = UType.VOID;
56
57 // The set of UTypes of items in the values in the map
58 private UType valueUType = UType.VOID;
59
60 // The atomic type of all keys, if they are homogeneous; otherwise null
61 private AtomicType keyAtomicType = ErrorType.getInstance();
62
63 // The item type of all items in values, if they are homogeneous; otherwise null
64 private ItemType valueItemType = ErrorType.getInstance();
65
66 // The "envelope" cardinality of values in the map (0:1, 0:0, 1:1, 0:many, 1:many)
67 private int valueCardinality = 0;
68
69 // The number of entries in the map; -1 if unknown
70 private int entries = -1;
71
72 /**
73 * Create an empty map
74 */
75
76 public HashTrieMap() {
77 this.imap = ImmutableHashTrieMap.empty();
78 this.entries = 0;
79 }
80
81
82 /**
83 * Create a singleton map with a single key and value
84 * @param key the key value
85 * @param value the associated value
86 * @return a singleton map
87 */
88
89 public static HashTrieMap singleton(AtomicValue key, GroundedValue<?> value) {
90 return new HashTrieMap().addEntry(key, value);
91 }
92
93 /**
94 * Create a map whose contents are a copy of an existing immutable map
95 * @param imap the map to be copied
96 */
97
98 public HashTrieMap(ImmutableMap<AtomicMatchKey, KeyValuePair> imap) {
99 this.imap = imap;
100 entries = -1;
101 }
102
103 /**
104 * Create a map whose entries are copies of the entries in an existing MapItem
105 *
106 * @param map the existing map to be copied
107 * @return the new map
108 */
109
110 public static HashTrieMap copy(MapItem map) {
111 // if (Instrumentation.ACTIVE) {
112 // Instrumentation.count("copies");
113 // }
114 if (map instanceof HashTrieMap) {
115 return (HashTrieMap)map;
116 }
117 HashTrieMap m2 = new HashTrieMap();
118 for (KeyValuePair pair : map.keyValuePairs()) {
119 m2 = m2.addEntry(pair.key, pair.value);
120 }
121 return m2;
122 }
123
124 /**
125 * After adding an entry to the map, update the cached type information
126 * @param key the new key
127 * @param val the new associated value
128 * @param wasEmpty true if the map was empty before adding these values
129 */
130
131 private void updateTypeInformation(AtomicValue key, Sequence<?> val, boolean wasEmpty) {
132 // if (Instrumentation.ACTIVE) {
133 // Instrumentation.count("updateTypeInformation");
134 // }
135 if (wasEmpty) {
136 keyUType = key.getUType();
137 valueUType = SequenceTool.getUType(val);
138 keyAtomicType = key.getItemType();
139 valueItemType = MapItem.getItemTypeOfSequence(val);
140 valueCardinality = SequenceTool.getCardinality(val);
141 } else {
142 keyUType = keyUType.union(key.getUType());
143 valueUType = valueUType.union(SequenceTool.getUType(val));
144 valueCardinality = Cardinality.union(valueCardinality, SequenceTool.getCardinality(val));
145 if (key.getItemType() != keyAtomicType) {
146 keyAtomicType = null;
147 }
148 if (!MapItem.isKnownToConform(val, valueItemType)) {
149 valueItemType = null;
150 }
151 }
152 }
153
154 /**
155 * Get the size of the map
156 */
157
158 public int size() {
159 // if (Instrumentation.ACTIVE) {
160 // Instrumentation.count("size");
161 // }
162 if (entries >= 0) {
163 return entries;
164 }
165 int count = 0;
166 //noinspection UnusedDeclaration
167 for (KeyValuePair entry: keyValuePairs()) {
168 count++;
169 }
170 return entries = count;
171 }
172
173 /**
174 * Ask whether the map is empty
175 *
176 * @return true if and only if the size of the map is zero
177 */
178 public boolean isEmpty() {
179 // if (Instrumentation.ACTIVE) {
180 // Instrumentation.count("isEmpty");
181 // }
182 return entries == 0 || !imap.iterator().hasNext();
183 }
184
185 /**
186 * Ask whether the map conforms to a given map type
187 *
188 * @param requiredKeyType the required keyType
189 * @param requiredValueType the required valueType
190 * @param th the type hierarchy cache for the configuration
191 * @return true if the map conforms to the required type
192 */
193 @Override
194 public boolean conforms(AtomicType requiredKeyType, SequenceType requiredValueType, TypeHierarchy th) {
195 // if (Instrumentation.ACTIVE) {
196 // Instrumentation.count("conforms");
197 // }
198 if (isEmpty()) {
199 return true;
200 }
201 if (keyAtomicType == requiredKeyType && valueItemType == requiredValueType.getPrimaryType() &&
202 Cardinality.subsumes(requiredValueType.getCardinality(), valueCardinality)) {
203 return true;
204 }
205 boolean needFullCheck = false;
206 if (requiredKeyType != BuiltInAtomicType.ANY_ATOMIC) {
207 ItemType upperBoundKeyType = keyUType.toItemType();
208 int rel = th.relationship(requiredKeyType, upperBoundKeyType);
209 if (rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMES) {
210 // The key type is matched
211 } else if (rel == TypeHierarchy.DISJOINT) {
212 return false;
213 } else {
214 needFullCheck = true;
215 }
216 }
217 ItemType requiredValueItemType = requiredValueType.getPrimaryType();
218 if (requiredValueItemType != BuiltInAtomicType.ANY_ATOMIC) {
219 ItemType upperBoundValueType = valueUType.toItemType();
220 int rel = th.relationship(requiredValueItemType, upperBoundValueType);
221 if (rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMES) {
222 // The value type is matched
223 } else if (rel == TypeHierarchy.DISJOINT) {
224 return false;
225 } else {
226 needFullCheck = true;
227 }
228 }
229 int requiredValueCard = requiredValueType.getCardinality();
230 if (!Cardinality.subsumes(requiredValueCard, valueCardinality)) {
231 needFullCheck = true;
232 }
233
234 if (needFullCheck) {
235 // we need to test the entries individually
236 AtomicIterator keyIter = keys();
237 AtomicValue key;
238 while ((key = keyIter.next()) != null) {
239 if (!requiredKeyType.matches(key, th)) {
240 return false;
241 }
242 Sequence val = get(key);
243 try {
244 if (!requiredValueType.matches(val, th)) {
245 return false;
246 }
247 } catch (XPathException e) {
248 throw new AssertionError(e); // cannot happen with a grounded sequence
249 }
250 }
251 }
252
253 return true;
254
255 }
256
257 /**
258 * Get the type of the map. This method is used largely for diagnostics, to report
259 * the type of a map when it differs from the required type. This method has the side-effect
260 * of updating the internal type information held within the map.
261 *
262 * @param th The type hierarchy cache for the configuration
263 * @return the type of this map
264 */
265 @Override
266 public MapType getItemType(TypeHierarchy th) {
267 AtomicType keyType = null;
268 ItemType valueType = null;
269 int valueCard = 0;
270 // we need to test the entries individually
271 AtomicIterator keyIter = keys();
272 AtomicValue key;
273 while ((key = keyIter.next()) != null) {
274 Sequence<?> val = get(key);
275 if (keyType == null) {
276 keyType = key.getItemType();
277 valueType = SequenceTool.getItemType(val, th);
278 valueCard = SequenceTool.getCardinality(val);
279 } else {
280 keyType = (AtomicType)Type.getCommonSuperType(keyType, key.getItemType(), th);
281 valueType = Type.getCommonSuperType(valueType, SequenceTool.getItemType(val, th), th);
282 valueCard = Cardinality.union(valueCard, SequenceTool.getCardinality(val));
283 }
284 }
285 if (keyType == null) {
286 // implies the map is empty
287 this.keyUType = UType.VOID;
288 this.valueUType = UType.VOID;
289 this.valueCardinality = 0;
290 return MapType.ANY_MAP_TYPE;
291 } else {
292 this.keyUType = keyType.getUType();
293 this.valueUType = valueType.getUType();
294 this.valueCardinality = valueCard;
295 return new MapType(keyType, SequenceType.makeSequenceType(valueType, valueCard));
296 }
297 }
298
299 /**
300 * Get the lowest common item type of the keys in the map
301 *
302 * @return the most specific type to which all the keys belong. If the map is
303 * empty, return UType.VOID (the type with no instances)
304 */
305 public UType getKeyUType() {
306 return keyUType;
307 }
308
309 /**
310 * Create a new map containing the existing entries in the map plus an additional entry,
311 * without modifying the original. If there is already an entry with the specified key,
312 * this entry is replaced by the new entry.
313 *
314 * @param key the key of the new entry
315 * @param value the value associated with the new entry
316 * @return the new map containing the additional entry
317 */
318
319 public HashTrieMap addEntry(AtomicValue key, GroundedValue<?> value) {
320 boolean empty = isEmpty();
321 ImmutableMap<AtomicMatchKey, KeyValuePair> imap2 = imap.put(makeKey(key), new KeyValuePair(key, value));
322 HashTrieMap t2 = new HashTrieMap(imap2);
323 t2.valueCardinality = this.valueCardinality;
324 t2.keyUType = keyUType;
325 t2.valueUType = valueUType;
326 t2.keyAtomicType = keyAtomicType;
327 t2.valueItemType = valueItemType;
328 t2.updateTypeInformation(key, value, empty);
329 return t2;
330 }
331
332 /**
333 * Add a new entry to this map. Since the map is supposed to be immutable, this method
334 * must only be called while initially populating the map, and must not be called if
335 * anyone else might already be using the map.
336 *
337 * @param key the key of the new entry. Any existing entry with this key is replaced.
338 * @param value the value associated with the new entry
339 * @return true if an existing entry with the same key was replaced
340 */
341
342 public boolean initialPut(AtomicValue key, GroundedValue<?> value) {
343 // if (Instrumentation.ACTIVE) {
344 // Instrumentation.count("initialPut");
345 // }
346 boolean empty = isEmpty();
347 boolean exists = get(key) != null;
348 imap = imap.put(makeKey(key), new KeyValuePair(key, value));
349 updateTypeInformation(key, value, empty);
350 entries = -1;
351 return exists;
352 }
353
354 private AtomicMatchKey makeKey(AtomicValue key) {
355 return key.asMapKey();
356 }
357
358
359 /**
360 * Remove an entry from the map
361 *
362 * @param key the key of the entry to be removed
363 * @return a new map in which the requested entry has been removed; or this map
364 * unchanged if the specified key was not present
365 */
366
367 public HashTrieMap remove(AtomicValue key) {
368 // if (Instrumentation.ACTIVE) {
369 // Instrumentation.count("remove");
370 // }
371 ImmutableMap<AtomicMatchKey, KeyValuePair> m2 = imap.remove(makeKey(key));
372 if (m2 == imap) {
373 // The key is not present; the map is unchanged
374 return this;
375 }
376 HashTrieMap result = new HashTrieMap(m2);
377 result.keyUType = keyUType;
378 result.valueUType = valueUType;
379 result.valueCardinality = valueCardinality;
380 result.entries = entries-1;
381 return result;
382 }
383
384 /**
385 * Get an entry from the Map
386 *
387 * @param key the value of the key
388 * @return the value associated with the given key, or null if the key is not present in the map
389 */
390
391 public GroundedValue<?> get(AtomicValue key) {
392 KeyValuePair o = imap.get(makeKey(key));
393 return o==null ? null : o.value;
394 }
395
396 /**
397 * Get an key/value pair from the Map
398 *
399 * @param key the value of the key
400 * @return the key-value-pair associated with the given key, or null if the key is not present in the map
401 */
402
403 public KeyValuePair getKeyValuePair(AtomicValue key) {
404 return imap.get(makeKey(key));
405 }
406
407 /**
408 * Get the set of all key values in the map
409 * @return an iterator over the keys, in undefined order
410 */
411
412 public AtomicIterator keys() {
413 return new AtomicIterator() {
414
415 Iterator<Tuple2<AtomicMatchKey, KeyValuePair>> base = imap.iterator();
416
417 public AtomicValue next() {
418 if (base.hasNext()) {
419 return base.next()._2.key;
420 } else {
421 return null;
422 }
423 }
424 };
425
426 }
427
428 /**
429 * Get the set of all key-value pairs in the map
430 *
431 * @return an iterator over the key-value pairs
432 */
433 public Iterable<KeyValuePair> keyValuePairs() {
434 // if (Instrumentation.ACTIVE) {
435 // Instrumentation.count("keyValuePairs");
436 // }
437 return () -> new Iterator<KeyValuePair>() {
438 Iterator<Tuple2<AtomicMatchKey, KeyValuePair>> base = imap.iterator();
439
440 public boolean hasNext() {
441 return base.hasNext();
442 }
443
444 public KeyValuePair next() {
445 return base.next()._2;
446 }
447
448 public void remove() {
449 base.remove();
450 }
451 };
452
453
454 }
455
456
457 public void diagnosticDump() {
458 System.err.println("Map details:");
459 Iterator<Tuple2<AtomicMatchKey, KeyValuePair>> iter = imap.iterator();
460 while (iter.hasNext()) {
461 Tuple2<AtomicMatchKey, KeyValuePair> entry = iter.next();
462 AtomicMatchKey k1 = entry._1;
463 AtomicValue k2 = entry._2.key;
464 Sequence<?> v = entry._2.value;
465 System.err.println(k1.getClass() + " " + k1 +
466 " #:" + k1.hashCode() +
467 " = (" + k2.getClass() + " " + k2 + " : " + v + ")");
468 }
469 }
470
471 public String toShortString() {
472 int size = size();
473 if (size == 0) {
474 return "map{}";
475 } else if (size > 5) {
476 return "map{(:size " + size + ":)}";
477 } else {
478 FastStringBuffer buff = new FastStringBuffer(256);
479 buff.append("map{");
480 Iterator<Tuple2<AtomicMatchKey, KeyValuePair>> iter = imap.iterator();
481 while (iter.hasNext()) {
482 Tuple2<AtomicMatchKey, KeyValuePair> entry = iter.next();
483 AtomicMatchKey k1 = entry._1;
484 AtomicValue k2 = entry._2.key;
485 Sequence<?> v = entry._2.value;
486 buff.append(k2.toShortString());
487 buff.append(':');
488 buff.append(Err.depictSequence(v).toString().trim());
489 buff.append(", ");
490 }
491 if (size == 1) {
492 buff.append("}");
493 } else {
494 buff.setCharAt(buff.length() - 2, '}');
495 }
496 return buff.toString().trim();
497 }
498 }
499
500 public String toString() {
501 return MapItem.mapToString(this);
502 }
503 }
504
505 // Copyright (c) 2018 Saxonica Limited.
506
507
508