]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/box_region.rs
a1a757b705418c421fdbe92e3b51b8c5219f87be
[rust.git] / compiler / rustc_data_structures / src / box_region.rs
1 //! This module provides a way to deal with self-referential data.
2 //!
3 //! The main idea is to allocate such data in a generator frame and then
4 //! give access to it by executing user-provided closures inside that generator.
5 //! The module provides a safe abstraction for the latter task.
6 //!
7 //! The interface consists of two exported macros meant to be used together:
8 //! * `declare_box_region_type` wraps a generator inside a struct with `access`
9 //!   method which accepts closures.
10 //! * `box_region_allow_access` is a helper which should be called inside
11 //!   a generator to actually execute those closures.
12
13 use std::marker::PhantomData;
14 use std::ops::{Generator, GeneratorState};
15 use std::pin::Pin;
16
17 #[derive(Copy, Clone)]
18 pub struct AccessAction(*mut dyn FnMut());
19
20 impl AccessAction {
21     pub fn get(self) -> *mut dyn FnMut() {
22         self.0
23     }
24 }
25
26 #[derive(Copy, Clone)]
27 pub enum Action {
28     Initial,
29     Access(AccessAction),
30     Complete,
31 }
32
33 pub struct PinnedGenerator<I, A, R> {
34     generator: Pin<Box<dyn Generator<Action, Yield = YieldType<I, A>, Return = R>>>,
35 }
36
37 impl<I, A, R> PinnedGenerator<I, A, R> {
38     pub fn new<T: Generator<Action, Yield = YieldType<I, A>, Return = R> + 'static>(
39         generator: T,
40     ) -> (I, Self) {
41         let mut result = PinnedGenerator { generator: Box::pin(generator) };
42
43         // Run it to the first yield to set it up
44         let init = match Pin::new(&mut result.generator).resume(Action::Initial) {
45             GeneratorState::Yielded(YieldType::Initial(y)) => y,
46             _ => panic!(),
47         };
48
49         (init, result)
50     }
51
52     pub unsafe fn access(&mut self, closure: *mut dyn FnMut()) {
53         // Call the generator, which in turn will call the closure
54         if let GeneratorState::Complete(_) =
55             Pin::new(&mut self.generator).resume(Action::Access(AccessAction(closure)))
56         {
57             panic!()
58         }
59     }
60
61     pub fn complete(&mut self) -> R {
62         // Tell the generator we want it to complete, consuming it and yielding a result
63         let result = Pin::new(&mut self.generator).resume(Action::Complete);
64         if let GeneratorState::Complete(r) = result { r } else { panic!() }
65     }
66 }
67
68 #[derive(PartialEq)]
69 pub struct Marker<T>(PhantomData<T>);
70
71 impl<T> Marker<T> {
72     pub unsafe fn new() -> Self {
73         Marker(PhantomData)
74     }
75 }
76
77 pub enum YieldType<I, A> {
78     Initial(I),
79     Accessor(Marker<A>),
80 }