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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//#![no_std] // https://github.com/sgrif/derive_deref/pull/9
#![feature(box_syntax)]
#![feature(box_into_raw_non_null)]
#![feature(map_first_last)]
#![allow(private_in_public)]

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        panic!("TODO")
    }
}

extern crate alloc;
use alloc::{boxed::Box, collections::btree_set::BTreeSet};
use core::{
    cmp::{Ord, Ordering},
    hash::{Hash, Hasher},
    marker::PhantomData,
    mem::swap,
    ops::{Deref, Drop},
    ptr::NonNull,
};
use derive_deref::Deref;
use hashbrown::HashSet;
use spin::{Mutex, MutexGuard};

pub mod trace {
    pub use super::libbare::{Trace, Tracer};
}

pub mod liblifetime {
    pub use super::trace::*;
    use super::*;
    pub struct Gc<'root, T: Trace> {
        val: libcore::Gc<T>,
        phantom: PhantomData<&'root libcore::Gc<T>>,
    }
    impl<T: Trace> Clone for Gc<'_, T> {
        fn clone(&self) -> Self {
            Self {
                val: self.val,
                phantom: PhantomData,
            }
        }
    }
    impl<T: Trace> Copy for Gc<'_, T> {}
    pub struct RootedGc<'root, T: Trace> {
        val: libcore::Root<libcore::Gc<T>>,
        phantom: PhantomData<&'root libcore::Root<T>>,
    }
    impl<T: Trace> Deref for RootedGc<'_, T> {
        type Target = T;
        fn deref(&self) -> &Self::Target {
            unsafe { self.val.deref().deref() }
        }
    }
    impl<'root, T: Trace> RootedGc<'root, T> {
        pub fn new(x: T, _rooter: &Rooter<'root>) -> Self {
            Self {
                val: libcore::Root::new(libcore::Gc::new(x)),
                phantom: PhantomData,
            }
        }
    }
    impl<'root, T: Trace> Clone for RootedGc<'root, T> {
        fn clone(&self) -> Self {
            Self {
                val: libcore::Root::new(*self.val),
                phantom: PhantomData,
            }
        }
    }
    pub struct Rooter<'root>(PhantomData<&'root ()>);
    impl<'root> Rooter<'root> {
        #[doc(hidden)]
        pub unsafe fn new(_: &'root ()) -> Self {
            Rooter(PhantomData)
        }
        pub fn create_rooted_gc<T: Trace>(&self, x: T) -> RootedGc<'root, T> {
            RootedGc::new(x, self)
        }
    }
    #[macro_export]
    macro_rules! letrooter {
        ($root:ident) => {
            let root = ();
            #[allow(unused_mut)]
            let $root = unsafe { $crate::Rooter::new(&root) };
        };
    }
}

/// Derefing Gc is unsafe. Auto marksweep.
pub mod libcore {
    pub use super::trace::*;
    use super::*;
    pub struct Gc<T: Trace>(libbare::Gc<T>);
    impl<T: Trace> Clone for Gc<T> {
        fn clone(&self) -> Self {
            self.0.try_marksweep_step();
            Self(self.0)
        }
    }
    impl<T: Trace> Copy for Gc<T> {}
    impl<T: Trace> Gc<T> {
        pub fn new(x: T) -> Self {
            Self(libbare::Gc::new(x))
        }
        pub unsafe fn deref(&self) -> &T {
            self.0.try_marksweep_step();
            self.0.deref()
        }
    }
    impl<T: Trace> Trace for Gc<T> {
        fn trace(&self, tracer: &mut Tracer) {
            self.0.trace(tracer);
        }
    }
    pub struct Root<T: Trace>(libbare::Root<T>);
    impl<T: Trace> Root<T> {
        pub fn new(x: T) -> Self {
            Self(libbare::Root::new(x))
        }
    }
    impl<T: Trace> Deref for Root<T> {
        type Target = T;
        fn deref(&self) -> &Self::Target {
            self.0.try_marksweep_step();
            &*self.0
        }
    }
}

/// Anything is manual and unsafe.
pub mod libbare {
    use super::*;
    pub struct Tracer<'a>(Box<dyn FnMut(Box<dyn AnyGc>) + 'a>);
    pub trait Trace: 'static {
        /// Define how to visit values referred by this value.
        ///
        /// For example, if `self.x` is a value referred by `self`,
        /// call `self.x.trace(tracer)` to visit it.
        ///
        /// The values that are visited must match the `Drop::drop`
        /// implementation. Otherwise memory leak or panic might
        /// happen. After the panic, dereferencing already collected
        /// `Cc<T>` can trigger:
        /// - Undefined behavior on release build.
        /// - Another panic on debug build.
        ///
        /// Ideally this can be generated by the compiler, since the
        /// compiler already knows how to generate `Drop::drop`.
        fn trace(&self, tracer: &mut Tracer) {
            let _ = tracer;
        }
    }
    pub struct Gc<T: Trace> {
        ptr: NonNull<GcInner<T>>,
        phantom: PhantomData<GcInner<T>>,
    }
    impl<T: Trace> Clone for Gc<T> {
        fn clone(&self) -> Self {
            Gc {
                ptr: self.ptr,
                phantom: PhantomData,
            }
        }
    }
    impl<T: Trace> Copy for Gc<T> {}
    unsafe impl<T: Trace + Sync + Send> Send for Gc<T> {}
    unsafe impl<T: Trace + Sync + Send> Sync for Gc<T> {}
    trait GcTraverse {
        fn gc_traverse(&self, tracer: &mut Tracer);
    }
    /// Type-erased `Gc<T>` needed by GC.
    trait AnyGc: GcTraverse {
        fn clone_as_any(&self) -> Box<dyn AnyGc>;
        fn get_unit_gcinner_ptr(&self) -> NonNull<()>;
        unsafe fn get_space_nonnull_mutex(&self) -> NonNull<Mutex<NonNull<AutoGcSpace>>>;
        unsafe fn destory(&self);
        fn clone_as_gc_traverse(&self) -> Box<dyn GcTraverse>;
    }
    impl<T: Trace> GcTraverse for Gc<T> {
        fn gc_traverse(&self, tracer: &mut Tracer) {
            unsafe {
                self.deref().trace(tracer);
            }
        }
    }
    impl<T: Trace> AnyGc for Gc<T> {
        fn clone_as_any(&self) -> Box<dyn AnyGc> {
            box *self
        }
        fn clone_as_gc_traverse(&self) -> Box<dyn GcTraverse> {
            box *self
        }
        fn get_unit_gcinner_ptr(&self) -> NonNull<()> {
            NonNull::cast(self.ptr)
        }
        unsafe fn get_space_nonnull_mutex(&self) -> NonNull<Mutex<NonNull<AutoGcSpace>>> {
            let ptr = self.ptr;
            let mut ptr = ptr;
            NonNull::new_unchecked(&mut ptr.as_mut().space)
        }
        unsafe fn destory(&self) {
            drop(Box::from_raw(self.ptr.as_ptr()));
        }
    }
    impl<T: Trace> Trace for Gc<T>
    where
        Gc<T>: AnyGc,
    {
        fn trace(&self, tracer: &mut Tracer) {
            tracer.0(self.clone_as_any());
        }
    }
    #[derive(Deref)]
    struct HashableAnyGc(Box<dyn AnyGc>);
    impl Hash for HashableAnyGc {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.get_unit_gcinner_ptr().hash(state);
        }
    }
    impl PartialEq for HashableAnyGc {
        fn eq(&self, other: &Self) -> bool {
            self.get_unit_gcinner_ptr() == other.get_unit_gcinner_ptr()
        }
    }
    impl Eq for HashableAnyGc {}
    impl Ord for HashableAnyGc {
        fn cmp(&self, other: &Self) -> Ordering {
            self.get_unit_gcinner_ptr()
                .cmp(&other.get_unit_gcinner_ptr())
        }
    }
    impl PartialOrd for HashableAnyGc {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }
    struct GcInner<T: Trace> {
        space: Mutex<NonNull<AutoGcSpace>>,
        data: T,
    }
    impl<T: Trace> Gc<T> {
        pub fn new(x: T) -> Self {
            let ptr = Box::into_raw_non_null(box GcInner {
                space: Mutex::new(Box::into_raw_non_null(box AutoGcSpace::new())),
                data: x,
            });
            let result = Gc {
                ptr: ptr,
                phantom: PhantomData,
            };
            unsafe {
                ptr.as_ref()
                    .space
                    .lock()
                    .as_ref()
                    .add_element(result.clone_as_any());
            }
            result
        }
        pub unsafe fn deref(&self) -> &T {
            &self.ptr.as_ref().data
        }
        pub fn try_marksweep_step(&self) {
            unsafe {
                if let Some(ptr) = {
                    let maybe_locked = self.ptr.as_ref().space.try_lock();
                    if let Some(ptr) = maybe_locked {
                        let result: NonNull<_> = *ptr;
                        Some(result)
                    } else {
                        None
                    }
                } {
                    AutoGcSpace::try_marksweep_step(ptr);
                }
            }
        }
    }
    #[derive(Deref)]
    struct AutoGcSpace(Mutex<AutoGcSpaceInner>);
    struct AutoGcSpaceInner {
        elements: HashSet<HashableAnyGc>,
        roots: HashSet<HashableAnyRoot>,
        state: AutoGcSpaceState,
    }
    enum AutoGcSpaceState {
        Mark {
            marked: HashSet<HashableAnyGc>,
            marking_gc: BTreeSet<HashableAnyGc>,
            marking_root: BTreeSet<HashableAnyRoot>,
        },
        Sweep {
            marked: HashSet<HashableAnyGc>,
            elements: BTreeSet<HashableAnyGc>,
        },
    }
    impl Drop for AutoGcSpace {
        fn drop(&mut self) {
            let this: NonNull<Self> = unsafe { NonNull::new_unchecked(self) };
            let mut locked_self = self.lock();
            locked_self.state = AutoGcSpaceState::Mark {
                marked: HashSet::new(),
                marking_gc: BTreeSet::new(),
                marking_root: BTreeSet::new(),
            };
            for x in locked_self.elements.drain() {
                unsafe {
                    debug_assert_eq!(*x.get_space_nonnull_mutex().as_ref().lock(), this);
                    x.destory();
                }
            }
        }
    }
    impl AutoGcSpace {
        fn new() -> Self {
            AutoGcSpace(Mutex::new(AutoGcSpaceInner {
                elements: HashSet::new(),
                roots: HashSet::new(),
                state: AutoGcSpaceState::Mark {
                    marked: HashSet::new(),
                    marking_gc: BTreeSet::new(),
                    marking_root: BTreeSet::new(),
                },
            }))
        }
        fn add_root(&self, x: Box<dyn AnyRoot>) {
            Self::add_root_aux(&mut self.lock(), x);
        }
        fn add_root_aux(locked: &mut MutexGuard<AutoGcSpaceInner>, x: Box<dyn AnyRoot>) {
            let should_be_false = locked.roots.insert(HashableAnyRoot(x.clone_as_any()));
            debug_assert_eq!(should_be_false, false);
            match &mut locked.state {
                AutoGcSpaceState::Mark {
                    marked: _,
                    marking_gc: _,
                    marking_root,
                } => {
                    let should_be_false = marking_root.insert(HashableAnyRoot(x));
                    debug_assert_eq!(should_be_false, false);
                }
                AutoGcSpaceState::Sweep {
                    marked: _,
                    elements: _,
                } => {}
            }
        }
        fn add_element(&self, x: Box<dyn AnyGc>) {
            Self::add_element_aux(&mut self.lock(), x);
        }
        fn add_element_aux(locked: &mut MutexGuard<AutoGcSpaceInner>, x: Box<dyn AnyGc>) {
            let should_be_false = locked.elements.insert(HashableAnyGc(x.clone_as_any()));
            debug_assert_eq!(should_be_false, false);
            match &mut locked.state {
                AutoGcSpaceState::Mark {
                    marked: _,
                    marking_gc,
                    marking_root: _,
                } => {
                    let should_be_false = marking_gc.insert(HashableAnyGc(x));
                    debug_assert_eq!(should_be_false, false);
                }
                AutoGcSpaceState::Sweep {
                    marked: _,
                    elements: _,
                } => {}
            }
        }
        unsafe fn destory(this: NonNull<Self>) {
            drop(Box::from_raw(this.as_ptr()));
        }
        unsafe fn remove_root_and_destory_if_empty(this: NonNull<Self>, x: &HashableAnyRoot) {
            let mut locked_this = this.as_ref().lock();
            let should_be_true = locked_this.roots.remove(x);
            debug_assert!(should_be_true);
            match &mut locked_this.state {
                AutoGcSpaceState::Mark {
                    marked: _,
                    marking_gc: _,
                    marking_root,
                } => {
                    marking_root.remove(x);
                }
                AutoGcSpaceState::Sweep {
                    marked: _,
                    elements: _,
                } => {}
            }
            drop(locked_this);
            Self::destory_if_empty(this);
        }
        unsafe fn destory_if_empty(this: NonNull<Self>) {
            let locked = this.as_ref().lock();
            if locked.roots.is_empty() {
                drop(locked);
                Self::destory(this);
            }
        }
        unsafe fn merge(
            (this, locked_this): (NonNull<Self>, MutexGuard<AutoGcSpaceInner>),
            (other, locked_other): (NonNull<Self>, MutexGuard<AutoGcSpaceInner>),
        ) {
            let this_approximate_size =
                locked_this.elements.capacity() + locked_this.roots.capacity();
            let other_approximate_size =
                locked_other.elements.capacity() + locked_other.roots.capacity();
            if this_approximate_size > other_approximate_size {
                Self::merge_aux((this, locked_this), (other, locked_other));
            } else {
                Self::merge_aux((other, locked_other), (this, locked_this));
            }
        }
        unsafe fn merge_aux(
            (this, locked_this): (NonNull<Self>, MutexGuard<AutoGcSpaceInner>),
            (other, locked_other): (NonNull<Self>, MutexGuard<AutoGcSpaceInner>),
        ) {
            let mut locked_this: MutexGuard<AutoGcSpaceInner> = locked_this;
            let mut locked_other: MutexGuard<AutoGcSpaceInner> = locked_other;
            debug_assert_eq!(
                locked_this
                    .elements
                    .intersection(&locked_other.elements)
                    .count(),
                0
            );
            debug_assert_eq!(
                locked_this.roots.intersection(&locked_other.roots).count(),
                0
            );
            let mut locked_this_space_refs: Vec<MutexGuard<NonNull<AutoGcSpace>>> = Vec::new();
            for ptr in locked_this
                .elements
                .iter()
                .map(|x| x.get_space_nonnull_mutex())
                .chain(
                    locked_this
                        .roots
                        .iter()
                        .map(|x| x.get_space_nonnull_mutex()),
                )
            {
                let lk = (*ptr.as_ptr()).lock();
                debug_assert!(*lk == this);
                locked_this_space_refs.push(lk);
            }
            let mut locked_other_space_refs: Vec<MutexGuard<NonNull<AutoGcSpace>>> = Vec::new();
            for ptr in locked_other
                .elements
                .iter()
                .map(|x| x.get_space_nonnull_mutex())
                .chain(
                    locked_other
                        .roots
                        .iter()
                        .map(|x| x.get_space_nonnull_mutex()),
                )
            {
                let lk = (*ptr.as_ptr()).lock();
                debug_assert!(*lk == other);
                locked_other_space_refs.push(lk);
            }
            for x in locked_other.elements.drain() {
                Self::add_element_aux(&mut locked_this, x.0);
            }
            for x in locked_other.roots.drain() {
                Self::add_root_aux(&mut locked_this, x.0);
            }
            drop(locked_other);
            Self::destory(other);
            for ptr in locked_other_space_refs.iter_mut() {
                **ptr = this;
            }
        }
        unsafe fn try_marksweep_step(this: NonNull<Self>) {
            if let Some(locked_this) = this.as_ref().try_lock() {
                let mut locked_this = locked_this;
                match &mut locked_this.state {
                    AutoGcSpaceState::Mark {
                        marked,
                        marking_gc,
                        marking_root,
                    } => {
                        if let Some(x) = {
                            if let Some(x) = marking_root.pop_first() {
                                Some(x.clone_as_gc_traverse())
                            } else if let Some(x) = marking_gc.pop_first() {
                                Some(x.clone_as_gc_traverse())
                            } else {
                                None
                            }
                        } {
                            let mut to_mark_set = BTreeSet::new();
                            let mut tracer = Tracer(box |v: Box<dyn AnyGc>| {
                                let hashable_v = HashableAnyGc(v.clone_as_any());
                                if !marked.contains(&hashable_v) {
                                    to_mark_set.insert(hashable_v);
                                }
                            });
                            x.gc_traverse(&mut tracer);
                            drop(tracer);
                            drop(x);
                            if let Some(other_space) = to_mark_set
                                .iter()
                                .map(|to_mark| *to_mark.get_space_nonnull_mutex().as_ref().lock())
                                .find(|&x| x != this)
                            {
                                if let Some(locked_other_space) = other_space.as_ref().try_lock() {
                                    return Self::merge(
                                        (this, locked_this),
                                        (other_space, locked_other_space),
                                    );
                                }
                            } else {
                                for x in to_mark_set.into_iter() {
                                    debug_assert_eq!(
                                        *x.get_space_nonnull_mutex().as_ref().lock(),
                                        this
                                    );
                                    if marked.insert(HashableAnyGc(x.0.clone_as_any())) {
                                        marking_gc.insert(x);
                                    }
                                }
                            }
                        } else {
                            let cap = marked.capacity();
                            let mut owned_marked = HashSet::new();
                            swap(&mut owned_marked, marked);
                            debug_assert_eq!(cap, owned_marked.capacity());
                            locked_this.state = AutoGcSpaceState::Sweep {
                                marked: owned_marked,
                                elements: locked_this
                                    .elements
                                    .iter()
                                    .map(|x| HashableAnyGc(x.clone_as_any()))
                                    .collect(),
                            }
                        }
                    }
                    AutoGcSpaceState::Sweep { marked, elements } => {
                        if let Some(x) = elements.pop_first() {
                            if !marked.contains(&x) {
                                debug_assert_eq!(
                                    *x.get_space_nonnull_mutex().as_ref().lock(),
                                    this
                                );
                                x.destory();
                            }
                        } else {
                            locked_this.state = AutoGcSpaceState::Mark {
                                marked: HashSet::new(),
                                marking_gc: BTreeSet::new(),
                                marking_root: locked_this
                                    .roots
                                    .iter()
                                    .map(|x| HashableAnyRoot(x.clone_as_any()))
                                    .collect(),
                            }
                        }
                    }
                }
            }
        }
    }
    /// Type-erased `Root<T>` needed by GC.
    trait AnyRoot: GcTraverse {
        fn clone_as_any(&self) -> Box<dyn AnyRoot>;
        fn get_unit_rootinner_ptr(&self) -> NonNull<()>;
        unsafe fn get_space_nonnull_mutex(&self) -> NonNull<Mutex<NonNull<AutoGcSpace>>>;
        fn clone_as_gc_traverse(&self) -> Box<dyn GcTraverse>;
    }
    impl<T: Trace> GcTraverse for Root<T> {
        fn gc_traverse(&self, tracer: &mut Tracer) {
            self.deref().trace(tracer);
        }
    }
    impl<T: Trace> AnyRoot for Root<T> {
        fn clone_as_any(&self) -> Box<dyn AnyRoot> {
            box Root {
                ptr: self.ptr,
                phantom: PhantomData,
            }
        }
        fn clone_as_gc_traverse(&self) -> Box<dyn GcTraverse> {
            box Root {
                ptr: self.ptr,
                phantom: PhantomData,
            }
        }
        fn get_unit_rootinner_ptr(&self) -> NonNull<()> {
            NonNull::cast(self.ptr)
        }
        unsafe fn get_space_nonnull_mutex(&self) -> NonNull<Mutex<NonNull<AutoGcSpace>>> {
            let ptr = self.ptr;
            let mut ptr = ptr;
            NonNull::new_unchecked(&mut ptr.as_mut().space)
        }
    }
    #[derive(Deref)]
    struct HashableAnyRoot(Box<dyn AnyRoot>);
    impl Hash for HashableAnyRoot {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.get_unit_rootinner_ptr().hash(state);
        }
    }
    impl PartialEq for HashableAnyRoot {
        fn eq(&self, other: &Self) -> bool {
            self.get_unit_rootinner_ptr() == other.get_unit_rootinner_ptr()
        }
    }
    impl Eq for HashableAnyRoot {}
    impl Ord for HashableAnyRoot {
        fn cmp(&self, other: &Self) -> Ordering {
            self.get_unit_rootinner_ptr()
                .cmp(&other.get_unit_rootinner_ptr())
        }
    }
    impl PartialOrd for HashableAnyRoot {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }
    pub struct Root<T: Trace> {
        ptr: NonNull<RootInner<T>>,
        phantom: PhantomData<RootInner<T>>,
    }
    struct RootInner<T: Trace> {
        space: Mutex<NonNull<AutoGcSpace>>,
        data: T,
    }
    impl<T: Trace> Root<T> {
        pub fn new(x: T) -> Self {
            let ptr = Box::into_raw_non_null(box RootInner {
                space: Mutex::new(Box::into_raw_non_null(box AutoGcSpace::new())),
                data: x,
            });
            let result = Root {
                ptr: ptr,
                phantom: PhantomData,
            };
            unsafe {
                ptr.as_ref()
                    .space
                    .lock()
                    .as_ref()
                    .add_root(result.clone_as_any());
            }
            result
        }
        pub fn try_marksweep_step(&self) {
            unsafe {
                if let Some(ptr) = {
                    let maybe_locked = self.ptr.as_ref().space.try_lock();
                    if let Some(ptr) = maybe_locked {
                        let result: NonNull<_> = *ptr;
                        Some(result)
                    } else {
                        None
                    }
                } {
                    AutoGcSpace::try_marksweep_step(ptr);
                }
            }
        }
    }
    impl<T: Trace> Deref for Root<T> {
        type Target = T;
        fn deref(&self) -> &Self::Target {
            unsafe { &self.ptr.as_ref().data }
        }
    }
    impl<T: Trace> Drop for Root<T> {
        fn drop(&mut self) {
            unsafe {
                let space_ref_locked = self.ptr.as_ref().space.lock();
                AutoGcSpace::remove_root_and_destory_if_empty(
                    *space_ref_locked,
                    &HashableAnyRoot(self.clone_as_any()),
                );
            }
        }
    }
}