| 1 |
// Copyright 2017 The Bazel 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 starlark |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"hash/maphash" |
| 10 |
"math/big" |
| 11 |
"os" |
| 12 |
) |
| 13 |
|
| 14 |
// hashtable is used to represent Starlark dict and set values. |
| 15 |
// It is a hash table whose key/value entries form a doubly-linked list |
| 16 |
// in the order the entries were inserted. |
| 17 |
// |
| 18 |
// Initialized instances of hashtable must not be copied. |
| 19 |
type hashtable struct { |
| 20 |
table []bucket // len is zero or a power of two |
| 21 |
bucket0 [1]bucket // inline allocation for small maps. |
| 22 |
len uint32 |
| 23 |
itercount uint32 // number of active iterators (ignored if frozen) |
| 24 |
head *entry // insertion order doubly-linked list; may be nil |
| 25 |
tailLink **entry // address of nil link at end of list (perhaps &head) |
| 26 |
frozen bool |
| 27 |
|
| 28 |
_ noCopy // triggers vet copylock check on this type. |
| 29 |
} |
| 30 |
|
| 31 |
// noCopy is zero-sized type that triggers vet's copylock check. |
| 32 |
// See https://github.com/golang/go/issues/8005#issuecomment-190753527. |
| 33 |
type noCopy struct{} |
| 34 |
|
| 35 |
func (*noCopy) Lock() {} |
| 36 |
func (*noCopy) Unlock() {} |
| 37 |
|
| 38 |
const bucketSize = 8 |
| 39 |
|
| 40 |
type bucket struct { |
| 41 |
entries [bucketSize]entry |
| 42 |
next *bucket // linked list of buckets |
| 43 |
} |
| 44 |
|
| 45 |
type entry struct { |
| 46 |
hash uint32 // nonzero => in use |
| 47 |
key, value Value |
| 48 |
next *entry // insertion order doubly-linked list; may be nil |
| 49 |
prevLink **entry // address of link to this entry (perhaps &head) |
| 50 |
} |
| 51 |
|
| 52 |
func (ht *hashtable) init(size int) { |
| 53 |
if size < 0 { |
| 54 |
panic("size < 0") |
| 55 |
} |
| 56 |
nb := 1 |
| 57 |
for overloaded(size, nb) { |
| 58 |
nb = nb << 1 |
| 59 |
} |
| 60 |
if nb < 2 { |
| 61 |
ht.table = ht.bucket0[:1] |
| 62 |
} else { |
| 63 |
ht.table = make([]bucket, nb) |
| 64 |
} |
| 65 |
ht.tailLink = &ht.head |
| 66 |
} |
| 67 |
|
| 68 |
func (ht *hashtable) freeze() { |
| 69 |
if !ht.frozen { |
| 70 |
ht.frozen = true |
| 71 |
for e := ht.head; e != nil; e = e.next { |
| 72 |
e.key.Freeze() |
| 73 |
e.value.Freeze() |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
func (ht *hashtable) insert(k, v Value) error { |
| 79 |
if err := ht.checkMutable("insert into"); err != nil { |
| 80 |
return err |
| 81 |
} |
| 82 |
if ht.table == nil { |
| 83 |
ht.init(1) |
| 84 |
} |
| 85 |
h, err := k.Hash() |
| 86 |
if err != nil { |
| 87 |
return err |
| 88 |
} |
| 89 |
if h == 0 { |
| 90 |
h = 1 // zero is reserved |
| 91 |
} |
| 92 |
|
| 93 |
retry: |
| 94 |
var insert *entry |
| 95 |
|
| 96 |
// Inspect each bucket in the bucket list. |
| 97 |
p := &ht.table[h&(uint32(len(ht.table)-1))] |
| 98 |
for { |
| 99 |
for i := range p.entries { |
| 100 |
e := &p.entries[i] |
| 101 |
if e.hash != h { |
| 102 |
if e.hash == 0 { |
| 103 |
// Found empty entry; make a note. |
| 104 |
insert = e |
| 105 |
} |
| 106 |
continue |
| 107 |
} |
| 108 |
if eq, err := Equal(k, e.key); err != nil { |
| 109 |
return err // e.g. excessively recursive tuple |
| 110 |
} else if !eq { |
| 111 |
continue |
| 112 |
} |
| 113 |
// Key already present; update value. |
| 114 |
e.value = v |
| 115 |
return nil |
| 116 |
} |
| 117 |
if p.next == nil { |
| 118 |
break |
| 119 |
} |
| 120 |
p = p.next |
| 121 |
} |
| 122 |
|
| 123 |
// Key not found. p points to the last bucket. |
| 124 |
|
| 125 |
// Does the number of elements exceed the buckets' load factor? |
| 126 |
if overloaded(int(ht.len), len(ht.table)) { |
| 127 |
ht.grow() |
| 128 |
goto retry |
| 129 |
} |
| 130 |
|
| 131 |
if insert == nil { |
| 132 |
// No space in existing buckets. Add a new one to the bucket list. |
| 133 |
b := new(bucket) |
| 134 |
p.next = b |
| 135 |
insert = &b.entries[0] |
| 136 |
} |
| 137 |
|
| 138 |
// Insert key/value pair. |
| 139 |
insert.hash = h |
| 140 |
insert.key = k |
| 141 |
insert.value = v |
| 142 |
|
| 143 |
// Append entry to doubly-linked list. |
| 144 |
insert.prevLink = ht.tailLink |
| 145 |
*ht.tailLink = insert |
| 146 |
ht.tailLink = &insert.next |
| 147 |
|
| 148 |
ht.len++ |
| 149 |
|
| 150 |
return nil |
| 151 |
} |
| 152 |
|
| 153 |
func overloaded(elems, buckets int) bool { |
| 154 |
const loadFactor = 6.5 // just a guess |
| 155 |
return elems >= bucketSize && float64(elems) >= loadFactor*float64(buckets) |
| 156 |
} |
| 157 |
|
| 158 |
func (ht *hashtable) grow() { |
| 159 |
// Double the number of buckets and rehash. |
| 160 |
// |
| 161 |
// Even though this makes reentrant calls to ht.insert, |
| 162 |
// calls Equals unnecessarily (since there can't be duplicate keys), |
| 163 |
// and recomputes the hash unnecessarily, the gains from |
| 164 |
// avoiding these steps were found to be too small to justify |
| 165 |
// the extra logic: -2% on hashtable benchmark. |
| 166 |
ht.table = make([]bucket, len(ht.table)<<1) |
| 167 |
oldhead := ht.head |
| 168 |
ht.head = nil |
| 169 |
ht.tailLink = &ht.head |
| 170 |
ht.len = 0 |
| 171 |
for e := oldhead; e != nil; e = e.next { |
| 172 |
ht.insert(e.key, e.value) // can't fail |
| 173 |
} |
| 174 |
ht.bucket0[0] = bucket{} // clear out unused initial bucket |
| 175 |
} |
| 176 |
|
| 177 |
func (ht *hashtable) lookup(k Value) (v Value, found bool, err error) { |
| 178 |
h, err := k.Hash() |
| 179 |
if err != nil { |
| 180 |
return nil, false, err // unhashable |
| 181 |
} |
| 182 |
if h == 0 { |
| 183 |
h = 1 // zero is reserved |
| 184 |
} |
| 185 |
if ht.table == nil { |
| 186 |
return None, false, nil // empty |
| 187 |
} |
| 188 |
|
| 189 |
// Inspect each bucket in the bucket list. |
| 190 |
for p := &ht.table[h&(uint32(len(ht.table)-1))]; p != nil; p = p.next { |
| 191 |
for i := range p.entries { |
| 192 |
e := &p.entries[i] |
| 193 |
if e.hash == h { |
| 194 |
if eq, err := Equal(k, e.key); err != nil { |
| 195 |
return nil, false, err // e.g. excessively recursive tuple |
| 196 |
} else if eq { |
| 197 |
return e.value, true, nil // found |
| 198 |
} |
| 199 |
} |
| 200 |
} |
| 201 |
} |
| 202 |
return None, false, nil // not found |
| 203 |
} |
| 204 |
|
| 205 |
// count returns the number of distinct elements of iter that are elements of ht. |
| 206 |
func (ht *hashtable) count(iter Iterator) (int, error) { |
| 207 |
if ht.table == nil { |
| 208 |
return 0, nil // empty |
| 209 |
} |
| 210 |
|
| 211 |
var k Value |
| 212 |
count := 0 |
| 213 |
|
| 214 |
// Use a bitset per table entry to record seen elements of ht. |
| 215 |
// Elements are identified by their bucket number and index within the bucket. |
| 216 |
// Each bitset gets one word initially, but may grow. |
| 217 |
storage := make([]big.Word, len(ht.table)) |
| 218 |
bitsets := make([]big.Int, len(ht.table)) |
| 219 |
for i := range bitsets { |
| 220 |
bitsets[i].SetBits(storage[i : i+1 : i+1]) |
| 221 |
} |
| 222 |
for iter.Next(&k) && count != int(ht.len) { |
| 223 |
h, err := k.Hash() |
| 224 |
if err != nil { |
| 225 |
return 0, err // unhashable |
| 226 |
} |
| 227 |
if h == 0 { |
| 228 |
h = 1 // zero is reserved |
| 229 |
} |
| 230 |
|
| 231 |
// Inspect each bucket in the bucket list. |
| 232 |
bucketId := h & (uint32(len(ht.table) - 1)) |
| 233 |
i := 0 |
| 234 |
for p := &ht.table[bucketId]; p != nil; p = p.next { |
| 235 |
for j := range p.entries { |
| 236 |
e := &p.entries[j] |
| 237 |
if e.hash == h { |
| 238 |
if eq, err := Equal(k, e.key); err != nil { |
| 239 |
return 0, err |
| 240 |
} else if eq { |
| 241 |
bitIndex := i<<3 + j |
| 242 |
if bitsets[bucketId].Bit(bitIndex) == 0 { |
| 243 |
bitsets[bucketId].SetBit(&bitsets[bucketId], bitIndex, 1) |
| 244 |
count++ |
| 245 |
} |
| 246 |
} |
| 247 |
} |
| 248 |
} |
| 249 |
i++ |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
return count, nil |
| 254 |
} |
| 255 |
|
| 256 |
// Items returns all the items in the map (as key/value pairs) in insertion order. |
| 257 |
func (ht *hashtable) items() []Tuple { |
| 258 |
items := make([]Tuple, 0, ht.len) |
| 259 |
array := make([]Value, ht.len*2) // allocate a single backing array |
| 260 |
for e := ht.head; e != nil; e = e.next { |
| 261 |
pair := Tuple(array[:2:2]) |
| 262 |
array = array[2:] |
| 263 |
pair[0] = e.key |
| 264 |
pair[1] = e.value |
| 265 |
items = append(items, pair) |
| 266 |
} |
| 267 |
return items |
| 268 |
} |
| 269 |
|
| 270 |
func (ht *hashtable) first() (Value, bool) { |
| 271 |
if ht.head != nil { |
| 272 |
return ht.head.key, true |
| 273 |
} |
| 274 |
return None, false |
| 275 |
} |
| 276 |
|
| 277 |
func (ht *hashtable) keys() []Value { |
| 278 |
keys := make([]Value, 0, ht.len) |
| 279 |
for e := ht.head; e != nil; e = e.next { |
| 280 |
keys = append(keys, e.key) |
| 281 |
} |
| 282 |
return keys |
| 283 |
} |
| 284 |
|
| 285 |
func (ht *hashtable) delete(k Value) (v Value, found bool, err error) { |
| 286 |
if err := ht.checkMutable("delete from"); err != nil { |
| 287 |
return nil, false, err |
| 288 |
} |
| 289 |
if ht.table == nil { |
| 290 |
return None, false, nil // empty |
| 291 |
} |
| 292 |
h, err := k.Hash() |
| 293 |
if err != nil { |
| 294 |
return nil, false, err // unhashable |
| 295 |
} |
| 296 |
if h == 0 { |
| 297 |
h = 1 // zero is reserved |
| 298 |
} |
| 299 |
|
| 300 |
// Inspect each bucket in the bucket list. |
| 301 |
for p := &ht.table[h&(uint32(len(ht.table)-1))]; p != nil; p = p.next { |
| 302 |
for i := range p.entries { |
| 303 |
e := &p.entries[i] |
| 304 |
if e.hash == h { |
| 305 |
if eq, err := Equal(k, e.key); err != nil { |
| 306 |
return nil, false, err |
| 307 |
} else if eq { |
| 308 |
// Remove e from doubly-linked list. |
| 309 |
*e.prevLink = e.next |
| 310 |
if e.next == nil { |
| 311 |
ht.tailLink = e.prevLink // deletion of last entry |
| 312 |
} else { |
| 313 |
e.next.prevLink = e.prevLink |
| 314 |
} |
| 315 |
|
| 316 |
v := e.value |
| 317 |
*e = entry{} |
| 318 |
ht.len-- |
| 319 |
return v, true, nil // found |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
} |
| 324 |
|
| 325 |
// TODO(adonovan): opt: remove completely empty bucket from bucket list. |
| 326 |
|
| 327 |
return None, false, nil // not found |
| 328 |
} |
| 329 |
|
| 330 |
// checkMutable reports an error if the hash table should not be mutated. |
| 331 |
// verb+" dict" should describe the operation. |
| 332 |
func (ht *hashtable) checkMutable(verb string) error { |
| 333 |
if ht.frozen { |
| 334 |
return fmt.Errorf("cannot %s frozen hash table", verb) |
| 335 |
} |
| 336 |
if ht.itercount > 0 { |
| 337 |
return fmt.Errorf("cannot %s hash table during iteration", verb) |
| 338 |
} |
| 339 |
return nil |
| 340 |
} |
| 341 |
|
| 342 |
func (ht *hashtable) clear() error { |
| 343 |
if err := ht.checkMutable("clear"); err != nil { |
| 344 |
return err |
| 345 |
} |
| 346 |
if ht.table != nil { |
| 347 |
for i := range ht.table { |
| 348 |
ht.table[i] = bucket{} |
| 349 |
} |
| 350 |
} |
| 351 |
ht.head = nil |
| 352 |
ht.tailLink = &ht.head |
| 353 |
ht.len = 0 |
| 354 |
return nil |
| 355 |
} |
| 356 |
|
| 357 |
func (ht *hashtable) addAll(other *hashtable) error { |
| 358 |
for e := other.head; e != nil; e = e.next { |
| 359 |
if err := ht.insert(e.key, e.value); err != nil { |
| 360 |
return err |
| 361 |
} |
| 362 |
} |
| 363 |
return nil |
| 364 |
} |
| 365 |
|
| 366 |
// dump is provided as an aid to debugging. |
| 367 |
func (ht *hashtable) dump() { |
| 368 |
fmt.Fprintf(os.Stderr, "hashtable %p len=%d head=%p tailLink=%p", |
| 369 |
ht, ht.len, ht.head, ht.tailLink) |
| 370 |
if ht.tailLink != nil { |
| 371 |
fmt.Fprintf(os.Stderr, " *tailLink=%p", *ht.tailLink) |
| 372 |
} |
| 373 |
fmt.Fprintln(os.Stderr) |
| 374 |
for j := range ht.table { |
| 375 |
fmt.Fprintf(os.Stderr, "bucket chain %d\n", j) |
| 376 |
for p := &ht.table[j]; p != nil; p = p.next { |
| 377 |
fmt.Fprintf(os.Stderr, "bucket %p\n", p) |
| 378 |
for i := range p.entries { |
| 379 |
e := &p.entries[i] |
| 380 |
fmt.Fprintf(os.Stderr, "\tentry %d @ %p hash=%d key=%v value=%v\n", |
| 381 |
i, e, e.hash, e.key, e.value) |
| 382 |
fmt.Fprintf(os.Stderr, "\t\tnext=%p &next=%p prev=%p", |
| 383 |
e.next, &e.next, e.prevLink) |
| 384 |
if e.prevLink != nil { |
| 385 |
fmt.Fprintf(os.Stderr, " *prev=%p", *e.prevLink) |
| 386 |
} |
| 387 |
fmt.Fprintln(os.Stderr) |
| 388 |
} |
| 389 |
} |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
func (ht *hashtable) iterate() *keyIterator { |
| 394 |
if !ht.frozen { |
| 395 |
ht.itercount++ |
| 396 |
} |
| 397 |
return &keyIterator{ht: ht, e: ht.head} |
| 398 |
} |
| 399 |
|
| 400 |
type keyIterator struct { |
| 401 |
ht *hashtable |
| 402 |
e *entry |
| 403 |
} |
| 404 |
|
| 405 |
func (it *keyIterator) Next(k *Value) bool { |
| 406 |
if it.e != nil { |
| 407 |
*k = it.e.key |
| 408 |
it.e = it.e.next |
| 409 |
return true |
| 410 |
} |
| 411 |
return false |
| 412 |
} |
| 413 |
|
| 414 |
func (it *keyIterator) Done() { |
| 415 |
if !it.ht.frozen { |
| 416 |
it.ht.itercount-- |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
// entries is a go1.23 iterator over the entries of the hash table. |
| 421 |
func (ht *hashtable) entries(yield func(k, v Value) bool) { |
| 422 |
if !ht.frozen { |
| 423 |
ht.itercount++ |
| 424 |
defer func() { ht.itercount-- }() |
| 425 |
} |
| 426 |
for e := ht.head; e != nil && yield(e.key, e.value); e = e.next { |
| 427 |
} |
| 428 |
} |
| 429 |
|
| 430 |
var seed = maphash.MakeSeed() |
| 431 |
|
| 432 |
// hashString computes the hash of s. |
| 433 |
func hashString(s string) uint32 { |
| 434 |
if len(s) >= 12 { |
| 435 |
// Call the Go runtime's optimized hash implementation, |
| 436 |
// which uses the AES instructions on amd64 and arm64 machines. |
| 437 |
h := maphash.String(seed, s) |
| 438 |
return uint32(h>>32) ^ uint32(h) |
| 439 |
} |
| 440 |
return softHashString(s) |
| 441 |
} |
| 442 |
|
| 443 |
// softHashString computes the 32-bit FNV-1a hash of s in software. |
| 444 |
func softHashString(s string) uint32 { |
| 445 |
var h uint32 = 2166136261 |
| 446 |
for i := 0; i < len(s); i++ { |
| 447 |
h ^= uint32(s[i]) |
| 448 |
h *= 16777619 |
| 449 |
} |
| 450 |
return h |
| 451 |
} |