WebAssembly/Reference types

From Lazarus wiki
Revision as of 18:42, 20 June 2023 by Nickysn (talk | contribs) (Future features (not yet implemented/TODO))
Jump to navigationJump to search

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

Support for reference types is partially implemented in the wasm_js_promise_integration branch: [1]

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 opaque
  • 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)

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

An additional WebAssembly proposal might allow equality comparison between reference types (currently, only comparison to nil is allowed).

See also