-
Notifications
You must be signed in to change notification settings - Fork 54
/
callback.rs
279 lines (248 loc) · 8.16 KB
/
callback.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
use std::{
fmt,
hash::{Hash, Hasher},
ops,
};
use allocator_api2::boxed;
use gc_arena::{allocator_api::MetricsAlloc, Collect, Gc, Mutation};
use crate::{Context, Error, Execution, Function, Stack, Thread};
#[derive(Collect)]
#[collect(no_drop)]
pub enum CallbackReturn<'gc> {
Return,
Sequence(BoxSequence<'gc>),
Yield {
to_thread: Option<Thread<'gc>>,
then: Option<BoxSequence<'gc>>,
},
Call {
function: Function<'gc>,
then: Option<BoxSequence<'gc>>,
},
Resume {
thread: Thread<'gc>,
then: Option<BoxSequence<'gc>>,
},
}
pub trait CallbackFn<'gc>: Collect {
fn call(
&self,
ctx: Context<'gc>,
exec: Execution<'gc, '_>,
stack: Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>>;
}
// Represents a callback as a single pointer with an inline VTable header.
#[derive(Copy, Clone, Collect)]
#[collect(no_drop)]
pub struct Callback<'gc>(Gc<'gc, CallbackInner<'gc>>);
pub struct CallbackInner<'gc> {
call: unsafe fn(
*const CallbackInner<'gc>,
Context<'gc>,
Execution<'gc, '_>,
Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>>,
}
impl<'gc> Callback<'gc> {
pub fn new<C: CallbackFn<'gc> + 'gc>(mc: &Mutation<'gc>, callback: C) -> Self {
#[repr(C)]
struct HeaderCallback<'gc, C> {
header: CallbackInner<'gc>,
callback: C,
}
// SAFETY: We can't auto-implement `Collect` due to the function pointer lifetimes, but
// function pointers can't hold any data. It would be nice if function pointers could have
// higher rank `for<'gc>` lifetimes.
unsafe impl<'gc, C: Collect> Collect for HeaderCallback<'gc, C> {
fn needs_trace() -> bool
where
Self: Sized,
{
C::needs_trace()
}
fn trace(&self, cc: &gc_arena::Collection) {
self.callback.trace(cc)
}
}
let hc = Gc::new(
mc,
HeaderCallback {
header: CallbackInner {
call: |ptr, ctx, exec, stack| unsafe {
let hc = ptr as *const HeaderCallback<C>;
((*hc).callback).call(ctx, exec, stack)
},
},
callback,
},
);
Self(unsafe { Gc::cast::<CallbackInner>(hc) })
}
pub fn from_fn<F>(mc: &Mutation<'gc>, call: F) -> Callback<'gc>
where
F: 'static
+ Fn(
Context<'gc>,
Execution<'gc, '_>,
Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>>,
{
Self::from_fn_with(mc, (), move |_, ctx, exec, stack| call(ctx, exec, stack))
}
pub fn from_fn_with<R, F>(mc: &Mutation<'gc>, root: R, call: F) -> Callback<'gc>
where
R: 'gc + Collect,
F: 'static
+ Fn(
&R,
Context<'gc>,
Execution<'gc, '_>,
Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>>,
{
#[derive(Collect)]
#[collect(no_drop)]
struct RootCallback<R, F> {
root: R,
#[collect(require_static)]
call: F,
}
impl<'gc, R, F> CallbackFn<'gc> for RootCallback<R, F>
where
R: 'gc + Collect,
F: 'static
+ Fn(
&R,
Context<'gc>,
Execution<'gc, '_>,
Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>>,
{
fn call(
&self,
ctx: Context<'gc>,
exec: Execution<'gc, '_>,
stack: Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>> {
(self.call)(&self.root, ctx, exec, stack)
}
}
Callback::new(mc, RootCallback { root, call })
}
pub fn from_inner(inner: Gc<'gc, CallbackInner<'gc>>) -> Self {
Self(inner)
}
pub fn into_inner(self) -> Gc<'gc, CallbackInner<'gc>> {
self.0
}
pub fn call(
self,
ctx: Context<'gc>,
exec: Execution<'gc, '_>,
stack: Stack<'gc, '_>,
) -> Result<CallbackReturn<'gc>, Error<'gc>> {
unsafe { (self.0.call)(Gc::as_ptr(self.0), ctx, exec, stack) }
}
}
impl<'gc> fmt::Debug for Callback<'gc> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_tuple("Callback")
.field(&Gc::as_ptr(self.0))
.finish()
}
}
impl<'gc> PartialEq for Callback<'gc> {
fn eq(&self, other: &Callback<'gc>) -> bool {
Gc::ptr_eq(self.0, other.0)
}
}
impl<'gc> Eq for Callback<'gc> {}
impl<'gc> Hash for Callback<'gc> {
fn hash<H: Hasher>(&self, state: &mut H) {
Gc::as_ptr(self.0).hash(state)
}
}
pub enum SequencePoll<'gc> {
/// Sequence pending, `Sequence::poll` will be called on the next step with the stack unchanged.
Pending,
/// Sequence finished, the values in the stack will be returned to the caller.
Return,
/// Yield the values in the stack inside a coroutine. If `is_tail` is true, then this also
/// finishes the sequence, otherwise `Sequence::poll` will be called when the coroutine is
/// resumed, or `Sequence::error` if the coroutine is resumed with an error.
Yield {
to_thread: Option<Thread<'gc>>,
is_tail: bool,
},
/// Call the given function with the arguments in the stack. If `is_tail` is true, then this
/// is a tail call, and the sequence is now finished, otherwise `Sequence::poll` will be called
/// with the results of the function call, or if the function errors, `Sequence::error` will be
/// called with the function error.
Call {
function: Function<'gc>,
is_tail: bool,
},
Resume {
thread: Thread<'gc>,
is_tail: bool,
},
}
pub trait Sequence<'gc>: Collect {
/// Called when a `Sequence` is first run with the stack unchanged from the returned `Callback`
/// that spawned it.
///
/// If a sub-function is called and succeeds, this will be called when that function finishes
/// successfully with its return values.
///
/// If the `Sequence` yields values, this will suspend the containing coroutine and
/// `Sequence::poll` will be called again with the resume parameters.
fn poll(
&mut self,
ctx: Context<'gc>,
exec: Execution<'gc, '_>,
stack: Stack<'gc, '_>,
) -> Result<SequencePoll<'gc>, Error<'gc>>;
/// Called if a sub-function errors to handle the error, or if a `Sequence` has yielded and the
/// containing coroutine is resumed with an error.
fn error(
&mut self,
_ctx: Context<'gc>,
_exec: Execution<'gc, '_>,
error: Error<'gc>,
_stack: Stack<'gc, '_>,
) -> Result<SequencePoll<'gc>, Error<'gc>> {
Err(error)
}
}
#[derive(Collect)]
#[collect(no_drop)]
pub struct BoxSequence<'gc>(boxed::Box<dyn Sequence<'gc> + 'gc, MetricsAlloc<'gc>>);
impl<'gc> fmt::Debug for BoxSequence<'gc> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_tuple("Sequence")
.field(&(self.0.as_ref() as *const _))
.finish()
}
}
impl<'gc> ops::Deref for BoxSequence<'gc> {
type Target = dyn Sequence<'gc> + 'gc;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl<'gc> ops::DerefMut for BoxSequence<'gc> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.0
}
}
impl<'gc> BoxSequence<'gc> {
pub fn new(mc: &Mutation<'gc>, sequence: impl Sequence<'gc> + 'gc) -> Self {
let b = boxed::Box::new_in(sequence, MetricsAlloc::new(mc));
let (ptr, alloc) = boxed::Box::into_raw_with_allocator(b);
// TODO: Required unsafety due to do lack of `CoerceUnsized` on allocator_api2 `Box` type,
// replace with safe cast when one of allocator_api or CoerceUnsized is stabilized.
let b = unsafe { boxed::Box::from_raw_in(ptr as *mut dyn Sequence, alloc) };
Self(b)
}
}