forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm_class.rs
More file actions
106 lines (93 loc) · 2.84 KB
/
vm_class.rs
File metadata and controls
106 lines (93 loc) · 2.84 KB
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
use convert;
use js_sys::TypeError;
use rustpython_vm::{pyobject::PyObjectRef, VirtualMachine};
use std::cell::RefCell;
use std::collections::HashMap;
use wasm_bindgen::prelude::*;
struct StoredVirtualMachine {
pub vm: VirtualMachine,
pub scope: PyObjectRef,
}
impl StoredVirtualMachine {
fn new() -> StoredVirtualMachine {
let mut vm = VirtualMachine::new();
let builtin = vm.get_builtin_scope();
let scope = vm.context().new_scope(Some(builtin));
StoredVirtualMachine { vm, scope }
}
}
// It's fine that it's thread local, since WASM doesn't even have threads yet
thread_local! {
static STORED_VMS: RefCell<HashMap<String, StoredVirtualMachine>> = RefCell::default();
}
#[wasm_bindgen(js_name = vmStore)]
pub struct VMStore;
#[wasm_bindgen(js_class = vmStore)]
impl VMStore {
pub fn init(id: String) -> WASMVirtualMachine {
STORED_VMS.with(|cell| {
let mut vms = cell.borrow_mut();
if !vms.contains_key(&id) {
vms.insert(id.clone(), StoredVirtualMachine::new());
}
});
WASMVirtualMachine { id }
}
pub fn get(id: String) -> JsValue {
STORED_VMS.with(|cell| {
let vms = cell.borrow();
if vms.contains_key(&id) {
WASMVirtualMachine { id }.into()
} else {
JsValue::UNDEFINED
}
})
}
pub fn destroy(id: &String) {
STORED_VMS.with(|cell| {
cell.borrow_mut().remove(id);
});
}
pub fn ids() -> Vec<JsValue> {
STORED_VMS.with(|cell| cell.borrow().keys().map(|k| k.into()).collect())
}
}
#[wasm_bindgen(js_name = VirtualMachine)]
pub struct WASMVirtualMachine {
id: String,
}
#[wasm_bindgen(js_class = VirtualMachine)]
impl WASMVirtualMachine {
pub fn valid(&self) -> bool {
STORED_VMS.with(|cell| cell.borrow().contains_key(&self.id))
}
fn assert_valid(&self) -> Result<(), JsValue> {
if self.valid() {
Ok(())
} else {
Err(TypeError::new(
"Invalid VirtualMachine, this VM was destroyed while this reference was still held",
)
.into())
}
}
pub fn destroy(&self) -> Result<(), JsValue> {
self.assert_valid()?;
VMStore::destroy(&self.id);
Ok(())
}
#[wasm_bindgen(js_name = addToScope)]
pub fn add_to_scope(&self, name: String, value: JsValue) -> Result<(), JsValue> {
self.assert_valid()?;
STORED_VMS.with(|cell| {
let mut vms = cell.borrow_mut();
let StoredVirtualMachine {
ref mut vm,
ref mut scope,
} = vms.get_mut(&self.id).unwrap();
let value = convert::js_to_py(vm, value);
vm.ctx.set_attr(scope, &name, value);
});
Ok(())
}
}