| 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. |
| 4 | |
| 5 | // Package typeutil defines various utilities for types, such as [Map], |
| 6 | // a hash table that maps [types.Type] to any value. |
| 7 | package typeutil |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "fmt" |
| 12 | "go/types" |
| 13 | "hash/maphash" |
| 14 | |
| 15 | "golang.org/x/tools/internal/typeparams" |
| 16 | ) |
| 17 | |
| 18 | // Map is a hash-table-based mapping from types (types.Type) to |
| 19 | // arbitrary values. The concrete types that implement |
| 20 | // the Type interface are pointers. Since they are not canonicalized, |
| 21 | // == cannot be used to check for equivalence, and thus we cannot |
| 22 | // simply use a Go map. |
| 23 | // |
| 24 | // Just as with map[K]V, a nil *Map is a valid empty map. |
| 25 | // |
| 26 | // Read-only map operations ([Map.At], [Map.Len], and so on) may |
| 27 | // safely be called concurrently. |
| 28 | // |
| 29 | // TODO(adonovan): deprecate in favor of https://go.dev/issues/69420 |
| 30 | // and 69559, if the latter proposals for a generic hash-map type and |
| 31 | // a types.Hash function are accepted. |
| 32 | type Map struct { |
| 33 | table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused |
| 34 | length int // number of map entries |
| 35 | } |
| 36 | |
| 37 | // entry is an entry (key/value association) in a hash bucket. |
| 38 | type entry struct { |
| 39 | key types.Type |
| 40 | value any |
| 41 | } |
| 42 | |
| 43 | // SetHasher has no effect. |
| 44 | // |
| 45 | // It is a relic of an optimization that is no longer profitable. Do |
| 46 | // not use [Hasher], [MakeHasher], or [SetHasher] in new code. |
| 47 | func (m *Map) SetHasher(Hasher) {} |
| 48 | |
| 49 | // Delete removes the entry with the given key, if any. |
| 50 | // It returns true if the entry was found. |
| 51 | func (m *Map) Delete(key types.Type) bool { |
| 52 | if m != nil && m.table != nil { |
| 53 | hash := hash(key) |
| 54 | bucket := m.table[hash] |
| 55 | for i, e := range bucket { |
| 56 | if e.key != nil && types.Identical(key, e.key) { |
| 57 | // We can't compact the bucket as it |
| 58 | // would disturb iterators. |
| 59 | bucket[i] = entry{} |
| 60 | m.length-- |
| 61 | return true |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | return false |
| 66 | } |
| 67 | |
| 68 | // At returns the map entry for the given key. |
| 69 | // The result is nil if the entry is not present. |
| 70 | func (m *Map) At(key types.Type) any { |
| 71 | if m != nil && m.table != nil { |
| 72 | for _, e := range m.table[hash(key)] { |
| 73 | if e.key != nil && types.Identical(key, e.key) { |
| 74 | return e.value |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | return nil |
| 79 | } |
| 80 | |
| 81 | // Set sets the map entry for key to val, |
| 82 | // and returns the previous entry, if any. |
| 83 | func (m *Map) Set(key types.Type, value any) (prev any) { |
| 84 | if m.table != nil { |
| 85 | hash := hash(key) |
| 86 | bucket := m.table[hash] |
| 87 | var hole *entry |
| 88 | for i, e := range bucket { |
| 89 | if e.key == nil { |
| 90 | hole = &bucket[i] |
| 91 | } else if types.Identical(key, e.key) { |
| 92 | prev = e.value |
| 93 | bucket[i].value = value |
| 94 | return |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | if hole != nil { |
| 99 | *hole = entry{key, value} // overwrite deleted entry |
| 100 | } else { |
| 101 | m.table[hash] = append(bucket, entry{key, value}) |
| 102 | } |
| 103 | } else { |
| 104 | hash := hash(key) |
| 105 | m.table = map[uint32][]entry{hash: {entry{key, value}}} |
| 106 | } |
| 107 | |
| 108 | m.length++ |
| 109 | return |
| 110 | } |
| 111 | |
| 112 | // Len returns the number of map entries. |
| 113 | func (m *Map) Len() int { |
| 114 | if m != nil { |
| 115 | return m.length |
| 116 | } |
| 117 | return 0 |
| 118 | } |
| 119 | |
| 120 | // Iterate calls function f on each entry in the map in unspecified order. |
| 121 | // |
| 122 | // If f should mutate the map, Iterate provides the same guarantees as |
| 123 | // Go maps: if f deletes a map entry that Iterate has not yet reached, |
| 124 | // f will not be invoked for it, but if f inserts a map entry that |
| 125 | // Iterate has not yet reached, whether or not f will be invoked for |
| 126 | // it is unspecified. |
| 127 | func (m *Map) Iterate(f func(key types.Type, value any)) { |
| 128 | if m != nil { |
| 129 | for _, bucket := range m.table { |
| 130 | for _, e := range bucket { |
| 131 | if e.key != nil { |
| 132 | f(e.key, e.value) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // Keys returns a new slice containing the set of map keys. |
| 140 | // The order is unspecified. |
| 141 | func (m *Map) Keys() []types.Type { |
| 142 | keys := make([]types.Type, 0, m.Len()) |
| 143 | m.Iterate(func(key types.Type, _ any) { |
| 144 | keys = append(keys, key) |
| 145 | }) |
| 146 | return keys |
| 147 | } |
| 148 | |
| 149 | func (m *Map) toString(values bool) string { |
| 150 | if m == nil { |
| 151 | return "{}" |
| 152 | } |
| 153 | var buf bytes.Buffer |
| 154 | fmt.Fprint(&buf, "{") |
| 155 | sep := "" |
| 156 | m.Iterate(func(key types.Type, value any) { |
| 157 | fmt.Fprint(&buf, sep) |
| 158 | sep = ", " |
| 159 | fmt.Fprint(&buf, key) |
| 160 | if values { |
| 161 | fmt.Fprintf(&buf, ": %q", value) |
| 162 | } |
| 163 | }) |
| 164 | fmt.Fprint(&buf, "}") |
| 165 | return buf.String() |
| 166 | } |
| 167 | |
| 168 | // String returns a string representation of the map's entries. |
| 169 | // Values are printed using fmt.Sprintf("%v", v). |
| 170 | // Order is unspecified. |
| 171 | func (m *Map) String() string { |
| 172 | return m.toString(true) |
| 173 | } |
| 174 | |
| 175 | // KeysString returns a string representation of the map's key set. |
| 176 | // Order is unspecified. |
| 177 | func (m *Map) KeysString() string { |
| 178 | return m.toString(false) |
| 179 | } |
| 180 | |
| 181 | // -- Hasher -- |
| 182 | |
| 183 | // hash returns the hash of type t. |
| 184 | // TODO(adonovan): replace by types.Hash when Go proposal #69420 is accepted. |
| 185 | func hash(t types.Type) uint32 { |
| 186 | return theHasher.Hash(t) |
| 187 | } |
| 188 | |
| 189 | // A Hasher provides a [Hasher.Hash] method to map a type to its hash value. |
| 190 | // Hashers are stateless, and all are equivalent. |
| 191 | type Hasher struct{} |
| 192 | |
| 193 | var theHasher Hasher |
| 194 | |
| 195 | // MakeHasher returns Hasher{}. |
| 196 | // Hashers are stateless; all are equivalent. |
| 197 | func MakeHasher() Hasher { return theHasher } |
| 198 | |
| 199 | // Hash computes a hash value for the given type t such that |
| 200 | // Identical(t, t') => Hash(t) == Hash(t'). |
| 201 | func (h Hasher) Hash(t types.Type) uint32 { |
| 202 | return hasher{inGenericSig: false}.hash(t) |
| 203 | } |
| 204 | |
| 205 | // hasher holds the state of a single Hash traversal: whether we are |
| 206 | // inside the signature of a generic function; this is used to |
| 207 | // optimize [hasher.hashTypeParam]. |
| 208 | type hasher struct{ inGenericSig bool } |
| 209 | |
| 210 | // hashString computes the Fowler–Noll–Vo hash of s. |
| 211 | func hashString(s string) uint32 { |
| 212 | var h uint32 |
| 213 | for i := 0; i < len(s); i++ { |
| 214 | h ^= uint32(s[i]) |
| 215 | h *= 16777619 |
| 216 | } |
| 217 | return h |
| 218 | } |
| 219 | |
| 220 | // hash computes the hash of t. |
| 221 | func (h hasher) hash(t types.Type) uint32 { |
| 222 | // See Identical for rationale. |
| 223 | switch t := t.(type) { |
| 224 | case *types.Basic: |
| 225 | return uint32(t.Kind()) |
| 226 | |
| 227 | case *types.Alias: |
| 228 | return h.hash(types.Unalias(t)) |
| 229 | |
| 230 | case *types.Array: |
| 231 | return 9043 + 2*uint32(t.Len()) + 3*h.hash(t.Elem()) |
| 232 | |
| 233 | case *types.Slice: |
| 234 | return 9049 + 2*h.hash(t.Elem()) |
| 235 | |
| 236 | case *types.Struct: |
| 237 | var hash uint32 = 9059 |
| 238 | for i, n := 0, t.NumFields(); i < n; i++ { |
| 239 | f := t.Field(i) |
| 240 | if f.Anonymous() { |
| 241 | hash += 8861 |
| 242 | } |
| 243 | hash += hashString(t.Tag(i)) |
| 244 | hash += hashString(f.Name()) // (ignore f.Pkg) |
| 245 | hash += h.hash(f.Type()) |
| 246 | } |
| 247 | return hash |
| 248 | |
| 249 | case *types.Pointer: |
| 250 | return 9067 + 2*h.hash(t.Elem()) |
| 251 | |
| 252 | case *types.Signature: |
| 253 | var hash uint32 = 9091 |
| 254 | if t.Variadic() { |
| 255 | hash *= 8863 |
| 256 | } |
| 257 | |
| 258 | tparams := t.TypeParams() |
| 259 | if n := tparams.Len(); n > 0 { |
| 260 | h.inGenericSig = true // affects constraints, params, and results |
| 261 | |
| 262 | for i := range n { |
| 263 | tparam := tparams.At(i) |
| 264 | hash += 7 * h.hash(tparam.Constraint()) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results()) |
| 269 | |
| 270 | case *types.Union: |
| 271 | return h.hashUnion(t) |
| 272 | |
| 273 | case *types.Interface: |
| 274 | // Interfaces are identical if they have the same set of methods, with |
| 275 | // identical names and types, and they have the same set of type |
| 276 | // restrictions. See go/types.identical for more details. |
| 277 | var hash uint32 = 9103 |
| 278 | |
| 279 | // Hash methods. |
| 280 | for i, n := 0, t.NumMethods(); i < n; i++ { |
| 281 | // Method order is not significant. |
| 282 | // Ignore m.Pkg(). |
| 283 | m := t.Method(i) |
| 284 | // Use shallow hash on method signature to |
| 285 | // avoid anonymous interface cycles. |
| 286 | hash += 3*hashString(m.Name()) + 5*h.shallowHash(m.Type()) |
| 287 | } |
| 288 | |
| 289 | // Hash type restrictions. |
| 290 | terms, err := typeparams.InterfaceTermSet(t) |
| 291 | // if err != nil t has invalid type restrictions. |
| 292 | if err == nil { |
| 293 | hash += h.hashTermSet(terms) |
| 294 | } |
| 295 | |
| 296 | return hash |
| 297 | |
| 298 | case *types.Map: |
| 299 | return 9109 + 2*h.hash(t.Key()) + 3*h.hash(t.Elem()) |
| 300 | |
| 301 | case *types.Chan: |
| 302 | return 9127 + 2*uint32(t.Dir()) + 3*h.hash(t.Elem()) |
| 303 | |
| 304 | case *types.Named: |
| 305 | hash := h.hashTypeName(t.Obj()) |
| 306 | targs := t.TypeArgs() |
| 307 | for targ := range targs.Types() { |
| 308 | hash += 2 * h.hash(targ) |
| 309 | } |
| 310 | return hash |
| 311 | |
| 312 | case *types.TypeParam: |
| 313 | return h.hashTypeParam(t) |
| 314 | |
| 315 | case *types.Tuple: |
| 316 | return h.hashTuple(t) |
| 317 | } |
| 318 | |
| 319 | panic(fmt.Sprintf("%T: %v", t, t)) |
| 320 | } |
| 321 | |
| 322 | func (h hasher) hashTuple(tuple *types.Tuple) uint32 { |
| 323 | // See go/types.identicalTypes for rationale. |
| 324 | n := tuple.Len() |
| 325 | hash := 9137 + 2*uint32(n) |
| 326 | for i := range n { |
| 327 | hash += 3 * h.hash(tuple.At(i).Type()) |
| 328 | } |
| 329 | return hash |
| 330 | } |
| 331 | |
| 332 | func (h hasher) hashUnion(t *types.Union) uint32 { |
| 333 | // Hash type restrictions. |
| 334 | terms, err := typeparams.UnionTermSet(t) |
| 335 | // if err != nil t has invalid type restrictions. Fall back on a non-zero |
| 336 | // hash. |
| 337 | if err != nil { |
| 338 | return 9151 |
| 339 | } |
| 340 | return h.hashTermSet(terms) |
| 341 | } |
| 342 | |
| 343 | func (h hasher) hashTermSet(terms []*types.Term) uint32 { |
| 344 | hash := 9157 + 2*uint32(len(terms)) |
| 345 | for _, term := range terms { |
| 346 | // term order is not significant. |
| 347 | termHash := h.hash(term.Type()) |
| 348 | if term.Tilde() { |
| 349 | termHash *= 9161 |
| 350 | } |
| 351 | hash += 3 * termHash |
| 352 | } |
| 353 | return hash |
| 354 | } |
| 355 | |
| 356 | // hashTypeParam returns the hash of a type parameter. |
| 357 | func (h hasher) hashTypeParam(t *types.TypeParam) uint32 { |
| 358 | // Within the signature of a generic function, TypeParams are |
| 359 | // identical if they have the same index and constraint, so we |
| 360 | // hash them based on index. |
| 361 | // |
| 362 | // When we are outside a generic function, free TypeParams are |
| 363 | // identical iff they are the same object, so we can use a |
| 364 | // more discriminating hash consistent with object identity. |
| 365 | // This optimization saves [Map] about 4% when hashing all the |
| 366 | // types.Info.Types in the forward closure of net/http. |
| 367 | if !h.inGenericSig { |
| 368 | // Optimization: outside a generic function signature, |
| 369 | // use a more discrimating hash consistent with object identity. |
| 370 | return h.hashTypeName(t.Obj()) |
| 371 | } |
| 372 | return 9173 + 3*uint32(t.Index()) |
| 373 | } |
| 374 | |
| 375 | var theSeed = maphash.MakeSeed() |
| 376 | |
| 377 | // hashTypeName hashes the pointer of tname. |
| 378 | func (hasher) hashTypeName(tname *types.TypeName) uint32 { |
| 379 | // Since types.Identical uses == to compare TypeNames, |
| 380 | // the Hash function uses maphash.Comparable. |
| 381 | hash := maphash.Comparable(theSeed, tname) |
| 382 | return uint32(hash ^ (hash >> 32)) |
| 383 | } |
| 384 | |
| 385 | // shallowHash computes a hash of t without looking at any of its |
| 386 | // element Types, to avoid potential anonymous cycles in the types of |
| 387 | // interface methods. |
| 388 | // |
| 389 | // When an unnamed non-empty interface type appears anywhere among the |
| 390 | // arguments or results of an interface method, there is a potential |
| 391 | // for endless recursion. Consider: |
| 392 | // |
| 393 | // type X interface { m() []*interface { X } } |
| 394 | // |
| 395 | // The problem is that the Methods of the interface in m's result type |
| 396 | // include m itself; there is no mention of the named type X that |
| 397 | // might help us break the cycle. |
| 398 | // (See comment in go/types.identical, case *Interface, for more.) |
| 399 | func (h hasher) shallowHash(t types.Type) uint32 { |
| 400 | // t is the type of an interface method (Signature), |
| 401 | // its params or results (Tuples), or their immediate |
| 402 | // elements (mostly Slice, Pointer, Basic, Named), |
| 403 | // so there's no need to optimize anything else. |
| 404 | switch t := t.(type) { |
| 405 | case *types.Alias: |
| 406 | return h.shallowHash(types.Unalias(t)) |
| 407 | |
| 408 | case *types.Signature: |
| 409 | var hash uint32 = 604171 |
| 410 | if t.Variadic() { |
| 411 | hash *= 971767 |
| 412 | } |
| 413 | // The Signature/Tuple recursion is always finite |
| 414 | // and invariably shallow. |
| 415 | return hash + 1062599*h.shallowHash(t.Params()) + 1282529*h.shallowHash(t.Results()) |
| 416 | |
| 417 | case *types.Tuple: |
| 418 | n := t.Len() |
| 419 | hash := 9137 + 2*uint32(n) |
| 420 | for i := range n { |
| 421 | hash += 53471161 * h.shallowHash(t.At(i).Type()) |
| 422 | } |
| 423 | return hash |
| 424 | |
| 425 | case *types.Basic: |
| 426 | return 45212177 * uint32(t.Kind()) |
| 427 | |
| 428 | case *types.Array: |
| 429 | return 1524181 + 2*uint32(t.Len()) |
| 430 | |
| 431 | case *types.Slice: |
| 432 | return 2690201 |
| 433 | |
| 434 | case *types.Struct: |
| 435 | return 3326489 |
| 436 | |
| 437 | case *types.Pointer: |
| 438 | return 4393139 |
| 439 | |
| 440 | case *types.Union: |
| 441 | return 562448657 |
| 442 | |
| 443 | case *types.Interface: |
| 444 | return 2124679 // no recursion here |
| 445 | |
| 446 | case *types.Map: |
| 447 | return 9109 |
| 448 | |
| 449 | case *types.Chan: |
| 450 | return 9127 |
| 451 | |
| 452 | case *types.Named: |
| 453 | return h.hashTypeName(t.Obj()) |
| 454 | |
| 455 | case *types.TypeParam: |
| 456 | return h.hashTypeParam(t) |
| 457 | } |
| 458 | panic(fmt.Sprintf("shallowHash: %T: %v", t, t)) |
| 459 | } |