Files
Edoardo Vacchi 2c14bbff3d feat: typed function references spec (#2497)
Add experimental support for the [Typed Function References](https://github.com/WebAssembly/function-references)
proposal.

Closes https://github.com/wazero/wazero/issues/2483, follows up to the
refactoring in https://github.com/wazero/wazero/pull/2495 and prepares
to WasmGC.

Typed function references extend WebAssembly's type system with
non-nullable reference types and concrete function type indices (`(ref
$t)`, `(ref null $t)`), enabling direct calls through typed references
(`call_ref`, `return_call_ref`) and null-aware branching (`br_on_null`,
`br_on_non_null`, `ref.as_non_null`).

Excluding tests and spec suites, the feature amounts to roughly 1,900
lines of code.

Feature flag: `experimental.CoreFeaturesTypedFunctionReferences`

## What's the use for this?

Sadly, very little. This proposal is a pretty much just a prerequisite
for the GC proposal.

On the flip side, it completes the exception handling spec
(https://github.com/wazero/wazero/pull/2489):
1. two EH spec tests were previously skipped because they required
distinguishing nullable from non-nullable references. Those tests now
pass.
2. The fuzzer is now enabled for both exception handling and typed
function references. It could not be enabled for EH because the fuzzer
would generate func refs.

So I guess, technically, it has a use :D

## Type System

`ValueType` (already `uint64` introduced in
https://github.com/wazero/wazero/pull/2495) is now extended with bit
flags to encode nullability and concrete type indices:

| Bits  | Purpose                         |
|-------|---------------------------------|
| 0-7   | Base type byte (same as before) |
| 8     | Non-nullable flag               |
| 9     | Concrete ref flag               |
| 32-63 | Type index (for `(ref $t)`)     |

This encoding should be fine for WasmGC too and should not require
further changes in the near future.

Subtyping rules: non-nullable is a subtype of nullable (same
kind/index); concrete function refs `(ref $t)` are subtypes of
`funcref`.

## New Instructions

| Opcode | Hex | Description |

|-------------------|--------|----------------------------------------------------------|
| `call_ref` | `0x14` | Indirect call through a typed function reference
|
| `return_call_ref` | `0x15` | Tail-call variant of `call_ref` |
| `ref.as_non_null` | `0xd4` | Assert ref is non-null, trap otherwise |
| `br_on_null` | `0xd5` | Branch if null, push non-null ref on
fall-through |
| `br_on_non_null` | `0xd6` | Branch if non-null (carrying the ref),
fall-through on null |

## Validation

Tricky bits:

- Non-nullable local initialization tracking: `local.get` on a
non-nullable ref local is rejected unless a `local.set`/`local.tee` has
been executed in the same or enclosing block scope. State is
saved/restored at block boundaries per the spec (needed an additional
field to keep track of init'd values)
- `ref.func` now pushes `(ref $t)` (the concrete non-nullable type of
the referenced function) onto the validation type stack instead of plain
`funcref`, so that passing it to `call_ref` type-checks without an
upcast.
- Block types, element segments, table types, and const expressions all
support concrete ref types.
- The type section now validates forward references (standalone types
can only reference previously defined types; rec group members can
reference each other).

## Interpreter

The five new opcodes are compiled to new IR operations and executed in
the interpreter loop. `call_ref` / `return_call_ref` load the function
instance from the opaque reference pointer, null-check, and dispatch.
`br_on_null` / `br_on_non_null` pop the reference, check nullity, and
either branch or fall through with the appropriate stack state.

## Compiler (wazevo)

Implemented entirely as SSA-level lowering with no backend-specific
code:

- `call_ref` / `return_call_ref`: load executable and module context
pointers from the function instance, null-check via
`ExitIfTrueWithCode(ExitCodeNullReference)`, then dispatch as an
indirect call.
- `br_on_null` / `br_on_non_null`: compare against zero, branch with
trampoline blocks for try-table exits and listener support.
- `ref.as_non_null`: null-check with trap.

## Binary Decoding

- `decodeRefType` helper extracted and shared across `value.go`,
`element.go`, `table.go`, and `code.go` for consistent handling of `(ref
null ht)` / `(ref ht)` prefixes.
- Tables support the `0x40 0x00` prefix for initializer expressions
(required for non-nullable table element types).
- `DecodeBlockType` handles concrete ref types as block results.

## Cross-Module Linking

`call_indirect` uses `FunctionTypeID` for fast runtime type checks. The
existing `FunctionType.key()` method builds the key from raw `ValueType`
bytes, but with concrete refs `(ref $0)` in module A and `(ref $0)` in
module B may refer to structurally identical types at different local
indices. `structuralTypeKey` fixes this by replacing local type indices
with the already-assigned `FunctionTypeID` of the referenced type, so
two modules with the same structural signature share a single
`FunctionTypeID`.

## Spec Suite

The spec test suite uses `wasm-tools json-from-wast` (same as exception
handling). All 22 test files pass.

## Fuzzing

The fuzzer (`nodiff`) now enables both `CoreFeaturesExceptionHandling`
and `CoreFeaturesTypedFunctionReferences`. Dummy import generation
handles `exnref` and concrete ref types.

---------

Signed-off-by: Edoardo Vacchi <evacchi@users.noreply.github.com>
2026-05-28 15:57:29 +02:00

229 lines
8.9 KiB
Go

package api
import (
"fmt"
"strings"
)
// CoreFeatures is a bit flag of WebAssembly Core specification features. See
// https://github.com/WebAssembly/proposals for proposals and their status.
//
// Constants define individual features, such as CoreFeatureMultiValue, or
// groups of "finished" features, assigned to a WebAssembly Core Specification
// version, e.g. CoreFeaturesV1 or CoreFeaturesV2.
//
// Note: Numeric values are not intended to be interpreted except as bit flags.
type CoreFeatures uint64
// CoreFeaturesV1 are features included in the WebAssembly Core Specification
// 1.0. As of late 2022, this is the only version that is a Web Standard (W3C
// Recommendation).
//
// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/
const CoreFeaturesV1 = CoreFeatureMutableGlobal
// CoreFeaturesV2 are features included in the WebAssembly Core Specification
// 2.0 (20220419). As of late 2022, version 2.0 is a W3C working draft, not yet
// a Web Standard (W3C Recommendation).
//
// See https://www.w3.org/TR/2022/WD-wasm-core-2-20220419/appendix/changes.html#release-1-1
const CoreFeaturesV2 = CoreFeaturesV1 |
CoreFeatureBulkMemoryOperations |
CoreFeatureMultiValue |
CoreFeatureNonTrappingFloatToIntConversion |
CoreFeatureReferenceTypes |
CoreFeatureSignExtensionOps |
CoreFeatureSIMD
const (
// CoreFeatureBulkMemoryOperations adds instructions modify ranges of
// memory or table entries ("bulk-memory-operations"). This is included in
// CoreFeaturesV2, but not CoreFeaturesV1.
//
// Here are the notable effects:
// - Adds `memory.fill`, `memory.init`, `memory.copy` and `data.drop`
// instructions.
// - Adds `table.init`, `table.copy` and `elem.drop` instructions.
// - Introduces a "passive" form of element and data segments.
// - Stops checking "active" element and data segment boundaries at
// compile-time, meaning they can error at runtime.
//
// Note: "bulk-memory-operations" is mixed with the "reference-types"
// proposal due to the WebAssembly Working Group merging them
// "mutually dependent". Therefore, enabling this feature requires enabling
// CoreFeatureReferenceTypes, and vice-versa.
//
// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/bulk-memory-operations/Overview.md
// https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/reference-types/Overview.md and
// https://github.com/WebAssembly/spec/pull/1287
CoreFeatureBulkMemoryOperations CoreFeatures = 1 << iota
// CoreFeatureMultiValue enables multiple values ("multi-value"). This is
// included in CoreFeaturesV2, but not CoreFeaturesV1.
//
// Here are the notable effects:
// - Function (`func`) types allow more than one result.
// - Block types (`block`, `loop` and `if`) can be arbitrary function
// types.
//
// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/multi-value/Overview.md
CoreFeatureMultiValue
// CoreFeatureMutableGlobal allows globals to be mutable. This is included
// in both CoreFeaturesV1 and CoreFeaturesV2.
//
// When false, an api.Global can never be cast to an api.MutableGlobal, and
// any wasm that includes global vars will fail to parse.
CoreFeatureMutableGlobal
// CoreFeatureNonTrappingFloatToIntConversion enables non-trapping
// float-to-int conversions ("nontrapping-float-to-int-conversion"). This
// is included in CoreFeaturesV2, but not CoreFeaturesV1.
//
// The only effect of enabling is allowing the following instructions,
// which return 0 on NaN instead of panicking.
// - `i32.trunc_sat_f32_s`
// - `i32.trunc_sat_f32_u`
// - `i32.trunc_sat_f64_s`
// - `i32.trunc_sat_f64_u`
// - `i64.trunc_sat_f32_s`
// - `i64.trunc_sat_f32_u`
// - `i64.trunc_sat_f64_s`
// - `i64.trunc_sat_f64_u`
//
// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/nontrapping-float-to-int-conversion/Overview.md
CoreFeatureNonTrappingFloatToIntConversion
// CoreFeatureReferenceTypes enables various instructions and features
// related to table and new reference types. This is included in
// CoreFeaturesV2, but not CoreFeaturesV1.
//
// - Introduction of new value types: `funcref` and `externref`.
// - Support for the following new instructions:
// - `ref.null`
// - `ref.func`
// - `ref.is_null`
// - `table.fill`
// - `table.get`
// - `table.grow`
// - `table.set`
// - `table.size`
// - Support for multiple tables per module:
// - `call_indirect`, `table.init`, `table.copy` and `elem.drop`
// - Support for instructions can take non-zero table index.
// - Element segments can take non-zero table index.
//
// Note: "reference-types" is mixed with the "bulk-memory-operations"
// proposal due to the WebAssembly Working Group merging them
// "mutually dependent". Therefore, enabling this feature requires enabling
// CoreFeatureBulkMemoryOperations, and vice-versa.
//
// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/bulk-memory-operations/Overview.md
// https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/reference-types/Overview.md and
// https://github.com/WebAssembly/spec/pull/1287
CoreFeatureReferenceTypes
// CoreFeatureSignExtensionOps enables sign extension instructions
// ("sign-extension-ops"). This is included in CoreFeaturesV2, but not
// CoreFeaturesV1.
//
// Adds instructions:
// - `i32.extend8_s`
// - `i32.extend16_s`
// - `i64.extend8_s`
// - `i64.extend16_s`
// - `i64.extend32_s`
//
// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/sign-extension-ops/Overview.md
CoreFeatureSignExtensionOps
// CoreFeatureSIMD enables the vector value type and vector instructions
// (aka SIMD). This is included in CoreFeaturesV2, but not CoreFeaturesV1.
//
// Note: The instruction list is too long to enumerate in godoc.
// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/simd/SIMD.md
CoreFeatureSIMD
// Update experimental/features.go when adding elements here.
)
// SetEnabled enables or disables the feature or group of features.
func (f CoreFeatures) SetEnabled(feature CoreFeatures, val bool) CoreFeatures {
if val {
return f | feature
}
return f &^ feature
}
// IsEnabled returns true if the feature (or group of features) is enabled.
func (f CoreFeatures) IsEnabled(feature CoreFeatures) bool {
return f&feature != 0
}
// RequireEnabled returns an error if the feature (or group of features) is not
// enabled.
func (f CoreFeatures) RequireEnabled(feature CoreFeatures) error {
if f&feature == 0 {
return fmt.Errorf("feature %q is disabled", feature)
}
return nil
}
// String implements fmt.Stringer by returning each enabled feature.
func (f CoreFeatures) String() string {
var builder strings.Builder
for i := 0; i <= 63; i++ { // cycle through all bits to reduce code and maintenance
target := CoreFeatures(1 << i)
if f.IsEnabled(target) {
if name := featureName(target); name != "" {
if builder.Len() > 0 {
builder.WriteByte('|')
}
builder.WriteString(name)
}
}
}
return builder.String()
}
func featureName(f CoreFeatures) string {
switch f {
case CoreFeatureMutableGlobal:
// match https://github.com/WebAssembly/mutable-global
return "mutable-global"
case CoreFeatureSignExtensionOps:
// match https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/sign-extension-ops/Overview.md
return "sign-extension-ops"
case CoreFeatureMultiValue:
// match https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/multi-value/Overview.md
return "multi-value"
case CoreFeatureNonTrappingFloatToIntConversion:
// match https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/nontrapping-float-to-int-conversion/Overview.md
return "nontrapping-float-to-int-conversion"
case CoreFeatureBulkMemoryOperations:
// match https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/bulk-memory-operations/Overview.md
return "bulk-memory-operations"
case CoreFeatureReferenceTypes:
// match https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/reference-types/Overview.md
return "reference-types"
case CoreFeatureSIMD:
// match https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/simd/SIMD.md
return "simd"
// The cases below cover features defined in the experimental package
// (experimental.CoreFeaturesThreads, CoreFeaturesTailCall,
// experimental.CoreFeaturesExtendedConst, experimental.CoreFeaturesExceptionHandling).
// They cannot be imported here (circular dependency), so we match by value.
case CoreFeatureSIMD << 1: // experimental.CoreFeaturesThreads
return "threads"
case CoreFeatureSIMD << 2: // experimental.CoreFeaturesTailCall
return "tail-call"
case CoreFeatureSIMD << 3: // experimental.CoreFeaturesExtendedConst
return "extended-const"
case CoreFeatureSIMD << 4: // experimental.CoreFeaturesExceptionHandling
return "exception-handling"
case CoreFeatureSIMD << 5: // experimental.CoreFeaturesTypedFunctionReferences
return "typed-function-references"
}
return ""
}