function-references icon indicating copy to clipboard operation
function-references copied to clipboard

Function reference from JavaScript functions?

Open fgmccabe opened this issue 10 months ago • 4 comments

I was under the impression that this proposal would allow JavaScript functions to be stored in function tables and returned as a result of a call to an import. I can't locate the appropriate changes to the JS-API spec that would accomodate this; specifically.

fgmccabe avatar Mar 28 '24 22:03 fgmccabe

I don't know whether the omission was intentional or not, but this proposal does not allow that. It would have to change to "create a host function" from ToWebAssemblyValue when the destination type is a typed function reference.

tlively avatar Mar 29 '24 16:03 tlively

So, how is someone expected to dynamically pass a callback to wasm?

fgmccabe avatar Mar 29 '24 20:03 fgmccabe

Use the not-yet-standard WebAssembly.Function or create a tiny WebAssembly module that imports and re-exports the function. The re-exported function can be put in the table.

Here's where we do this in Emscripten: https://github.com/emscripten-core/emscripten/blob/af763a9099fcf1511e889057759de8cf8907db07/src/library_addfunction.js#L97-L137

We should really fix this in the spec, although it won't help the Emscripten case because Emscripten's function table holds untyped funcref.

tlively avatar Mar 29 '24 20:03 tlively

There is no implicit conversion for function references, you'll have to use WebAssembly.Function. That is the only way I am aware to reliably provide the necessary Wasm type information to make it callable from inside Wasm. A table may well have type funcref, which is not sufficient.

We could presumably add a hack to the API to make the call to WA.Function implicit in the special case that the table (or a global?) has a concrete function type, but it won't work in general. But the discontinuity this creates seems dubious to me – it essentially violates subtyping if something works at a subtype, but can break clients when weakening(!) an input type to a supertype like funcref where it doesn't.

rossberg avatar Apr 02 '24 06:04 rossberg