vile / scheme / hashtable.v
488 lines · 449 sloc · 15.13 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3const hashtable_driver_names = ['hashtable-ref', 'hashtable-set!', 'hashtable-delete!',
4 'hashtable-contains?', 'hashtable-update!']!
5
6const hashtable_native_descriptors = [
7 NativeDescriptor{'make-eq-hashtable', hashtable_make_eq},
8 NativeDescriptor{'make-eqv-hashtable', hashtable_make_eqv},
9 NativeDescriptor{'make-hashtable', hashtable_make_custom},
10 NativeDescriptor{'hashtable?', hashtable_predicate},
11 NativeDescriptor{'hashtable-size', hashtable_size},
12 NativeDescriptor{'hashtable-copy', hashtable_copy},
13 NativeDescriptor{'hashtable-clear!', hashtable_clear},
14 NativeDescriptor{'hashtable-keys', hashtable_keys},
15 NativeDescriptor{'hashtable-entries', hashtable_entries},
16 NativeDescriptor{'hashtable-equivalence-function', hashtable_equivalence},
17 NativeDescriptor{'hashtable-hash-function', hashtable_hash_function},
18 NativeDescriptor{'hashtable-mutable?', hashtable_mutable},
19 NativeDescriptor{'equal-hash', hashtable_equal_hash},
20 NativeDescriptor{'string-hash', hashtable_string_hash},
21 NativeDescriptor{'string-ci-hash', hashtable_string_ci_hash},
22 NativeDescriptor{'symbol-hash', hashtable_symbol_hash},
23]!
24
25enum HashtableMode as u8 {
26 eq
27 eqv
28 custom
29}
30
31enum HashtableOperation as u8 {
32 ref
33 set
34 delete
35 contains
36 update
37}
38
39enum HashtablePhase as u8 {
40 hash
41 lookup
42 found
43 hash_wait
44 equiv_wait
45 update_wait
46}
47
48struct HashtableEntry {
49mut:
50 key Value
51 value Value
52 hash u64
53 next int = -1
54 live bool
55}
56
57@[heap]
58struct Hashtable {
59 owner &Owner
60 mode HashtableMode
61 hash_function Value
62 equivalence Value
63 mutable bool
64mut:
65 buckets map[u64]int
66 entries []HashtableEntry
67 free int = -1
68 size int
69 revision u64
70}
71
72// Only scalar progress is copied after capture. Table containers remain live
73// mutable objects; a resumed operation revalidates candidate indices by revision.
74@[heap]
75struct HashtableOperationState {
76 operation HashtableOperation
77mut:
78 phase HashtablePhase
79 hash u64
80 revision u64
81 index int = -1
82 previous int = -1
83 committing bool
84}
85
86fn (value Value) hashtable_pointer() &Hashtable { return unsafe { &Hashtable(value.pointer()) } }
87
88fn table_operation(value Value) &HashtableOperationState {
89 return unsafe { &HashtableOperationState(value.pointer()) }
90}
91
92fn (vm &VM) checked_hashtable(value Value) !&Hashtable {
93 if value.tag != .hashtable { return failure('expected a hashtable') }
94 table := value.hashtable_pointer()
95 if voidptr(table.owner) != voidptr(vm.owner) {
96 return failure('hashtable belongs to another VM')
97 }
98 return table
99}
100
101fn (vm &VM) pristine_table_predicate(name string) !Value {
102 index := vm.global_index(name)!
103 return vm.standard_original[index] or { vm.globals[index] }
104}
105
106fn hashtable_capacity(args []Value, index int) !int {
107 if args.len <= index { return 0 }
108 count := allocation_count(args[index], int(sizeof(HashtableEntry)))!
109 // V's map metadata uses u32 offsets. Reject hints outside its representable
110 // indexing range before narrowing; ordinary allocation limits still apply.
111 if u64(count) > u64(0x0fffffff) { return failure('hashtable capacity exceeds supported range') }
112 return count
113}
114
115fn new_hashtable(owner &Owner, mode HashtableMode, hash Value, equivalence Value, mutable bool, capacity int) &Hashtable {
116 mut table := &Hashtable{ owner: owner, mode: mode, hash_function: hash, equivalence: equivalence, mutable: mutable, entries: []HashtableEntry{cap: capacity} }
117 if capacity > 0 { table.buckets.reserve(u32(capacity)) }
118 return table
119}
120
121fn make_identity_hashtable(mut vm VM, args []Value, mode HashtableMode) !Value {
122 check_arity('make-${mode}-hashtable', args.len, 0, 1)!
123 equivalence := vm.pristine_table_predicate(if mode == .eq { 'eq?' } else { 'eqv?' })!
124 return payload_value(.hashtable, new_hashtable(vm.owner, mode, boolean(false), equivalence, true, hashtable_capacity(args, 0)!))
125}
126
127fn hashtable_make_eq(mut vm VM, args []Value) !Value {
128 return make_identity_hashtable(mut vm, args, .eq)
129}
130
131fn hashtable_make_eqv(mut vm VM, args []Value) !Value {
132 return make_identity_hashtable(mut vm, args, .eqv)
133}
134
135fn (vm &VM) check_hashtable_callback(value Value) ! {
136 if !value.is_callable() { return failure('hashtable callback must be a procedure') }
137 vm.check_callable_owner(value)!
138}
139
140fn hashtable_make_custom(mut vm VM, args []Value) !Value {
141 check_arity('make-hashtable', args.len, 2, 3)!
142 vm.check_hashtable_callback(args[0])!
143 vm.check_hashtable_callback(args[1])!
144 return payload_value(.hashtable, new_hashtable(vm.owner, .custom, args[0], args[1], true, hashtable_capacity(args, 2)!))
145}
146
147fn (mut vm VM) install_hashtable_primitives() {
148 for operation in 0 .. hashtable_driver_names.len {
149 entry := &hashtable_driver_names[operation]
150 arity := if operation == int(HashtableOperation.update) {
151 4
152 } else if operation in [int(HashtableOperation.ref), int(HashtableOperation.set)] {
153 3
154 } else {
155 2
156 }
157 function := &Function{
158 code: unsafe { nil }
159 params: arity
160 slot_count: 6
161 instructions: [
162 bridge_instruction(.hashtable_init, operation, 0),
163 bridge_instruction(.hashtable_step, 0, 0),
164 bridge_instruction(.hashtable_collect, 0, 0),
165 bridge_instruction(.jump, 1, 0),
166 ]
167 }
168 bridge := procedure_value(&Procedure{ owner: vm.owner, mode: .closure, name: *entry, function: function })
169 vm.bind_global(*entry, procedure_value(&Procedure{ owner: vm.owner, mode: .hashtable, name: *entry, function: function, env: &Environment{ slots: [bridge] } }))
170 }
171 for index in 0 .. hashtable_native_descriptors.len {
172 entry := &hashtable_native_descriptors[index]
173 vm.bind_global(entry.name, procedure_value(&Procedure{ owner: vm.owner, mode: .native, name: entry.name, native: entry.callback }))
174 }
175}
176
177fn hashtable_callback_extent(function &Function, env &Environment, table &Hashtable) bool {
178 if isnil(function) || !isnil(function.code) || function.instructions.len == 0 || function.instructions[0].op != .hashtable_init || isnil(env) || env.slots[5].tag != .hashtable_operation {
179 return false
180 }
181 state := table_operation(env.slots[5])
182 return state.phase in [.hash_wait, .equiv_wait, .update_wait] && env.slots[0].pointer() == voidptr(table)
183}
184
185fn (vm &VM) check_hashtable_mutation(table &Hashtable) ! {
186 if !table.mutable { return failure('cannot modify an immutable hashtable') }
187 // Eq/eqv operations remain scan-free. Updater purity is a documented
188 // precondition there; a fresh commit lookup still protects storage safety.
189 if table.mode != .custom { return }
190 for machine in vm.active {
191 if hashtable_callback_extent(machine.function, machine.env, table) {
192 return failure('hashtable callback must not mutate its table')
193 }
194 for frame in machine.frames {
195 if hashtable_callback_extent(frame.function, frame.env, table) {
196 return failure('hashtable callback must not mutate its table')
197 }
198 }
199 }
200}
201
202fn (mut table Hashtable) store(hash u64, key Value, value Value, index int) {
203 if index >= 0 {
204 table.entries[index].value = value
205 } else {
206 entry := HashtableEntry{ key: key, value: value, hash: hash, next: table.buckets[hash] or { -1 }, live: true }
207 mut slot := table.free
208 if slot >= 0 {
209 table.free = table.entries[slot].next
210 container_store(mut table.entries, slot, entry)
211 } else {
212 slot = table.entries.len
213 table.entries << entry
214 }
215 table.buckets[hash] = slot
216 table.size++
217 }
218 table.revision++
219}
220
221fn (mut table Hashtable) remove(hash u64, index int, previous int) {
222 if index < 0 { return }
223 next := table.entries[index].next
224 if previous >= 0 {
225 table.entries[previous].next = next
226 } else if next >= 0 {
227 table.buckets[hash] = next
228 } else {
229 table.buckets.delete(hash)
230 }
231 // Clear both scanned handles before the slot enters the private free chain.
232 container_store(mut table.entries, index, HashtableEntry{ next: table.free })
233 table.free = index
234 table.size--
235 table.revision++
236}
237
238fn (mut state HashtableOperationState) begin_lookup(table &Hashtable) {
239 state.phase = .lookup
240 state.revision = table.revision
241 state.index = table.buckets[state.hash] or { -1 }
242 state.previous = -1
243}
244
245fn (mut vm VM) charge_hashtable() ! {
246 if vm.active.len > 0 { vm.active.last().charge(vm.options.max_steps)! }
247}
248
249fn hashtable_fast(mut vm VM, operation HashtableOperation, table &Hashtable, args []Value) !Value {
250 hash := identity_key_hash(args[1])
251 mut index := table.buckets[hash] or { -1 }
252 mut previous := -1
253 for index >= 0 {
254 vm.charge_hashtable()!
255 entry := table.entries[index]
256 if eqv(args[1], entry.key) { break }
257 previous = index
258 index = entry.next
259 }
260 match operation {
261 .ref { return if index >= 0 { table.entries[index].value } else { args[2] } }
262 .contains { return boolean(index >= 0) }
263 .set {
264 mut target := unsafe { &Hashtable(table) }
265 target.store(hash, args[1], args[2], index)
266 }
267 .delete {
268 mut target := unsafe { &Hashtable(table) }
269 target.remove(hash, index, previous)
270 }
271 .update { return failure('invalid native hashtable update') }
272 }
273 return unspecified()
274}
275
276@[direct_array_access]
277fn (mut m Machine) start_hashtable(operation HashtableOperation) ! {
278 table := m.env.slots[0].hashtable_pointer()
279 if operation == .update {
280 // Public update arguments are (table key proc default).
281 procedure := m.env.slots[2]
282 m.env.slots[2] = m.env.slots[3]
283 m.env.slots[3] = procedure
284 } else {
285 m.env.slots[3] = unspecified()
286 }
287 mut state := &HashtableOperationState{ operation: operation }
288 if table.mode == .custom {
289 state.phase = .hash
290 } else {
291 state.hash = identity_key_hash(m.env.slots[1])
292 state.begin_lookup(table)
293 }
294 m.env.slots[5] = payload_value(.hashtable_operation, state)
295}
296
297@[direct_array_access]
298fn (mut m Machine) step_hashtable(mut vm VM) ! {
299 mut state := table_operation(m.env.slots[5])
300 table := m.env.slots[0].hashtable_pointer()
301 if state.phase == .hash {
302 state.phase = .hash_wait
303 m.push(table.hash_function)
304 m.push(m.env.slots[1])
305 m.apply(mut vm, 1, false)!
306 return
307 }
308 if state.phase == .lookup {
309 for state.index >= 0 {
310 m.charge(vm.options.max_steps)!
311 entry := table.entries[state.index]
312 if table.mode == .custom {
313 m.env.slots[4] = entry.key
314 state.phase = .equiv_wait
315 m.push(table.equivalence)
316 m.push(m.env.slots[1])
317 m.push(entry.key)
318 m.apply(mut vm, 2, false)!
319 return
320 }
321 if eqv(m.env.slots[1], entry.key) { break }
322 state.previous = state.index
323 state.index = entry.next
324 }
325 state.phase = .found
326 }
327 if state.phase != .found { return failure('invalid hashtable bridge phase') }
328 if state.operation == .update && !state.committing {
329 state.phase = .update_wait
330 m.push(m.env.slots[3])
331 m.push(if state.index >= 0 { table.entries[state.index].value } else { m.env.slots[2] })
332 m.apply(mut vm, 1, false)!
333 return
334 }
335 match state.operation {
336 .ref {
337 m.finish_call(if state.index >= 0 {
338 table.entries[state.index].value
339 } else {
340 m.env.slots[2]
341 })
342 }
343 .contains { m.finish_call(boolean(state.index >= 0)) }
344 .set, .update {
345 mut target := m.env.slots[0].hashtable_pointer()
346 target.store(state.hash, m.env.slots[1], m.env.slots[2], state.index)
347 m.finish_call(unspecified())
348 }
349 .delete {
350 mut target := m.env.slots[0].hashtable_pointer()
351 target.remove(state.hash, state.index, state.previous)
352 m.finish_call(unspecified())
353 }
354 }
355}
356
357@[direct_array_access]
358fn (mut m Machine) collect_hashtable() ! {
359 result := m.pop_value()
360 if result.tag == .multiple { return failure('hashtable callback must return one value') }
361 mut state := table_operation(m.env.slots[5])
362 if m.env.escaped {
363 mut scope := m.detach_bridge()
364 state = &HashtableOperationState{ ...state }
365 scope.slots[5] = payload_value(.hashtable_operation, state)
366 }
367 table := m.env.slots[0].hashtable_pointer()
368 match state.phase {
369 .hash_wait {
370 state.hash = hashtable_callback_hash(result)!
371 state.begin_lookup(table)
372 }
373 .equiv_wait {
374 m.env.slots[4] = unspecified()
375 if state.revision != table.revision {
376 // A saved callback can resume after mutations outside its dynamic
377 // extent. Discard the stale candidate answer, not the continuation.
378 state.begin_lookup(table)
379 } else if result.is_true() {
380 state.phase = .found
381 } else {
382 state.previous = state.index
383 state.index = table.entries[state.index].next
384 state.phase = .lookup
385 }
386 }
387 .update_wait {
388 m.env.slots[2] = result
389 state.committing = true
390 // Equivalent to a new set! lookup. Never rerun the updater when a
391 // continuation supplies another return value or table contents changed.
392 state.begin_lookup(table)
393 }
394 else { return failure('invalid hashtable callback return') }
395 }
396}
397
398fn hashtable_predicate(mut _vm VM, args []Value) !Value {
399 check_arity('hashtable?', args.len, 1, 1)!
400 return boolean(args[0].tag == .hashtable)
401}
402
403fn hashtable_size(mut vm VM, args []Value) !Value {
404 check_arity('hashtable-size', args.len, 1, 1)!
405 return integer(i64(vm.checked_hashtable(args[0])!.size))
406}
407
408fn hashtable_mutable(mut vm VM, args []Value) !Value {
409 check_arity('hashtable-mutable?', args.len, 1, 1)!
410 return boolean(vm.checked_hashtable(args[0])!.mutable)
411}
412
413fn hashtable_equivalence(mut vm VM, args []Value) !Value {
414 check_arity('hashtable-equivalence-function', args.len, 1, 1)!
415 return vm.checked_hashtable(args[0])!.equivalence
416}
417
418fn hashtable_hash_function(mut vm VM, args []Value) !Value {
419 check_arity('hashtable-hash-function', args.len, 1, 1)!
420 return vm.checked_hashtable(args[0])!.hash_function
421}
422
423fn hashtable_copy(mut vm VM, args []Value) !Value {
424 check_arity('hashtable-copy', args.len, 1, 2)!
425 table := vm.checked_hashtable(args[0])!
426 mut result_table := new_hashtable(vm.owner, table.mode, table.hash_function, table.equivalence, args.len == 2 && args[1].is_true(), table.size)
427 for entry in table.entries {
428 if entry.live { result_table.store(entry.hash, entry.key, entry.value, -1) }
429 }
430 return payload_value(.hashtable, result_table)
431}
432
433fn hashtable_clear(mut vm VM, args []Value) !Value {
434 check_arity('hashtable-clear!', args.len, 1, 2)!
435 mut table := vm.checked_hashtable(args[0])!
436 vm.check_hashtable_mutation(table)!
437 capacity := hashtable_capacity(args, 1)!
438 for i in 0 .. table.entries.len {
439 container_store_validated(mut table.entries, i, HashtableEntry{})
440 }
441 if args.len == 2 {
442 table.entries = []HashtableEntry{cap: capacity}
443 table.buckets = map[u64]int{}
444 if capacity > 0 { table.buckets.reserve(u32(capacity)) }
445 } else {
446 unsafe { table.entries.len = 0 }
447 table.buckets.clear()
448 }
449 table.free = -1
450 table.size = 0
451 table.revision++
452 return unspecified()
453}
454
455fn hashtable_keys(mut vm VM, args []Value) !Value {
456 check_arity('hashtable-keys', args.len, 1, 1)!
457 table := vm.checked_hashtable(args[0])!
458 mut keys := value_storage(table.size)
459 mut index := 0
460 for entry in table.entries {
461 if entry.live {
462 container_store_validated(mut keys, index, entry.key)
463 index++
464 }
465 }
466 return payload_value(.vector, &Vector{ items: keys })
467}
468
469fn hashtable_entries(mut vm VM, args []Value) !Value {
470 check_arity('hashtable-entries', args.len, 1, 1)!
471 table := vm.checked_hashtable(args[0])!
472 mut keys := value_storage(table.size)
473 mut entry_values := value_storage(table.size)
474 mut index := 0
475 for entry in table.entries {
476 if entry.live {
477 container_store_validated(mut keys, index, entry.key)
478 container_store_validated(mut entry_values, index, entry.value)
479 index++
480 }
481 }
482 return payload_value(.multiple, &Vector{
483 items: [
484 payload_value(.vector, &Vector{ items: keys }),
485 payload_value(.vector, &Vector{ items: entry_values }),
486 ]
487 })
488}
489