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
46/// Pop the frame `guard` owns and hand it back, so a caller that yields between
47/// uses (the async evaluator) can keep a `binding` frame off the thread-local
48/// stack while other tasks on the same thread run, and push it again later.
49/// Must be called with the innermost frame's guard.
50pub fn take_frame(guard: BindingGuard) -> HashMap<VarKey, Value> {
51 std::mem::forget(guard);
52 BINDING_STACK.with(|s| s.borrow_mut().pop().unwrap_or_default())
53}
54
55fn pop_frame() {
56 BINDING_STACK.with(|s| {
57 s.borrow_mut().pop();
58 });
59}
60
61// ── Lookup ────────────────────────────────────────────────────────────────────
62
63/// Check the thread-local stack first (innermost frame wins); fall back to the
64/// root binding stored in the `Var` itself.
65pub fn deref_var(var: &GcPtr<Var>) -> Option<Value> {
66 let key = var_key_of(var);
67 let tl = BINDING_STACK.with(|s| {
68 s.borrow()
69 .iter()
70 .rev()
71 .find_map(|frame| frame.get(&key).cloned())
72 });
73 tl.or_else(|| var.get().deref())
74}
75
76/// True if `var` has any thread-local binding on this thread.
77pub fn is_thread_bound(var: &GcPtr<Var>) -> bool {
78 let key = var_key_of(var);
79 BINDING_STACK.with(|s| s.borrow().iter().any(|frame| frame.contains_key(&key)))
80}
81
82/// Set the innermost thread-local binding for `var`.
83/// Returns `false` if no thread-local binding exists (caller should fall back
84/// to setting the root).
85pub fn set_thread_local(var: &GcPtr<Var>, val: Value) -> bool {
86 let key = var_key_of(var);
87 BINDING_STACK.with(|s| {
88 for frame in s.borrow_mut().iter_mut().rev() {
89 if let std::collections::hash_map::Entry::Occupied(mut e) = frame.entry(key) {
90 e.insert(val);
91 return true;
92 }
93 }
94 false
95 })
96}
97
98// ── Binding conveyance ────────────────────────────────────────────────────────
99
100/// Snapshot the current thread's entire binding stack (for conveyance into a
101/// child thread, e.g. `future`).
102pub fn capture_current() -> Vec<HashMap<VarKey, Value>> {
103 BINDING_STACK.with(|s| s.borrow().clone())
104}
105
106/// Install a previously captured snapshot on the current (new) thread.
107pub fn install_frames(frames: Vec<HashMap<VarKey, Value>>) {
108 BINDING_STACK.with(|s| *s.borrow_mut() = frames);
109}
110
111// ── GC root tracing ───────────────────────────────────────────────────────────
112
113/// Trace all values in the current thread's binding stack as GC roots.
114/// Call this during the GC root enumeration phase.
115pub fn trace_current(visitor: &mut cljrs_gc::MarkVisitor) {
116 BINDING_STACK.with(|s| {
117 for frame in s.borrow().iter() {
118 for val in frame.values() {
119 val.trace(visitor);
120 }
121 }
122 });
123}