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
use std::marker::PhantomData;
use std::ptr;
use boolinator::Boolinator;
use anymap::AnyMap;
use chakracore_sys::*;
use error::*;
use util::jstry;
use {value, Runtime};
struct ContextData {
promise_queue: Vec<value::Function>,
user_data: AnyMap,
}
#[derive(Debug, PartialEq)]
pub struct Context(JsContextRef);
impl Context {
pub fn new(runtime: &Runtime) -> Result<Context> {
let mut reference = JsContextRef::new();
unsafe {
jstry!(JsCreateContext(runtime.as_raw(), &mut reference));
jstry!(JsSetObjectBeforeCollectCallback(reference, ptr::null_mut(), Some(Self::collect)));
let context = Self::from_raw(reference);
context.set_data(Box::new(ContextData {
promise_queue: Vec::new(),
user_data: AnyMap::new(),
}))?;
context.exec_with(|_| {
let data = context.get_data() as *mut _ as *mut _;
jstry(JsSetPromiseContinuationCallback(Some(Self::promise_handler), data))
})
.expect("activating promise continuation callback")
.map(|_| context)
}
}
pub fn make_current<'a>(&'a self) -> Result<ContextGuard<'a>> {
let current = unsafe { Self::get_current().map(|guard| guard.current.clone()) };
self.enter().map(|_| {
ContextGuard::<'a> {
previous: current,
current: self.clone(),
phantom: PhantomData,
drop: true,
}
})
}
pub unsafe fn get_current<'a>() -> Option<ContextGuard<'a>> {
let mut reference = JsContextRef::new();
jsassert!(JsGetCurrentContext(&mut reference));
reference.0.as_ref().map(|_| ContextGuard {
previous: None,
current: Self::from_raw(reference),
phantom: PhantomData,
drop: false,
})
}
pub fn exec_with<Ret, T: FnOnce(&ContextGuard) -> Ret>(&self, callback: T) -> Result<Ret> {
self.make_current().map(|guard| callback(&guard))
}
pub fn exec_with_current<Ret, T: FnOnce(&ContextGuard) -> Ret>(callback: T) -> Option<Ret> {
unsafe { Self::get_current().as_ref().map(callback) }
}
pub(crate) fn exec_with_value<Ret, T>(value: &value::Value, callback: T) -> Result<Option<Ret>>
where T: FnOnce(&ContextGuard) -> Ret {
Context::from_recyclable(value).map_or(Ok(None), |context| unsafe {
let guard = Context::get_current()
.and_then(|guard| (guard.context() == context).as_some(guard))
.map_or_else(|| context.make_current(), Ok);
guard.map(|guard| Some(callback(&guard)))
})
}
pub fn insert_user_data<T>(&self, value: T) -> Option<T> where T: Send + 'static {
unsafe { self.get_data().user_data.insert(value) }
}
pub fn remove_user_data<T>(&self) -> Option<T> where T: Send + 'static {
unsafe { self.get_data().user_data.remove::<T>() }
}
pub fn get_user_data<T>(&self) -> Option<&T> where T: Send + 'static {
unsafe { self.get_data().user_data.get::<T>() }
}
pub fn get_user_data_mut<T>(&self) -> Option<&mut T> where T: Send + 'static {
unsafe { self.get_data().user_data.get_mut::<T>() }
}
fn from_recyclable(value: &value::Value) -> Option<Context> {
let mut reference = JsContextRef::new();
unsafe {
jstry(JsGetContextOfObject(value.as_raw(), &mut reference))
.ok()
.map(|_| Self::from_raw(reference))
}
}
unsafe fn set_data(&self, data: Box<ContextData>) -> Result<()> {
jstry(JsSetContextData(self.as_raw(), Box::into_raw(data) as *mut _))
}
unsafe fn get_data<'a>(&'a self) -> &'a mut ContextData {
let mut data = ptr::null_mut();
jsassert!(JsGetContextData(self.as_raw(), &mut data));
(data as *mut _)
.as_mut()
.expect("retrieving context data")
}
fn enter(&self) -> Result<()> {
jstry(unsafe { JsSetCurrentContext(self.as_raw()) })
}
fn exit(&self, previous: Option<&Context>) -> Result<()> {
jstry(unsafe {
let next = previous
.map(|context| context.as_raw())
.unwrap_or_else(JsValueRef::new);
JsSetCurrentContext(next)
})
}
unsafe extern "system" fn promise_handler(task: JsValueRef, data: *mut ::libc::c_void) {
let data = (data as *mut ContextData).as_mut().expect("retrieving promise handler stack");
data.promise_queue.push(value::Function::from_raw(task));
}
unsafe extern "system" fn collect(context: JsContextRef, _: *mut ::libc::c_void) {
let context = Self::from_raw(context);
Box::from_raw(context.get_data());
}
}
reference!(Context);
#[must_use]
#[derive(Debug)]
pub struct ContextGuard<'a> {
previous: Option<Context>,
current: Context,
phantom: PhantomData<&'a Context>,
drop: bool,
}
impl<'a> ContextGuard<'a> {
pub fn context(&self) -> Context {
self.current.clone()
}
pub fn global(&self) -> value::Object {
let mut value = JsValueRef::new();
unsafe {
jsassert!(JsGetGlobalObject(&mut value));
value::Object::from_raw(value)
}
}
pub fn execute_tasks(&self) {
let data = unsafe { self.current.get_data() };
while let Some(task) = data.promise_queue.pop() {
task.call(self, &[]).expect("executing promise task");
}
}
}
impl<'a> Drop for ContextGuard<'a> {
fn drop(&mut self) {
if self.drop {
assert!(self.current.exit(self.previous.as_ref()).is_ok())
}
}
}
#[cfg(test)]
mod tests {
use {test, value, script, Context, Property};
#[test]
fn global() {
test::run_with_context(|guard| {
let global = guard.global();
let dirname = Property::new(guard, "__dirname");
global.set(guard, &dirname, &value::String::new(guard, "FooBar"));
global.set_index(guard, 2, &value::Number::new(guard, 1337));
let result1 = script::eval(guard, "__dirname").unwrap();
let result2 = script::eval(guard, "this[2]").unwrap();
assert_eq!(result1.to_string(guard), "FooBar");
assert_eq!(result2.to_integer(guard), 1337);
});
}
#[test]
fn stack() {
let (runtime, context) = test::setup_env();
{
let get_current = || unsafe { Context::get_current().unwrap().context() };
let _guard = context.make_current().unwrap();
assert_eq!(get_current(), context);
{
let inner_context = Context::new(&runtime).unwrap();
let _guard = inner_context.make_current().unwrap();
assert_eq!(get_current(), inner_context);
}
assert_eq!(get_current(), context);
}
assert!(unsafe { Context::get_current() }.is_none());
}
#[test]
fn user_data() {
test::run_with_context(|guard| {
type Data = Vec<i32>;
let context = guard.context();
let data: Data = vec![10, 20];
context.insert_user_data(data);
let data = context.get_user_data::<Data>().unwrap();
assert_eq!(data.as_slice(), [10, 20]);
assert!(context.remove_user_data::<Data>().is_some());
assert!(context.get_user_data::<Data>().is_none());
});
}
#[test]
fn promise_queue() {
test::run_with_context(|guard| {
let result = script::eval(guard, "
var object = {};
Promise.resolve(5)
.then(val => val + 5)
.then(val => val / 5)
.then(val => object.val = val);
object;").unwrap();
guard.execute_tasks();
let value = result
.into_object()
.unwrap()
.get(guard, &Property::new(guard, "val"))
.to_integer(guard);
assert_eq!(value, 2);
});
}
}