WebAssembly/Reference types
The WebAssembly reference types extension adds support for two opaque types - externref and funcref. They are managed by the host and cannot be stored in linear memory. They can be used as function parameters (they can only be passed by value), local variables, function results, and as WebAssembly globals.
Free Pascal support
Partial support for reference types was merged into the main FPC branch on Jun 26 2023.
externref
There is a new type in the System unit, called WasmExternRef. It represents the externref WebAssembly type.
funcref
Procedural types can now be declared as WasmFuncRef. For example:
type TMyWasmFuncRef = function(a: longint; b: int64): longint; WasmFuncRef;
These types represent the funcref WebAssembly type.
Restrictions
The WebAssembly reference types don't have an in-memory representation. Therefore, the following is not allowed:
- Taking their address
- Taking their size, using sizeof() or bitsizeof()
- Using them as a field in a record, object or class
- Passing them as var, constref or out parameters
- Typecasting them to pointer, or integer, or any other type that is not a WebAssembly reference type
- Comparing them by value (they can only be compared to nil)
Allowed operations
The WebAssembly reference types can be used in the following ways:
- as procedure and function parameters, passed by value
- as function results
- as local variables
- as WebAssembly globals
- they can be assigned the value nil
- they can be compared to nil, or used as a parameter to assigned()
- they can be copied (a := b)
Future features (Not yet implemented)
The following seem to be possible to implement in the future, but is not yet implemented:
- putting reference types inside tables, which can be modeled in Pascal as dynamic arrays, declared as WebAssembly globals
- calling funcrefs
- converting a normal Pascal function to a funcref
- with the multivalue extension, it is possible to allow them as out or var parameters. In this case, they would need to be converted as extra function results.
An additional WebAssembly proposal might allow equality comparison between reference types (currently, only comparison to nil is allowed).