-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathcontext.rs
325 lines (286 loc) · 8.56 KB
/
context.rs
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use super::OwnedObject;
use super::Trace;
use crate::core::env::UninternedSymbolMap;
use crate::core::object::{Gc, GcObj, IntoObject, WithLifetime};
use std::cell::{Cell, RefCell};
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::atomic::AtomicBool;
/// A global store of all gc roots. This struct should be passed to the [Context]
/// when it is created.
#[derive(Default, Debug)]
pub(crate) struct RootSet {
pub(super) roots: RefCell<Vec<*const dyn Trace>>,
}
/// A block of allocations. This type should be owned by [Context] and not used
/// directly.
#[derive(Default)]
pub(crate) struct Block<const CONST: bool> {
pub(super) objects: RefCell<Vec<OwnedObject>>,
pub(in crate::core) uninterned_symbol_map: UninternedSymbolMap,
}
/// Owns all allocations and creates objects. All objects have
/// a lifetime tied to the borrow of their `Context`. When the
/// `Context` goes out of scope, no objects should be accessible.
pub(crate) struct Context<'rt> {
pub(crate) block: Block<false>,
root_set: &'rt RootSet,
prev_obj_count: usize,
}
impl<'rt> Drop for Context<'rt> {
fn drop(&mut self) {
self.garbage_collect(true);
assert!(
std::thread::panicking() || self.block.objects.borrow().is_empty(),
"Error: Context was dropped while still holding data"
);
}
}
#[derive(Debug, Default)]
pub(in crate::core) struct GcMark(Cell<bool>);
impl Trace for GcMark {
fn trace(&self, _: &mut Vec<crate::core::object::RawObj>) {
self.0.set(true);
}
}
/// This trait represents a type that is managed by the Garbage collector and
/// therefore has a markbit to preserve it.
pub(in crate::core) trait GcManaged {
fn get_mark(&self) -> &GcMark;
fn mark(&self) {
self.get_mark().0.set(true);
}
fn unmark(&self) {
self.get_mark().0.set(false);
}
fn is_marked(&self) -> bool {
self.get_mark().0.get()
}
}
impl PartialEq for GcMark {
#[inline(always)]
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for GcMark {}
thread_local! {
static SINGLETON_CHECK: Cell<bool> = Cell::new(false);
}
static GLOBAL_CHECK: AtomicBool = AtomicBool::new(false);
impl Block<true> {
pub(crate) fn new_global() -> Self {
use std::sync::atomic::Ordering::SeqCst as Rel;
assert!(GLOBAL_CHECK.compare_exchange(false, true, Rel, Rel).is_ok());
Self::default()
}
}
impl Block<false> {
pub(crate) fn new_local() -> Self {
Self::assert_unique();
Self::default()
}
pub(crate) fn new_local_unchecked() -> Self {
Self::default()
}
pub(crate) fn assert_unique() {
SINGLETON_CHECK.with(|x| {
assert!(
!x.get(),
"There was already and active context when this context was created"
);
x.set(true);
});
}
}
impl<const CONST: bool> Block<CONST> {
pub(crate) fn add<'ob, T, U>(&'ob self, obj: T) -> GcObj
where
T: IntoObject<Out<'ob> = U>,
Gc<U>: Into<GcObj<'ob>>,
{
obj.into_obj(self).into()
}
pub(crate) fn add_as<'ob, T, U, V>(&'ob self, obj: T) -> Gc<V>
where
T: IntoObject<Out<'ob> = U>,
Gc<U>: Into<Gc<V>>,
{
obj.into_obj(self).into()
}
pub(super) fn register(objects: &mut Vec<OwnedObject>, obj: OwnedObject) {
objects.push(obj);
}
}
impl<'ob, 'rt> Context<'rt> {
pub(crate) fn new(roots: &'rt RootSet) -> Self {
Context {
block: Block::new_local(),
root_set: roots,
prev_obj_count: 0,
}
}
pub(crate) fn from_block(block: Block<false>, roots: &'rt RootSet) -> Self {
Block::assert_unique();
Context {
block,
root_set: roots,
prev_obj_count: 0,
}
}
pub(crate) fn bind<T>(&'ob self, obj: T) -> <T as WithLifetime>::Out
where
T: WithLifetime<'ob>,
{
unsafe { obj.with_lifetime() }
}
pub(crate) fn get_root_set(&'ob self) -> &'rt RootSet {
self.root_set
}
pub(crate) fn garbage_collect(&mut self, force: bool) {
let mut objects = self.block.objects.borrow_mut();
if cfg!(not(test))
&& !force
&& (objects.len() < 2000 || objects.len() < (self.prev_obj_count * 2))
{
return;
}
let gray_stack = &mut Vec::new();
for x in self.root_set.roots.borrow().iter() {
// SAFETY: The contact of root structs will ensure that it removes
// itself from this list before it drops.
unsafe {
(**x).trace(gray_stack);
}
}
while let Some(raw) = gray_stack.pop() {
let obj = unsafe { GcObj::from_raw(raw) };
if !obj.is_marked() {
obj.trace_mark(gray_stack);
}
}
// let prev = objects.len();
objects.retain_mut(|x| {
let marked = x.is_marked();
if marked {
x.unmark();
}
marked
});
// let retained = prev - objects.len();
// println!("garbage collected: {retained}/{prev}");
self.prev_obj_count = objects.len();
}
}
impl OwnedObject {
fn unmark(&self) {
match self {
OwnedObject::Float(x) => x.unmark(),
OwnedObject::Cons(x) => x.unmark(),
OwnedObject::Vec(x) => x.unmark(),
OwnedObject::HashTable(x) => x.unmark(),
OwnedObject::String(x) => x.unmark(),
OwnedObject::Symbol(x) => x.unmark(),
OwnedObject::ByteFn(x) => x.unmark(),
}
}
fn is_marked(&self) -> bool {
match self {
OwnedObject::Float(x) => x.is_marked(),
OwnedObject::Cons(x) => x.is_marked(),
OwnedObject::Vec(x) => x.is_marked(),
OwnedObject::HashTable(x) => x.is_marked(),
OwnedObject::String(x) => x.is_marked(),
OwnedObject::Symbol(x) => x.is_marked(),
OwnedObject::ByteFn(x) => x.is_marked(),
}
}
}
impl<'rt> Deref for Context<'rt> {
type Target = Block<false>;
fn deref(&self) -> &Self::Target {
&self.block
}
}
impl<'rt> AsRef<Block<false>> for Context<'rt> {
fn as_ref(&self) -> &Block<false> {
&self.block
}
}
impl<const CONST: bool> Drop for Block<CONST> {
// Only one block can exist in a thread at a time. This part of that
// contract.
fn drop(&mut self) {
SINGLETON_CHECK.with(|s| {
assert!(s.get(), "Context singleton check was overwritten");
s.set(false);
});
}
}
// helper macro for the `rebind!` macro
macro_rules! last {
($arg:expr) => { $arg };
($head:expr, $($rest:expr),+) => {
last!($($rest),+)
};
}
/// Rebinds an object so that it is bound to an immutable borrow of [Context]
/// instead of a mutable borrow. This can release the mutable borrow and allow
/// Context to be used for other things.
///
/// # Examples
///
/// ```
/// let object = rebind!(func1(&mut cx));
/// func2(&mut cx);
/// let object2 = object;
/// ```
///
/// wthout this macro the above code would not compile because `object` can't
/// outlive the call to func2.
#[macro_export]
macro_rules! rebind {
// rebind!(func(x, cx)?)
($($path:ident).*($($arg:expr),+)$($x:tt)?) => {{
rebind!($($path).*($($arg),+)$($x)?, last!($($arg),+))
}};
// rebind!(func(x, cx).unwrap())
($($path:ident).*($($arg:expr),+).unwrap()) => {{
rebind!($($path).*($($arg),+).unwrap(), last!($($arg),+))
}};
// rebind!(x, cx)
($value:expr, $cx:expr) => {{
// Eval value outside the unsafe block
let unbound = match $value {
v => unsafe { $crate::core::object::WithLifetime::<'static>::with_lifetime(v) }
};
$cx.bind(unbound)
}};
}
#[cfg(test)]
mod test {
use crate::root;
use super::*;
fn bind_to_mut<'ob>(cx: &'ob mut Context) -> GcObj<'ob> {
cx.add("invariant")
}
#[test]
fn test_reborrow() {
let roots = &RootSet::default();
let cx = &mut Context::new(roots);
let obj = rebind!(bind_to_mut(cx));
_ = "foo".into_obj(cx);
assert_eq!(obj, "invariant");
}
#[test]
fn garbage_collect() {
let roots = &RootSet::default();
let cx = &mut Context::new(roots);
let vec1: Vec<GcObj> = Vec::new();
root!(vec, vec1, cx);
cx.garbage_collect(true);
let cons = list!["foo", 1, false, "end"; cx];
vec.push(cons);
cx.garbage_collect(true);
}
}