webassembly/proxy_js: Allow a Python proxy of a function to be undone.

This optimises the case where a Python function is, for example, stored to
a JavaScript attribute and then later retrieved from Python.  The Python
function no longer needs to be a proxy with double proxying needed for the
call from Python -> JavaScript -> Python.

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Damien George
2024-03-29 23:58:50 +11:00
parent 7c62fbe3f2
commit 5114f2c1ea
4 changed files with 92 additions and 7 deletions

View File

@@ -48,9 +48,17 @@ EM_JS(bool, lookup_attr, (int jsref, const char *str, uint32_t * out), {
const attr = UTF8ToString(str);
if (attr in base) {
let value = base[attr];
if (typeof value == "function") {
if (typeof value === "function") {
if (base !== globalThis) {
value = value.bind(base);
if ("_ref" in value) {
// This is a proxy of a Python function, it doesn't need
// binding. And not binding it means if it's passed back
// to Python then it can be extracted from the proxy as a
// true Python function.
} else {
// A function that is not a Python function. Bind it.
value = value.bind(base);
}
}
}
proxy_convert_js_to_mp_obj_jsside(value, out);

View File

@@ -135,10 +135,11 @@ function proxy_convert_js_to_mp_obj_jsside(js_obj, out) {
Module.stringToUTF8(js_obj, buf, len + 1);
Module.setValue(out + 4, len, "i32");
Module.setValue(out + 8, buf, "i32");
} else if (js_obj instanceof PyProxy) {
kind = PROXY_KIND_JS_PYPROXY;
Module.setValue(out + 4, js_obj._ref, "i32");
} else if (js_obj instanceof PyProxyThenable) {
} else if (
js_obj instanceof PyProxy ||
(typeof js_obj === "function" && "_ref" in js_obj) ||
js_obj instanceof PyProxyThenable
) {
kind = PROXY_KIND_JS_PYPROXY;
Module.setValue(out + 4, js_obj._ref, "i32");
} else {
@@ -151,7 +152,11 @@ function proxy_convert_js_to_mp_obj_jsside(js_obj, out) {
}
function proxy_convert_js_to_mp_obj_jsside_force_double_proxy(js_obj, out) {
if (js_obj instanceof PyProxy) {
if (
js_obj instanceof PyProxy ||
(typeof js_obj === "function" && "_ref" in js_obj) ||
js_obj instanceof PyProxyThenable
) {
const kind = PROXY_KIND_JS_OBJECT;
const id = proxy_js_ref.length;
proxy_js_ref[id] = js_obj;
@@ -212,6 +217,7 @@ function proxy_convert_mp_to_js_obj_jsside(value) {
obj = (...args) => {
return proxy_call_python(id, args);
};
obj._ref = id;
} else if (kind === PROXY_KIND_MP_GENERATOR) {
obj = new PyProxyThenable(id);
} else {