-
Notifications
You must be signed in to change notification settings - Fork 84
Suggestion: Combine opaque external references with explicit wasm-extern casts #307
Description
In issue #293, we discussed the possibility that funcref
not be a subtype of anyref
, to avoid representation-change costs at the JS/Wasm boundary. It is reasonable to assume that other types might also require similar transformations in the future: i31ref
will most probably require some form of range check, and it is not unlikely that structs and arrays will require some wrapping to function optimally in both worlds.
This creates a situation where passing a value to wasm as anyref
carries significant cost at the boundary, since every object has to be checked against every Wasm type, in case a representation change has to be applied. The idea to apply these checks during downcasts from anyref
will not work, as we would need to apply the reverse transformation when upcasting to anyref
, breaking the fundamental assumption that upcasts are no-ops.
Therefore I suggest the following (assuming funcref <: anyref
, but this does not matter for this discussion):
- Reintroduce an
externref
type which represents host references in the host's representation. This will be separate from the type hierarchy, i.e. not a subtype ofanyref
. - Specify that
anyref
is not just a supertype offuncref
,i31ref
, anddataref
, but in fact contains no values that do not classify as one of these three types. In other words,anyref
is the type of all references that can be generated by a wasm module. - Introduce explicit casts from
anyref
toexternref
and vice versa. These will not be free, and will perform the same representation change as at the Wasm/JS boundary. For performance, we will also introduce additional casts fromexternref
to more specific types. The specifics of the representation change will of course depend on the module's host.
With this design
- an API that wants to pass opaque references to Wasm can pass them as
externref
and have the guarantee that there is no cost at the boundary. Such references might even be Wasm references (albeit in the host's representation); this way, another Wasm module can create objects internally and pass them to anexternref
interface. - an API that wants to pass references of specific Wasm types can do so, accepting the cost of representation change. Note that this is likely to be quite minimal for more concrete types than
anyref
.
I understand that the premise of this post is not a given. However, I also do not see the downside: even if we decide that funcref </: anyref
, we allow for more flexibility in the implementation of other (current and future) reference types, and allow Wasm modules to specify more cleanly whether they expose an opaque interface.