vile / scheme / goops_weak_d_gcboehm.v
69 lines · 63 sloc · 2.34 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import arena
4
5enum GoopsWeakStorage {
6 tracing
7 arena
8 collector
9}
10
11// Heap targets use standard collector weak handles. Arena targets retain their
12// original lifetime check; resetting/freeing an arena still requires host synchronization.
13struct GoopsWeakValue {
14 value Value
15 lifetime arena.LifetimeToken
16 collector GCWeakReference
17 storage GoopsWeakStorage
18}
19
20// Callers supply validated metaobjects or callable applicability hooks. In
21// particular, arbitrary scalar Value bits must never reach the raw GC API.
22fn goops_weak(value Value) GoopsWeakValue {
23 if lifetime := arena.lifetime_token(value.pointer()) {
24 return GoopsWeakValue{ value: value, lifetime: lifetime, storage: .arena }
25 }
26 $if gcboehm_leak ? {
27 // Leak-finding deliberately keeps ordinary tracing semantics. The weak
28 // service is unavailable in this mode; never pretend this is collector weakness.
29 return GoopsWeakValue{ value: value }
30 } $else {
31 collector := unsafe { gc_weak_reference(value.pointer()) } or {
32 // A missing registry edge could bypass ownership or redefinition checks.
33 // Allocation/registration failure cannot silently publish a partial registry.
34 panic('cannot create GOOPS collector weak reference')
35 }
36 return GoopsWeakValue{
37 value: Value{ ...value, bits: ValueBits{ payload: unsafe { nil } } }
38 collector: collector
39 storage: .collector
40 }
41 }
42}
43
44@[inline]
45fn (reference &GoopsWeakValue) get() ?Value {
46 match reference.storage {
47 .tracing { return reference.value }
48 .arena {
49 if !reference.lifetime.matches(reference.value.pointer()) { return none }
50 return reference.value
51 }
52 .collector {
53 // Strengthen once under the collector lock and hold the resulting
54 // ordinary Value through use. Stored metadata contains no target pointer.
55 target := reference.collector.get()
56 if isnil(target) { return none }
57 return Value{ ...reference.value, bits: ValueBits{ payload: target } }
58 }
59 }
60}
61
62// Recycle expired ordinary-heap registry nodes too. Arena-owned targets in the
63// VM's own region cannot expire independently, so they keep the existing fast path.
64@[inline]
65fn (mut vm VM) goops_note_weak_reference(reference &GoopsWeakValue) {
66 if v_arena_current() == vm.allocation_owner && reference.storage != .collector { return }
67 vm.goops.temporary_references++
68 if vm.goops.temporary_references >= 256 { vm.goops_prune_references() }
69}
70