1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package typeutil defines various utilities for types, such as Map,
6 // a mapping from types.Type to interface{} values.
16 // Map is a hash-table-based mapping from types (types.Type) to
17 // arbitrary interface{} values. The concrete types that implement
18 // the Type interface are pointers. Since they are not canonicalized,
19 // == cannot be used to check for equivalence, and thus we cannot
20 // simply use a Go map.
22 // Just as with map[K]V, a nil *Map is a valid empty map.
26 // This fork handles Signatures correctly, respecting method
27 // receivers. Furthermore, it doesn't deduplicate interfaces or
28 // structs. Interfaces aren't deduplicated as not to conflate implicit
29 // and explicit methods. Structs aren't deduplicated because we track
30 // fields of each type separately.
33 hasher Hasher // shared by many Maps
34 table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused
35 length int // number of map entries
38 // entry is an entry (key/value association) in a hash bucket.
44 // SetHasher sets the hasher used by Map.
46 // All Hashers are functionally equivalent but contain internal state
47 // used to cache the results of hashing previously seen types.
49 // A single Hasher created by MakeHasher() may be shared among many
50 // Maps. This is recommended if the instances have many keys in
51 // common, as it will amortize the cost of hash computation.
53 // A Hasher may grow without bound as new types are seen. Even when a
54 // type is deleted from the map, the Hasher never shrinks, since other
55 // types in the map may reference the deleted type indirectly.
57 // Hashers are not thread-safe, and read-only operations such as
58 // Map.Lookup require updates to the hasher, so a full Mutex lock (not a
59 // read-lock) is require around all Map operations if a shared
60 // hasher is accessed from multiple threads.
62 // If SetHasher is not called, the Map will create a private hasher at
63 // the first call to Insert.
65 func (m *Map) SetHasher(hasher Hasher) {
69 // Delete removes the entry with the given key, if any.
70 // It returns true if the entry was found.
72 func (m *Map) Delete(key types.Type) bool {
73 if m != nil && m.table != nil {
74 hash := m.hasher.Hash(key)
75 bucket := m.table[hash]
76 for i, e := range bucket {
77 if e.key != nil && Identical(key, e.key) {
78 // We can't compact the bucket as it
79 // would disturb iterators.
89 // At returns the map entry for the given key.
90 // The result is nil if the entry is not present.
92 func (m *Map) At(key types.Type) interface{} {
93 if m != nil && m.table != nil {
94 for _, e := range m.table[m.hasher.Hash(key)] {
95 if e.key != nil && Identical(key, e.key) {
103 // Set sets the map entry for key to val,
104 // and returns the previous entry, if any.
105 func (m *Map) Set(key types.Type, value interface{}) (prev interface{}) {
107 hash := m.hasher.Hash(key)
108 bucket := m.table[hash]
110 for i, e := range bucket {
113 } else if Identical(key, e.key) {
115 bucket[i].value = value
121 *hole = entry{key, value} // overwrite deleted entry
123 m.table[hash] = append(bucket, entry{key, value})
126 if m.hasher.memo == nil {
127 m.hasher = MakeHasher()
129 hash := m.hasher.Hash(key)
130 m.table = map[uint32][]entry{hash: {entry{key, value}}}
137 // Len returns the number of map entries.
138 func (m *Map) Len() int {
145 // Iterate calls function f on each entry in the map in unspecified order.
147 // If f should mutate the map, Iterate provides the same guarantees as
148 // Go maps: if f deletes a map entry that Iterate has not yet reached,
149 // f will not be invoked for it, but if f inserts a map entry that
150 // Iterate has not yet reached, whether or not f will be invoked for
151 // it is unspecified.
153 func (m *Map) Iterate(f func(key types.Type, value interface{})) {
155 for _, bucket := range m.table {
156 for _, e := range bucket {
165 // Keys returns a new slice containing the set of map keys.
166 // The order is unspecified.
167 func (m *Map) Keys() []types.Type {
168 keys := make([]types.Type, 0, m.Len())
169 m.Iterate(func(key types.Type, _ interface{}) {
170 keys = append(keys, key)
175 func (m *Map) toString(values bool) string {
180 fmt.Fprint(&buf, "{")
182 m.Iterate(func(key types.Type, value interface{}) {
183 fmt.Fprint(&buf, sep)
185 fmt.Fprint(&buf, key)
187 fmt.Fprintf(&buf, ": %q", value)
190 fmt.Fprint(&buf, "}")
194 // String returns a string representation of the map's entries.
195 // Values are printed using fmt.Sprintf("%v", v).
196 // Order is unspecified.
198 func (m *Map) String() string {
199 return m.toString(true)
202 // KeysString returns a string representation of the map's key set.
203 // Order is unspecified.
205 func (m *Map) KeysString() string {
206 return m.toString(false)
209 ////////////////////////////////////////////////////////////////////////
212 // A Hasher maps each type to its hash value.
213 // For efficiency, a hasher uses memoization; thus its memory
214 // footprint grows monotonically over time.
215 // Hashers are not thread-safe.
216 // Hashers have reference semantics.
217 // Call MakeHasher to create a Hasher.
219 memo map[types.Type]uint32
222 // MakeHasher returns a new Hasher instance.
223 func MakeHasher() Hasher {
224 return Hasher{make(map[types.Type]uint32)}
227 // Hash computes a hash value for the given type t such that
228 // Identical(t, t') => Hash(t) == Hash(t').
229 func (h Hasher) Hash(t types.Type) uint32 {
230 hash, ok := h.memo[t]
238 // hashString computes the Fowler–Noll–Vo hash of s.
239 func hashString(s string) uint32 {
241 for i := 0; i < len(s); i++ {
248 // hashFor computes the hash of t.
249 func (h Hasher) hashFor(t types.Type) uint32 {
250 // See Identical for rationale.
251 switch t := t.(type) {
253 return uint32(t.Kind())
256 return 9043 + 2*uint32(t.Len()) + 3*h.Hash(t.Elem())
259 return 9049 + 2*h.Hash(t.Elem())
262 var hash uint32 = 9059
263 for i, n := 0, t.NumFields(); i < n; i++ {
268 hash += hashString(t.Tag(i))
269 hash += hashString(f.Name()) // (ignore f.Pkg)
270 hash += h.Hash(f.Type())
275 return 9067 + 2*h.Hash(t.Elem())
277 case *types.Signature:
278 var hash uint32 = 9091
282 return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results())
284 case *types.Interface:
285 var hash uint32 = 9103
286 for i, n := 0, t.NumMethods(); i < n; i++ {
287 // See go/types.identicalMethods for rationale.
288 // Method order is not significant.
291 hash += 3*hashString(m.Name()) + 5*h.Hash(m.Type())
296 return 9109 + 2*h.Hash(t.Key()) + 3*h.Hash(t.Elem())
299 return 9127 + 2*uint32(t.Dir()) + 3*h.Hash(t.Elem())
302 // Not safe with a copying GC; objects may move.
303 return uint32(reflect.ValueOf(t.Obj()).Pointer())
306 return h.hashTuple(t)
311 func (h Hasher) hashTuple(tuple *types.Tuple) uint32 {
312 // See go/types.identicalTypes for rationale.
314 var hash uint32 = 9137 + 2*uint32(n)
315 for i := 0; i < n; i++ {
316 hash += 3 * h.Hash(tuple.At(i).Type())