|
1 | 1 | use crate::browser_module::setup_browser_module;
|
2 | 2 | use crate::convert;
|
3 | 3 | use crate::wasm_builtins;
|
4 |
| -use js_sys::{SyntaxError, TypeError}; |
| 4 | +use js_sys::{Object, SyntaxError, TypeError}; |
5 | 5 | use rustpython_vm::{
|
6 | 6 | compile,
|
7 |
| - pyobject::{PyFuncArgs, PyObjectRef, PyResult}, |
| 7 | + pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult}, |
8 | 8 | VirtualMachine,
|
9 | 9 | };
|
10 | 10 | use std::cell::RefCell;
|
@@ -281,6 +281,32 @@ impl WASMVirtualMachine {
|
281 | 281 | )?
|
282 | 282 | }
|
283 | 283 |
|
| 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 | + |
284 | 310 | fn run(&self, mut source: String, mode: compile::Mode) -> Result<JsValue, JsValue> {
|
285 | 311 | self.assert_valid()?;
|
286 | 312 | self.with_unchecked(
|
|
0 commit comments