Skip to content

Commit 387c21f

Browse files
Merge pull request RustPython#570 from coolreader18/wasm-vm-inject_module
Add an `injectModule` method to WASMVirtualMachine
2 parents e34c8af + f619612 commit 387c21f

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

wasm/lib/src/vm_class.rs

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use crate::browser_module::setup_browser_module;
22
use crate::convert;
33
use crate::wasm_builtins;
4-
use js_sys::{SyntaxError, TypeError};
4+
use js_sys::{Object, SyntaxError, TypeError};
55
use rustpython_vm::{
66
compile,
7-
pyobject::{PyFuncArgs, PyObjectRef, PyResult},
7+
pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult},
88
VirtualMachine,
99
};
1010
use std::cell::RefCell;
@@ -281,6 +281,32 @@ impl WASMVirtualMachine {
281281
)?
282282
}
283283

284+
#[wasm_bindgen(js_name = injectModule)]
285+
pub fn inject_module(&self, name: String, module: Object) -> Result<(), JsValue> {
286+
self.with(|StoredVirtualMachine { ref mut vm, .. }| {
287+
let mut module_items: HashMap<String, PyObjectRef> = HashMap::new();
288+
for entry in convert::object_entries(&module) {
289+
let (key, value) = entry?;
290+
let key = Object::from(key).to_string();
291+
module_items.insert(key.into(), convert::js_to_py(vm, value));
292+
}
293+
294+
let mod_name = name.clone();
295+
296+
let stdlib_init_fn = move |ctx: &PyContext| {
297+
let py_mod = ctx.new_module(&name, ctx.new_scope(None));
298+
for (key, value) in module_items.clone() {
299+
ctx.set_attr(&py_mod, &key, value);
300+
}
301+
py_mod
302+
};
303+
304+
vm.stdlib_inits.insert(mod_name, Box::new(stdlib_init_fn));
305+
306+
Ok(())
307+
})?
308+
}
309+
284310
fn run(&self, mut source: String, mode: compile::Mode) -> Result<JsValue, JsValue> {
285311
self.assert_valid()?;
286312
self.with_unchecked(

0 commit comments

Comments
 (0)