MCPcopy Index your code
hub / github.com/RustPython/RustPython / py_to_js

Function py_to_js

crates/wasm/src/convert.rs:90–163  ·  view source on GitHub ↗
(vm: &VirtualMachine, py_obj: PyObjectRef)

Source from the content-addressed store, hash-verified

88}
89
90pub fn py_to_js(vm: &VirtualMachine, py_obj: PyObjectRef) -> JsValue {
91 if let Some(ref wasm_id) = vm.wasm_id
92 && py_obj.fast_isinstance(vm.ctx.types.function_type)
93 {
94 let wasm_vm = WASMVirtualMachine {
95 id: wasm_id.clone(),
96 };
97 let weak_py_obj = wasm_vm.push_held_rc(py_obj).unwrap().unwrap();
98
99 let closure = move |args: Option<Box<[JsValue]>>,
100 kwargs: Option<Object>|
101 -> Result<JsValue, JsValue> {
102 let py_obj = match wasm_vm.assert_valid() {
103 Ok(_) => weak_py_obj
104 .upgrade()
105 .expect("weak_py_obj to be valid if VM is valid"),
106 Err(err) => {
107 return Err(err);
108 }
109 };
110 stored_vm_from_wasm(&wasm_vm).interp.enter(move |vm| {
111 let args = match args {
112 Some(args) => Vec::from(args)
113 .into_iter()
114 .map(|arg| js_to_py(vm, arg))
115 .collect::<Vec<_>>(),
116 None => Vec::new(),
117 };
118 let mut py_func_args = FuncArgs::from(args);
119 if let Some(ref kwargs) = kwargs {
120 for pair in object_entries(kwargs) {
121 let (key, val) = pair?;
122 py_func_args
123 .kwargs
124 .insert(js_sys::JsString::from(key).into(), js_to_py(vm, val));
125 }
126 }
127 let result = py_obj.call(py_func_args, vm);
128 pyresult_to_js_result(vm, result)
129 })
130 };
131 let closure = Closure::wrap(Box::new(closure)
132 as Box<
133 dyn FnMut(Option<Box<[JsValue]>>, Option<Object>) -> Result<JsValue, JsValue>,
134 >);
135 let func = closure.as_ref().clone();
136
137 // stores pretty much nothing, it's fine to leak this because if it gets dropped
138 // the error message is worse
139 closure.forget();
140
141 return func;
142 }
143 // the browser module might not be injected
144 if vm.try_class("_js", "Promise").is_ok()
145 && let Some(py_prom) = py_obj.downcast_ref::<js_module::PyPromise>()
146 {
147 return py_prom.as_js(vm).into();

Callers 4

as_jsMethod · 0.85
pyresult_to_js_resultFunction · 0.85
js_to_pyFunction · 0.85
fetchFunction · 0.85

Calls 15

stored_vm_from_wasmFunction · 0.85
js_to_pyFunction · 0.85
newFunction · 0.85
object_entriesFunction · 0.85
pyresult_to_js_resultFunction · 0.85
fast_isinstanceMethod · 0.80
push_held_rcMethod · 0.80
assert_validMethod · 0.80
try_classMethod · 0.80
as_jsMethod · 0.80
with_refMethod · 0.80
ErrClass · 0.50

Tested by

no test coverage detected