Skip to content

Commit e4f247a

Browse files
committed
Convert to PyJsFunction instead of just a closure
1 parent edbb328 commit e4f247a

File tree

2 files changed

+17
-17
lines changed

2 files changed

+17
-17
lines changed

wasm/lib/src/convert.rs

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustpython_vm::pyobject::{PyObjectRef, PyResult, PyValue};
88
use rustpython_vm::VirtualMachine;
99

1010
use crate::browser_module;
11-
use crate::objjsvalue::PyJsValue;
11+
use crate::objjsvalue::{PyJsFunction, PyJsValue};
1212
use crate::vm_class::{stored_vm_from_wasm, WASMVirtualMachine};
1313

1414
pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &PyObjectRef) -> JsValue {
@@ -155,6 +155,14 @@ pub fn pyresult_to_jsresult(vm: &VirtualMachine, result: PyResult) -> Result<JsV
155155
}
156156

157157
pub fn js_to_py(vm: &VirtualMachine, js_val: JsValue) -> PyObjectRef {
158+
js_to_py_with_this(vm, js_val, None)
159+
}
160+
161+
pub fn js_to_py_with_this(
162+
vm: &VirtualMachine,
163+
js_val: JsValue,
164+
this: Option<JsValue>,
165+
) -> PyObjectRef {
158166
if js_val.is_object() {
159167
if let Some(promise) = js_val.dyn_ref::<Promise>() {
160168
// the browser module might not be injected
@@ -197,22 +205,7 @@ pub fn js_to_py(vm: &VirtualMachine, js_val: JsValue) -> PyObjectRef {
197205
}
198206
} else if js_val.is_function() {
199207
let func = js_sys::Function::from(js_val);
200-
vm.ctx
201-
.new_rustfunc(move |vm: &VirtualMachine, args: PyFuncArgs| -> PyResult {
202-
let func = func.clone();
203-
let this = Object::new();
204-
for (k, v) in args.kwargs {
205-
Reflect::set(&this, &k.into(), &py_to_js(vm, v))
206-
.expect("property to be settable");
207-
}
208-
let js_args = Array::new();
209-
for v in args.args {
210-
js_args.push(&py_to_js(vm, v));
211-
}
212-
func.apply(&this, &js_args)
213-
.map(|val| js_to_py(vm, val))
214-
.map_err(|err| js_to_py(vm, err))
215-
})
208+
PyJsFunction::new(func, this).into_ref(vm).into_object()
216209
} else if let Some(err) = js_val.dyn_ref::<js_sys::Error>() {
217210
let exc_type = match String::from(err.name()).as_str() {
218211
"TypeError" => &vm.ctx.exceptions.type_error,

wasm/lib/src/objjsvalue.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,13 @@ impl PyJsFunction {
8787
.map(|val| convert::js_to_py(vm, val))
8888
.map_err(|err| convert::js_to_py(vm, err))
8989
}
90+
91+
#[pymethod(name = "__repr__")]
92+
fn repr(&self, _vm: &VirtualMachine) -> String {
93+
// for better formatting
94+
let value: &JsValue = &self.func;
95+
format!("{:?}", value)
96+
}
9097
}
9198

9299
#[pyclass(name = "JsProps")]

0 commit comments

Comments
 (0)