1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
//! Lexical environments (scope chains) for the tree-walker over the new model
//! (`ROADMAP.md` ยง3 โ Phase D migration, the function/closure piece).
//!
//! A `Scope` is a reference-counted frame of `name โ `[`NanBox`] bindings with
//! a link to its enclosing scope. A function **closes over** the scope it was
//! defined in by keeping an `Rc` to it, so its captured variables stay live and
//! shared after the defining call returns โ the property a flat stack of scopes
//! cannot provide. Resolution walks the parent chain inner-first.
//!
//! Bindings hold only [`NanBox`] values (heap references are handles), so a
//! scope is `'static` and the GC can trace a closure's captured handles via
//! `Scope::for_each_handle`.
//!
//! [`NanBox`]: crate::nanbox::NanBox
//!
//! Pure, safe `alloc`-only Rust.
use crate::heap::Handle;
use crate::nanbox::NanBox;
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::string::String;
use core::cell::RefCell;
/// A reference-counted lexical scope: its own bindings plus a link to the
/// enclosing scope. Cloning shares the same frame (closures capture by sharing).
#[derive(Clone)]
pub struct Scope(Rc<RefCell<ScopeData>>);
struct ScopeData {
vars: BTreeMap<String, NanBox>,
/// Names declared `const` in this frame (reassignment is a TypeError).
consts: alloc::collections::BTreeSet<String>,
parent: Option<Scope>,
}
impl Scope {
/// A new root scope (no parent).
#[must_use]
pub fn root() -> Self {
Scope(Rc::new(RefCell::new(ScopeData {
vars: BTreeMap::new(),
consts: alloc::collections::BTreeSet::new(),
parent: None,
})))
}
/// A new child scope nested inside `self`.
#[must_use]
pub fn child(&self) -> Self {
Scope(Rc::new(RefCell::new(ScopeData {
vars: BTreeMap::new(),
consts: alloc::collections::BTreeSet::new(),
parent: Some(self.clone()),
})))
}
/// Declares (or redeclares) `name` in *this* scope.
pub fn declare(&self, name: &str, value: NanBox) {
self.0.borrow_mut().vars.insert(String::from(name), value);
}
/// Declares `name` as a `const` binding in *this* scope (reassignment fails).
pub fn declare_const(&self, name: &str, value: NanBox) {
let mut data = self.0.borrow_mut();
data.vars.insert(String::from(name), value);
data.consts.insert(String::from(name));
}
/// Whether the nearest binding of `name` was declared `const`.
#[must_use]
pub fn is_const(&self, name: &str) -> bool {
let data = self.0.borrow();
if data.vars.contains_key(name) {
return data.consts.contains(name);
}
data.parent.as_ref().is_some_and(|p| p.is_const(name))
}
/// Whether `name` is bound in *this* scope (not the enclosing chain).
#[must_use]
pub fn has_local(&self, name: &str) -> bool {
self.0.borrow().vars.contains_key(name)
}
/// Looks up `name`, walking outward through enclosing scopes.
#[must_use]
pub fn get(&self, name: &str) -> Option<NanBox> {
let data = self.0.borrow();
if let Some(v) = data.vars.get(name) {
return Some(*v);
}
data.parent.as_ref().and_then(|p| p.get(name))
}
/// Assigns to the nearest existing binding of `name`; returns `false` if it
/// is not declared anywhere in the chain.
pub fn set(&self, name: &str, value: NanBox) -> bool {
let mut data = self.0.borrow_mut();
if let Some(slot) = data.vars.get_mut(name) {
*slot = value;
return true;
}
match &data.parent {
Some(p) => p.set(name, value),
None => false,
}
}
/// This frame's own `(name, value, is_const)` bindings (not the parent
/// chain) โ for snapshotting a closure's captured environment.
#[must_use]
pub fn local_bindings(&self) -> alloc::vec::Vec<(String, NanBox, bool)> {
let data = self.0.borrow();
data.vars
.iter()
.map(|(k, v)| (k.clone(), *v, data.consts.contains(k)))
.collect()
}
/// This scope's enclosing scope, if any.
#[must_use]
pub fn parent(&self) -> Option<Scope> {
self.0.borrow().parent.clone()
}
/// Visits every heap [`Handle`] reachable from this scope chain's bindings
/// (for GC tracing of a closure's captured values).
pub fn for_each_handle(&self, visit: &mut dyn FnMut(Handle)) {
let data = self.0.borrow();
for v in data.vars.values() {
if let Some(raw) = v.as_handle() {
visit(Handle::from_raw(raw));
}
}
if let Some(p) = &data.parent {
p.for_each_handle(visit);
}
}
/// Rewrites every handle binding in this scope chain through `forward` โ the
/// mutating mirror of [`for_each_handle`](Scope::for_each_handle), for a
/// moving collector. (A shared parent is visited once per referrer, which is
/// idempotent: `forward` maps an already-forwarded handle to itself.)
pub fn relocate_handles(&self, forward: &dyn Fn(Handle) -> Handle) {
let mut data = self.0.borrow_mut();
for v in data.vars.values_mut() {
if let Some(raw) = v.as_handle() {
*v = NanBox::handle(forward(Handle::from_raw(raw)).to_raw());
}
}
if let Some(p) = &data.parent {
p.relocate_handles(forward);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn declare_and_resolve_inner_first() {
let root = Scope::root();
root.declare("x", NanBox::number(1.0));
root.declare("y", NanBox::number(2.0));
let child = root.child();
child.declare("x", NanBox::number(99.0)); // shadows
assert_eq!(child.get("x").unwrap().as_number(), Some(99.0)); // inner
assert_eq!(child.get("y").unwrap().as_number(), Some(2.0)); // from parent
assert_eq!(root.get("x").unwrap().as_number(), Some(1.0)); // parent unaffected
assert!(child.get("z").is_none());
}
#[test]
fn set_targets_the_nearest_binding() {
let root = Scope::root();
root.declare("x", NanBox::number(1.0));
let child = root.child();
// No local `x`: assignment reaches the parent's binding.
assert!(child.set("x", NanBox::number(5.0)));
assert_eq!(root.get("x").unwrap().as_number(), Some(5.0));
// A local shadow captures the assignment.
child.declare("x", NanBox::number(10.0));
assert!(child.set("x", NanBox::number(20.0)));
assert_eq!(child.get("x").unwrap().as_number(), Some(20.0));
assert_eq!(root.get("x").unwrap().as_number(), Some(5.0)); // parent unchanged
// Assigning an undeclared name fails.
assert!(!child.set("nope", NanBox::number(0.0)));
}
#[test]
fn captured_scope_outlives_and_shares() {
// A child keeps its parent alive and sees the parent's later mutations
// (the closure-capture property).
let captured = {
let outer = Scope::root();
outer.declare("count", NanBox::number(0.0));
let inner = outer.child();
outer.set("count", NanBox::number(7.0)); // mutate after capture
inner // `outer` drops here, but `inner` holds an Rc to it
};
assert_eq!(captured.get("count").unwrap().as_number(), Some(7.0));
}
#[test]
fn for_each_handle_visits_chain() {
let root = Scope::root();
root.declare("a", NanBox::handle(1));
root.declare("n", NanBox::number(5.0)); // not a handle
let child = root.child();
child.declare("b", NanBox::handle(2));
let mut seen = alloc::vec::Vec::new();
child.for_each_handle(&mut |h| seen.push(h.to_raw()));
seen.sort_unstable();
assert_eq!(seen, alloc::vec![1, 2]);
}
}