Skip to main content

cljrs_runtime/env/
dynamics.rs

1//! Thread-local dynamic variable binding stack.
2//!
3//! `binding` forms push a frame onto `BINDING_STACK` for the duration of their
4//! body; the RAII `BindingGuard` pops it on drop (handles both normal return
5//! and panics).
6
7use std::cell::RefCell;
8use std::collections::HashMap;
9
10use cljrs_gc::GcPtr;
11use cljrs_gc::Trace as _;
12use cljrs_value::{Value, Var};
13
14/// Opaque key for a Var in the binding stack (pointer identity).
15/// Stable because the GC is non-moving.
16pub type VarKey = usize;
17
18pub fn var_key_of(var: &GcPtr<Var>) -> VarKey {
19    var.get() as *const Var as usize
20}
21
22thread_local! {
23    static BINDING_STACK: RefCell<Vec<HashMap<VarKey, Value>>> =
24        const { RefCell::new(Vec::new()) };
25}
26
27// ── RAII guard ────────────────────────────────────────────────────────────────
28
29/// Pops the innermost binding frame when dropped.
30pub struct BindingGuard;
31
32impl Drop for BindingGuard {
33    fn drop(&mut self) {
34        pop_frame();
35    }
36}
37
38// ── Stack manipulation ────────────────────────────────────────────────────────
39
40/// Push a new dynamic binding frame; return a guard that pops it on drop.
41pub fn push_frame(bindings: HashMap<VarKey, Value>) -> BindingGuard {
42    BINDING_STACK.with(|s| s.borrow_mut().push(bindings));
43    BindingGuard
44}
45
46fn pop_frame() {
47    BINDING_STACK.with(|s| {
48        s.borrow_mut().pop();
49    });
50}
51
52// ── Lookup ────────────────────────────────────────────────────────────────────
53
54/// Check the thread-local stack first (innermost frame wins); fall back to the
55/// root binding stored in the `Var` itself.
56pub fn deref_var(var: &GcPtr<Var>) -> Option<Value> {
57    let key = var_key_of(var);
58    let tl = BINDING_STACK.with(|s| {
59        s.borrow()
60            .iter()
61            .rev()
62            .find_map(|frame| frame.get(&key).cloned())
63    });
64    tl.or_else(|| var.get().deref())
65}
66
67/// True if `var` has any thread-local binding on this thread.
68pub fn is_thread_bound(var: &GcPtr<Var>) -> bool {
69    let key = var_key_of(var);
70    BINDING_STACK.with(|s| s.borrow().iter().any(|frame| frame.contains_key(&key)))
71}
72
73/// Set the innermost thread-local binding for `var`.
74/// Returns `false` if no thread-local binding exists (caller should fall back
75/// to setting the root).
76pub fn set_thread_local(var: &GcPtr<Var>, val: Value) -> bool {
77    let key = var_key_of(var);
78    BINDING_STACK.with(|s| {
79        for frame in s.borrow_mut().iter_mut().rev() {
80            if let std::collections::hash_map::Entry::Occupied(mut e) = frame.entry(key) {
81                e.insert(val);
82                return true;
83            }
84        }
85        false
86    })
87}
88
89// ── Binding conveyance ────────────────────────────────────────────────────────
90
91/// Snapshot the current thread's entire binding stack (for conveyance into a
92/// child thread, e.g. `future`).
93pub fn capture_current() -> Vec<HashMap<VarKey, Value>> {
94    BINDING_STACK.with(|s| s.borrow().clone())
95}
96
97/// Install a previously captured snapshot on the current (new) thread.
98pub fn install_frames(frames: Vec<HashMap<VarKey, Value>>) {
99    BINDING_STACK.with(|s| *s.borrow_mut() = frames);
100}
101
102// ── GC root tracing ───────────────────────────────────────────────────────────
103
104/// Trace all values in the current thread's binding stack as GC roots.
105/// Call this during the GC root enumeration phase.
106pub fn trace_current(visitor: &mut cljrs_gc::MarkVisitor) {
107    BINDING_STACK.with(|s| {
108        for frame in s.borrow().iter() {
109            for val in frame.values() {
110                val.trace(visitor);
111            }
112        }
113    });
114}