binary

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	CanonKindLift              byte = 0x00
	CanonKindLower             byte = 0x01
	CanonKindResourceNew       byte = 0x02
	CanonKindResourceDrop      byte = 0x03
	CanonKindResourceRep       byte = 0x04
	CanonKindResourceDropAsync byte = 0x07

	CanonKindTaskCancel               byte = 0x05
	CanonKindSubtaskCancel            byte = 0x06
	CanonKindTaskReturn               byte = 0x09
	CanonKindContextGet               byte = 0x0a
	CanonKindContextSet               byte = 0x0b
	CanonKindThreadYield              byte = 0x0c
	CanonKindSubtaskDrop              byte = 0x0d
	CanonKindStreamNew                byte = 0x0e
	CanonKindStreamRead               byte = 0x0f
	CanonKindStreamWrite              byte = 0x10
	CanonKindStreamCancelRead         byte = 0x11
	CanonKindStreamCancelWrite        byte = 0x12
	CanonKindStreamDropReadable       byte = 0x13
	CanonKindStreamDropWritable       byte = 0x14
	CanonKindFutureNew                byte = 0x15
	CanonKindFutureRead               byte = 0x16
	CanonKindFutureWrite              byte = 0x17
	CanonKindFutureCancelRead         byte = 0x18
	CanonKindFutureCancelWrite        byte = 0x19
	CanonKindFutureDropReadable       byte = 0x1a
	CanonKindFutureDropWritable       byte = 0x1b
	CanonKindErrorContextNew          byte = 0x1c
	CanonKindErrorContextDebugMessage byte = 0x1d
	CanonKindErrorContextDrop         byte = 0x1e
	CanonKindWaitableSetNew           byte = 0x1f
	CanonKindWaitableSetWait          byte = 0x20
	CanonKindWaitableSetPoll          byte = 0x21
	CanonKindWaitableSetDrop          byte = 0x22
	CanonKindWaitableJoin             byte = 0x23
	CanonKindBackpressureInc          byte = 0x24
	CanonKindBackpressureDec          byte = 0x25
	CanonKindThreadIndex              byte = 0x26
	CanonKindThreadNewIndirect        byte = 0x27
	CanonKindThreadSuspend            byte = 0x29
	CanonKindThreadYieldThenResume    byte = 0x2b
)

CanonKind names the byte values Canon.Kind takes -- the first byte of each entry in the canonical-function section (id 0x08). 0x00-0x04 were already implemented; 0x05 and up are the Phase 0 async additions. Verified against wasm-tools 1.253 (`wasm-tools dump`) on internal/component/binary/testdata/ async/*.wasm -- see decodeCanonSection and canonKindName.

0x07 (resource.drop async) was added in Phase 3 -- see docs/component-model-async-phase3-design.md §4.4; its payload (a single typeidx) is byte-identical to 0x03's, verified against fresh wasm-tools output the same way as every other kind in this table.

CanonKindThreadYield/Index/NewIndirect/Suspend/YieldThenResume are the five thread.* builtins actually exercised by the vendored async .wast suites (cancellable, sync-barges-in, trap-if-sync-and-waitable-set, trap-if- block-and-sync); their opcodes and payload grammars are taken from the component-model spec's design/mvp/Binary.md canon-definitions EBNF (the 🧵/🔀 threads-proposal entries), cross-checked against `wasm-tools dump` on those four fixtures. The REMAINING thread.* opcodes (0x28 resume-later, 0x2a/0x2c/0x2d suspend/yield-then-promote, 0x40-0x42 spawn-ref/spawn- indirect/available-parallelism) are deliberately NOT added here: no vendored suite decodes one, so their byte layouts are unverified against a real fixture -- add them (and their decode case) only once a suite that actually needs them shows up. Decoding these five is NOT the same as implementing thread.* execution (no runtime support exists for any of them -- see stream_builtins.go/async_builtins.go's absence of a thread.yield/thread.new-indirect host func); every suite that reaches one at CALL time (not just decode) still traps or hangs on its own, real gap.

Variables

View Source
var (
	ErrInvalidMagicNumber = errors.New("invalid magic number")
	ErrInvalidVersion     = errors.New("invalid version header")
	ErrInvalidLayer       = errors.New("invalid layer header (expected component layer 0x01 0x00)")
	ErrInvalidSectionID   = errors.New("invalid section id")
	ErrTruncatedBinary    = errors.New("truncated binary")
)

Functions

func CoreModuleExports added in v0.6.0

func CoreModuleExports(module []byte, fn func(name []byte, kind byte)) error

CoreModuleExports calls fn with each export of a core module -- its name, which aliases the module's bytes, and its sort -- reading the export section alone: every other section, the code included, is stepped over by its size. It is all a check of export names needs, and allocates nothing.

func IsValidMapKeyPrimitive added in v0.4.0

func IsValidMapKeyPrimitive(prim string) bool

IsValidMapKeyPrimitive reports whether prim is one of the primitives the Component Model spec's `keytype` grammar allows as a map key: bool, every integer width, char, or string. It only ever sees MapDesc.Key.Primitive, so it cannot itself resolve a key given by type index -- every keytype is, however, a bare primitive a conformant producer always spells inline (see readValTypeRef), so an index there (Key.Primitive == "") already names something keytype does not permit: a composite, a resource handle, or a stream/future. TypeTable.Map treats it that way for the one type index that can occur in this codebase's own type tables (which never assign an index to a primitive to begin with -- see TypeTable.Add).

Types

type AliasDef

type AliasDef struct {
	Sort        byte   // sort of the aliased item: 0x00 = core, 0x01 = func, 0x02 = value, 0x03 = type, 0x04 = component, 0x05 = instance
	TargetKind  byte   // 0x00 = export, 0x01 = core export, 0x02 = outer
	InstanceIdx uint32 // for export/core export targets
	Name        string // for export/core export targets
	OuterCount  uint32 // for outer targets
	OuterIndex  uint32 // for outer targets

	// CoreSort is the core:sort discriminator byte that follows Sort when
	// Sort == 0x00 (i.e. this alias names a core-level item): 0x00 func,
	// 0x01 table, 0x02 memory, 0x03 global, 0x04 tag, 0x10 type, 0x11
	// module, 0x12 instance. It is meaningless (and left at its zero value,
	// 0x00) when Sort != 0x00.
	//
	// A core-export alias (Sort == 0x00, TargetKind == 0x01) needs this to
	// tell a core-func alias apart from a core-memory/table/global alias --
	// see internal/component/instance, which used to disambiguate by
	// probing the instantiated target module's exports (a name that
	// resolves to a Function is a func alias) because this field didn't
	// exist; that probe is now a fallback for AliasDefs built by hand
	// (e.g. in tests) rather than by decodeAliasSection.
	CoreSort byte
}

AliasDef represents an alias binding (section 6).

type BorrowDesc

type BorrowDesc struct {
	ResourceType uint32
}

BorrowDesc represents a borrowed handle to a resource.

func (BorrowDesc) Kind

func (BorrowDesc) Kind() string

type Canon

type Canon struct {
	Kind        byte   // one of the CanonKind* constants
	CoreFuncIdx uint32 // used for lift (0x00)
	FuncIdx     uint32 // used for lower (0x01) and for result indices in Start
	Opts        []CanonOpt
	TypeIdx     uint32 // lift's type index; resource.*'s type index; the

	// Async is the async_:bool payload of subtask.cancel, stream.cancel-read/
	// -write, and future.cancel-read/-write.
	Async bool

	// Cancellable is waitable-set.wait/poll's cancellable:bool payload, and
	// (decode-only -- see CanonKindThreadYield's doc) thread.yield/thread.
	// suspend/thread.yield-then-resume's identically-shaped cancel:bool.
	Cancellable bool

	// TableIdx is thread.new-indirect's tbl:<core:tableidx> payload
	// (decode-only). TypeIdx doubles as its ft:<typeidx> payload.
	TableIdx uint32

	// MemIdx is waitable-set.wait/poll's memory index. (error-context.new/
	// debug-message also take a memory, but via the existing Opts memory
	// option (0x03), same as lift/lower -- they don't need this field.)
	MemIdx uint32

	// CoreValType is context.get/context.set's `ty` payload: a single CORE
	// valtype byte (e.g. 0x7f = i32), not a component valtype -- same
	// encoding as ResourceDesc.Rep. See coreValtypeName.
	CoreValType byte

	// Slot is context.get/context.set's `slot` payload (a context-storage
	// index, not a type or func index).
	Slot uint32

	// TaskReturnResult is task.return's result list. Verified via
	// `wasm-tools dump`/round-trip probes (not just the fixtures) that this
	// is encoded with the EXACT SAME grammar as a functype's result list
	// (readResultListDesc): tag 0x00 + one valtype ("unnamed", e.g. `(result
	// u32)`), or tag 0x01 + vec(labelvaltype) ("named", empty for a
	// no-result task.return). This resolves the brief's flagged ambiguity:
	// task.return's `(result ...)` clause is NOT a bare option<valtype> --
	// bytes `09 00 79 00` decode as tag=0x00 (unnamed) valtype=0x79 (u32)
	// then an empty opts vec, while a no-result task.return encodes as
	// `09 01 00 00` (tag=0x01 named-list, count=0, then empty opts vec).
	TaskReturnResult FuncResults
}

Canon represents a canonical lift/lower binding (section 8).

type CanonOpt

type CanonOpt struct {
	Kind byte   // 0x00-0x07 (and potentially more)
	Idx  uint32 // for options that carry an index
}

CanonOpt represents a canonical option.

type Component

type Component struct {

	// Types contains the type definitions from the type section (section 7)
	// only, in that section's declaration order. This is NOT the full
	// component type index space that canon TypeIdx and export/instance type
	// references index into -- that space also includes type-sort aliases
	// and imported types, interleaved with Types in overall declaration
	// order. See TypeSpace and ResolveType.
	Types []Type

	// TypeSpace is the component's full type index space: one entry per
	// type-index-producing definition (type-section deftype, type-sort
	// alias, or imported type), in overall declaration order across
	// sections. Use ResolveType to resolve a type index through it rather
	// than indexing Types or TypeSpace directly. See typespace.go.
	TypeSpace []TypeSpaceEntry

	// Imports contains the import bindings.
	Imports []Import

	// Exports contains the export bindings.
	Exports []Export

	// ComponentFuncSpace is the component's func index space, one entry per
	// func-producing definition (func import / func alias / canon lift / func
	// export) in overall declaration order across sections. See
	// componentfuncspace.go.
	ComponentFuncSpace []ComponentFuncSpaceEntry

	// ComponentInstanceSpace is the component's instance index space, one
	// entry per instance-producing definition (instance import / instance
	// definition / instance alias / instance export) in overall declaration
	// order across sections. See componentinstancespace.go.
	ComponentInstanceSpace []ComponentInstanceSpaceEntry

	// ComponentSpace is the component's COMPONENT index space, one entry per
	// component-producing definition (component import / nested component
	// definition / component alias / component export) in overall declaration
	// order across sections. An instance definition's ComponentIdx indexes
	// this, not NestedComponents. See componentspace.go.
	ComponentSpace []ComponentSpaceEntry

	// CoreModules are embedded core wasm modules (section 1) only, in that
	// section's declaration order. This is NOT the core module index space a
	// core:instance's ModuleIdx indexes -- that space also includes core-
	// module outer aliases (section 6, sort core 0x00 / core:sort module
	// 0x11), interleaved with CoreModules in overall declaration order. See
	// CoreModuleSpace and ResolveCoreModule.
	CoreModules []CoreModule

	// CoreModuleSpace is the component's core module index space: one entry
	// per core-module-index-producing definition (section-1 embedded module or
	// section-6 core-module outer alias), in overall declaration order. Use
	// ResolveCoreModule rather than indexing CoreModules directly. See
	// coremodulespace.go.
	CoreModuleSpace []CoreModuleSpaceEntry

	// CoreTypes are the core type section's definitions, in order, and
	// CoreTypeSpace the core type index space they and the core type
	// aliases make -- see coretype.go.
	CoreTypes     []CoreTypeDef
	CoreTypeSpace []CoreTypeSpaceEntry

	// CoreInstances instantiate core modules with arguments (section 2).
	CoreInstances []CoreInstance

	// Instances instantiate components with arguments (section 5).
	Instances []Instance

	// NestedComponents are fully embedded sub-components (section 4), decoded
	// recursively -- per the Binary.md grammar, section_4(<component>) is a
	// complete component binary (its own magic/version/layer preamble plus
	// its own sections), not a bare section list. wit-component emits these
	// for a world that exports an interface: it packages the lifted core
	// funcs into a nested-component "shim" that re-exports them, and the
	// top-level export names an Instance (section 5) that instantiates this
	// nested component -- see internal/component/instance, which resolves
	// that shim to call the funcs it re-exports.
	//
	// Some real-world nested components (e.g. the wasip2 CLI adapter emitted
	// alongside a `wasi:cli/command` world) are far more complex than the
	// re-export shim -- they embed their own core module and full
	// instantiation graph. Those still decode fine here (this is a purely
	// structural, recursive decode with no semantic assumptions), but
	// internal/component/instance fails loud rather than trying to
	// instantiate them.
	NestedComponents []*Component

	// Outer is the component this one was decoded from as a section-4 nested
	// component (nil for a top-level component). It is what makes an
	// `alias outer <count> <idx>` with count > 0 resolvable: the de Bruijn
	// count is a number of enclosing components to skip, so resolution walks
	// this link that many times and then indexes the resulting component's
	// index space of the aliased sort. See ResolveType (typespace.go) and
	// ResolveCoreModule (coremodulespace.go).
	//
	// This makes the Component graph CYCLIC (parent -> NestedComponents ->
	// Outer -> parent). reflect.DeepEqual copes; fmt's %#v does not, so never
	// dump a whole Component with it.
	Outer *Component

	// Aliases bring names into scope (section 6).
	Aliases []AliasDef

	// Canons describe canonical lift/lower bindings (section 8).
	Canons []Canon

	// CoreFuncSpace is the component's full core func index space, in
	// declaration order across the (possibly interleaved) alias and canon
	// sections -- see corefuncspace.go. Empty for a Component not produced by
	// Decode (e.g. a hand-built binary.Component in a test), matching
	// TypeSpace's convention; callers needing the core func index space fall
	// back to treating Aliases/Canons as already correctly ordered in that
	// case.
	CoreFuncSpace []CoreFuncSpaceEntry

	// Start is the optional start section that specifies startup behavior (section 9).
	Start *Start

	// RawSections tracks sections we parse the header for but skip the body.
	// Used for sections we don't fully decode yet (e.g., core-type, component decls).
	RawSections []RawSection

	// Bytes is the complete binary this component was decoded from (the whole
	// buffer for a top-level component; the section-4 sub-slice for a nested
	// one). CoreModule.Offset/Size index into it, so recursively instantiating
	// a NestedComponents entry needs its own Bytes, not the parent's. The
	// decoded names are views of it, so it is read-only.
	Bytes []byte

	// Decoded is set true by Decode. It distinguishes a component that went
	// through the binary decoder (whose CoreFuncSpace/ComponentFuncSpace/
	// TypeSpace are authoritative -- an empty CoreFuncSpace genuinely means no
	// core-func-producing aliases/canons) from a hand-built Component value
	// (the common shape in tests, which never populates those index spaces).
	// The graph engine uses it to tell "legitimately no core funcs" from "index
	// spaces were never built"; see graph.go.
	Decoded bool
	// contains filtered or unexported fields
}

Component represents a parsed WebAssembly Component Model container.

func Decode

func Decode(r io.Reader) (*Component, error)

Decode parses a WebAssembly Component Model container from a reader. It validates the preamble, iterates outer component sections, and decodes type, import, and export sections into Go structs. Other sections are recorded but not fully decoded.

The decoded component's names are views of the buffer read (see readLabel), which it keeps as Component.Bytes: nothing may write to it.

func DecodeBytes added in v0.6.0

func DecodeBytes(b []byte) (*Component, error)

DecodeBytes is Decode of b. It copies b, once and to size, where io.ReadAll would grow a buffer to it: the copy is the decoder's own, which the names it decodes are views of, so b stays the caller's to change.

func (*Component) CoreModuleSpaceLen added in v0.3.0

func (c *Component) CoreModuleSpaceLen() int

CoreModuleSpaceLen is the number of indices in the core module index space, applying ResolveCoreModule's hand-built fallback (a Component that never went through Decode has no space, and its CoreModules IS its space).

func (*Component) Dump

func (c *Component) Dump(w io.Writer) error

Dump writes a human-readable summary of the component to w. It prints the type section, import/export graph, and instantiation graph.

func (*Component) ResolveComponentInstance

func (c *Component) ResolveComponentInstance(idx uint32) (int, bool)

ResolveComponentInstance resolves a component instance index to the index in Component.Instances of the instance DEFINITION it ultimately names, following export aliases (an `(export "x" (instance N))` both re-exports instance N and introduces a new instance index aliasing it).

ok is false when the index is out of range, names an imported instance, or names an alias this decoder does not resolve structurally (an outer alias, or an alias of another instance's instance-typed export). Callers that need to distinguish those cases should inspect ComponentInstanceSpace directly.

It returns (0, false) for a component that was not produced by Decode: a hand-built Component has no instance index space at all, and the caller is expected to fall back to its own arithmetic (see instance.go's componentInstanceDef).

func (*Component) ResolveCoreModule added in v0.3.0

func (c *Component) ResolveCoreModule(idx uint32) (owner *Component, moduleIdx uint32, err error)

ResolveCoreModule resolves an index in this component's core module index space to the component that actually EMBEDS the module and that component's index into its own CoreModules. The owner is not always c: an `alias outer` names a module embedded by an enclosing component, whose bytes live in the enclosing component's own Bytes (CoreModule.Offset/Size index into it), so callers need the owner, not just an index.

For a Component that was not produced by Decode (CoreModuleSpace left empty -- the common shape for hand-built binary.Component values in tests), idx is resolved directly against CoreModules with c as the owner, matching the behavior this package had before the space existed. Same convention as TypeSpace / CoreFuncSpace.

func (*Component) ResolveType

func (c *Component) ResolveType(idx uint32) (TypeDesc, error)

ResolveType resolves a component type index -- which may name a type-section deftype directly, or (transitively) a type-sort alias -- to its underlying TypeDesc, walking the component's full TypeSpace rather than indexing Types directly (which only covers type-section entries and misresolves the moment any alias or type import precedes a deftype).

It follows alias chains where this decoder has enough structure to do so: an "export" alias (TargetKind 0x00) naming a type-sort entry inline-exported by one of this component's own instances (Instances, section 5, Kind 0x01), and an "outer" alias (TargetKind 0x02) -- both the self-referential form (OuterCount 0, another index in this same TypeSpace) and a genuine de Bruijn reference into an ENCLOSING component's type index space, which walks Component.Outer OuterCount times. Anything else this decoder cannot follow structurally -- most notably a type exported from an *imported* instance (the common real-guest shape, e.g. `alias export $streams "output-stream" (type $ot)`; this package does not decode nested type declarations inside an imported instance type) -- fails loud with an error naming the index and the reason, rather than returning a zero value or panicking. That is the correct outcome for such an index: as documented on OwnDesc/BorrowDesc, own/borrow handle types only ever use their ResourceType index as an opaque tag (never dereferenced through a resolver), so a real guest built this way still instantiates and runs -- see internal/component/instance's package doc.

For a Component that was not produced by Decode (TypeSpace left empty -- the common shape for hand-built binary.Component values in tests), idx is resolved directly against Types instead, matching this method's behavior before TypeSpace existed.

func (*Component) ResourceDefIndex

func (c *Component) ResourceDefIndex(idx uint32) uint32

ResourceDefIndex maps a resource type index to the canonical index where the resource is DEFINED (or the root import it names), following the same TypeSpace links ResolveType does: export-introduces-alias, self "outer" type alias, and an `eq`-bounded type import. A resource is commonly named by several indices in one component -- the deftype that defines it AND the export alias created when it is exported -- while canon resource.new/drop/rep use the deftype and own<R>/borrow<R> in a lifted signature use the export alias. Reducing every alias of one resource to this single index gives a stable per-component identity. Returns idx unchanged for anything it cannot resolve further (a plain import, an opaque alias, or a hand-built Component with no TypeSpace) -- which is the right stable tag for those.

type ComponentDesc

type ComponentDesc struct {
	// Types and Outer are its own type index space, as InstanceDesc's are:
	// a type-sort import adds a slot as a type-sort export does there.
	Types []TypeDesc
	Outer map[uint32]OuterAlias

	// Decls are its declarations, in order; see InstanceDesc.Decls.
	Decls []TypeDecl
}

ComponentDesc represents a component type: what a component import, or a component export's type ascription, declares the component to be.

func (ComponentDesc) Kind

func (ComponentDesc) Kind() string

type ComponentFuncSpaceEntry

type ComponentFuncSpaceEntry struct {
	Kind   ComponentFuncSpaceEntryKind
	Import uint32 // index into Component.Imports (Kind == ComponentFuncFromImport)
	Alias  uint32 // index into Component.Aliases  (Kind == ComponentFuncFromAlias)
	Canon  uint32 // index into Component.Canons   (Kind == ComponentFuncFromCanonLift)
	Export uint32 // index into Component.Exports  (Kind == ComponentFuncFromExport)
}

ComponentFuncSpaceEntry is one entry in the component's func index space. Exactly one of Import/Alias/Canon/Export is meaningful, selected by Kind.

type ComponentFuncSpaceEntryKind

type ComponentFuncSpaceEntryKind byte

ComponentFuncSpaceEntryKind distinguishes what produced a component func index-space entry.

const (
	// ComponentFuncFromImport: a func import (section 10, sort func).
	ComponentFuncFromImport ComponentFuncSpaceEntryKind = iota
	// ComponentFuncFromAlias: a func alias (section 6, Sort == 0x01).
	ComponentFuncFromAlias
	// ComponentFuncFromCanonLift: a canon lift (section 8, Kind == 0x00).
	ComponentFuncFromCanonLift
	// ComponentFuncFromExport: a func export (section 11, sort func) -- an
	// alias of the exported func into the next func index.
	ComponentFuncFromExport
)

type ComponentInstanceSpaceEntry

type ComponentInstanceSpaceEntry struct {
	Kind     ComponentInstanceSpaceEntryKind
	Import   uint32 // index into Component.Imports   (Kind == ComponentInstanceFromImport)
	Instance uint32 // index into Component.Instances (Kind == ComponentInstanceFromDefinition)
	Alias    uint32 // index into Component.Aliases   (Kind == ComponentInstanceFromAlias)
	Export   uint32 // index into Component.Exports   (Kind == ComponentInstanceFromExport)
}

ComponentInstanceSpaceEntry is one entry in the component's instance index space. Exactly one of Import/Instance/Alias/Export is meaningful, selected by Kind.

type ComponentInstanceSpaceEntryKind

type ComponentInstanceSpaceEntryKind byte

ComponentInstanceSpaceEntryKind distinguishes what produced a component instance index-space entry.

const (
	// ComponentInstanceFromImport: an instance import (section 10, sort instance).
	ComponentInstanceFromImport ComponentInstanceSpaceEntryKind = iota
	// ComponentInstanceFromDefinition: an instance definition (section 5).
	ComponentInstanceFromDefinition
	// ComponentInstanceFromAlias: an instance alias (section 6, Sort == 0x05).
	ComponentInstanceFromAlias
	// ComponentInstanceFromExport: an instance export (section 11, sort
	// instance) -- an alias of the exported instance into the next instance
	// index.
	ComponentInstanceFromExport
)

type ComponentSpaceEntry added in v0.3.0

type ComponentSpaceEntry struct {
	Kind      ComponentSpaceEntryKind
	Import    uint32 // index into Component.Imports          (ComponentFromImport)
	Component uint32 // index into Component.NestedComponents (ComponentFromDefinition)
	Alias     uint32 // index into Component.Aliases          (ComponentFromAlias)
	Export    uint32 // index into Component.Exports          (ComponentFromExport)
}

ComponentSpaceEntry is one entry in the component index space. Exactly one of Import/Component/Alias/Export is meaningful, selected by Kind.

type ComponentSpaceEntryKind added in v0.3.0

type ComponentSpaceEntryKind byte

This file implements the COMPONENT index space -- the space an instance definition's `(instantiate <componentidx> ...)` names, and the last of the component-level index spaces this package models (see typespace.go, corefuncspace.go, componentfuncspace.go, componentinstancespace.go, coremodulespace.go).

Per the component-model binary format it is populated, in declaration order across sections, by every definition that yields a component:

  • a component import (section 10, externdesc sort component 0x04)
  • a nested component (section 4)
  • a component alias (section 6, Sort == 0x04) -- `alias outer`
  • a component export (section 11, externdesc sort component 0x04), since "all exports (of all sorts) introduce a new index that aliases the exported definition"

Equating the space with NestedComponents (section 4) alone is what made types.11.wast fail to instantiate: its nested `$c` defines NO nested component of its own, imports one (`(import "x" (component ...))`) and then does `(instantiate 0)` -- index 0 being that import. A component-sort import is a component DEFINITION (code) the embedder supplies, not an instance: the importing component instantiates it itself, with its own args, at its own instance section. internal/component/instance resolves an index against what the instantiation was given (its scope).

const (
	// ComponentFromImport: a component import (section 10, sort component 0x04).
	ComponentFromImport ComponentSpaceEntryKind = iota
	// ComponentFromDefinition: a nested component (section 4).
	ComponentFromDefinition
	// ComponentFromAlias: a component alias (section 6, Sort == 0x04).
	ComponentFromAlias
	// ComponentFromExport: a component export (section 11, sort component
	// 0x04) -- an alias of the exported component into the next component index.
	ComponentFromExport
)

type CoreExternType added in v0.6.0

type CoreExternType struct {
	// Kind is the core extern sort: 0x00 func, 0x01 table, 0x02 memory,
	// 0x03 global, 0x04 tag.
	Kind byte

	// TypeIndex is a func's or tag's type, an index into the enclosing
	// module type's core type index space.
	TypeIndex uint32

	// Bytes is the encoding after the kind byte: what a core import
	// section has for this desc.
	Bytes []byte
}

CoreExternType is a core:externtype, as a core import section encodes it.

type CoreFuncSpaceEntry

type CoreFuncSpaceEntry struct {
	Kind CoreFuncSpaceEntryKind

	// Alias is the index into Component.Aliases, valid when
	// Kind == CoreFuncFromAlias.
	Alias uint32

	// Canon is the index into Component.Canons, valid when
	// Kind == CoreFuncFromCanon.
	Canon uint32
}

CoreFuncSpaceEntry is one entry in the component's core func index space. Exactly one of Alias, Canon is meaningful, selected by Kind.

type CoreFuncSpaceEntryKind

type CoreFuncSpaceEntryKind byte

CoreFuncSpaceEntryKind distinguishes what produced a core func index-space entry.

const (
	// CoreFuncFromAlias marks an entry produced by a core-level func alias
	// (section 6, Sort == 0x00, CoreSort == 0x00).
	CoreFuncFromAlias CoreFuncSpaceEntryKind = iota
	// CoreFuncFromCanon marks an entry produced by a canon that yields a new
	// core func: every Canon.Kind except lift (0x00) -- see decodeComponent's
	// canon-section case.
	CoreFuncFromCanon
)

type CoreInlineExport

type CoreInlineExport struct {
	Name        string
	Sort        byte // core:sort: 0x00 func, 0x01 table, 0x02 memory, 0x03 global, 0x04 tag, 0x10 type, 0x11 module, 0x12 instance
	CoreSortIdx uint32
}

CoreInlineExport represents an inlined export in a core instance.

type CoreInstance

type CoreInstance struct {
	Kind      byte   // 0x00 = instantiate, 0x01 = inline exports
	ModuleIdx uint32 // used if Kind == 0x00
	Args      []CoreInstantiateArg
	Exports   []CoreInlineExport
}

CoreInstance represents a core module instantiation (section 2).

type CoreInstantiateArg

type CoreInstantiateArg struct {
	Name        string
	InstanceIdx uint32
}

CoreInstantiateArg represents an argument to instantiate a core module.

type CoreModule

type CoreModule struct {
	Offset int // byte offset in the component binary
	Size   int // byte length of the core module
}

CoreModule represents an embedded core wasm module (section 1). The binary is stored as an offset and size; it is not parsed here, as wazy's core decoder handles that separately.

type CoreModuleDecl added in v0.6.0

type CoreModuleDecl struct {
	Kind CoreModuleDeclKind

	// Module and Name are an import's module and field names, and Name an
	// export's name.
	Module, Name string

	// Extern is the declared type of an import or export.
	Extern CoreExternType

	// Rec is a type declaration's core:rectype, and RecCount the number of
	// type indices it introduces.
	Rec      []byte
	RecCount uint32

	// AliasCount and AliasIndex are an outer type alias's target: the
	// AliasIndex-th core type of the AliasCount-th enclosing component (0:
	// the component holding the module type), never a module type.
	AliasCount, AliasIndex uint32
}

CoreModuleDecl is one declaration of a core module type.

type CoreModuleDeclKind added in v0.6.0

type CoreModuleDeclKind byte

CoreModuleDeclKind says what one declaration of a core module type is. Its values are the declaration tags of the binary format.

const (
	// CoreModuleDeclImport is an import: Module, Name and Extern.
	CoreModuleDeclImport CoreModuleDeclKind = 0x00
	// CoreModuleDeclType is a type definition: Rec and RecCount.
	CoreModuleDeclType CoreModuleDeclKind = 0x01
	// CoreModuleDeclAlias is an outer alias of a core type: AliasCount and
	// AliasIndex.
	CoreModuleDeclAlias CoreModuleDeclKind = 0x02
	// CoreModuleDeclExport is an export: Name and Extern.
	CoreModuleDeclExport CoreModuleDeclKind = 0x03
)

type CoreModuleSpaceEntry added in v0.3.0

type CoreModuleSpaceEntry struct {
	Kind   CoreModuleSpaceEntryKind
	Module uint32 // index into Component.CoreModules (Kind == CoreModuleFromDefinition)
	Alias  uint32 // index into Component.Aliases     (Kind == CoreModuleFromAlias)
	Import uint32 // index into Component.Imports     (Kind == CoreModuleFromImport)
	Export uint32 // index into Component.Exports     (Kind == CoreModuleFromExport)
}

CoreModuleSpaceEntry is one entry in the component's core module index space. Exactly one of Module/Alias/Import/Export is meaningful, selected by Kind.

type CoreModuleSpaceEntryKind added in v0.3.0

type CoreModuleSpaceEntryKind byte

CoreModuleSpaceEntryKind distinguishes what produced a core module index space entry.

const (
	// CoreModuleFromDefinition: an embedded core module (section 1).
	CoreModuleFromDefinition CoreModuleSpaceEntryKind = iota
	// CoreModuleFromAlias: a core-module alias (section 6, Sort == 0x00 core,
	// CoreSort == 0x11 module).
	CoreModuleFromAlias
	// CoreModuleFromImport: a core module import (section 10, sort 0x00).
	CoreModuleFromImport
	// CoreModuleFromExport: a core module export (section 11, sort 0x00).
	CoreModuleFromExport
)

type CoreModuleType added in v0.6.0

type CoreModuleType struct {
	Decls []CoreModuleDecl
}

CoreModuleType is a core module type: its declarations, in order. Each type declaration and type alias opens the next index of the module type's own core type index space, which starts empty; a func or tag extern type names an index there.

type CoreTypeDef added in v0.6.0

type CoreTypeDef struct {
	// Module is the module type, nil for a rectype.
	Module *CoreModuleType

	// Rec is a rectype's encoding as a core type section has it: a
	// component's top-level `0x00 0x50` non-final sub is re-encoded as the
	// plain `0x50` a core decoder expects.
	Rec []byte

	// Count is the number of core type indices the definition introduces:
	// the size of its recursion group, and 1 for a module type.
	Count uint32
}

CoreTypeDef is one core:type definition: a core module type, or a core:rectype -- one or more func, struct or array types, a recursion group when more than one.

type CoreTypeSpaceEntry added in v0.6.0

type CoreTypeSpaceEntry struct {
	Kind CoreTypeSpaceEntryKind
	// Def and Member name a definition's Member-th type (the position in
	// its recursion group).
	Def, Member uint32
	// Alias is the alias's index in Component.Aliases.
	Alias uint32
}

CoreTypeSpaceEntry is one index of a component's core type index space.

type CoreTypeSpaceEntryKind added in v0.6.0

type CoreTypeSpaceEntryKind byte

CoreTypeSpaceEntryKind says what produced an index of a component's core type index space.

const (
	// CoreTypeFromDefinition is a core type section definition: one member
	// of CoreTypes[Def].
	CoreTypeFromDefinition CoreTypeSpaceEntryKind = iota
	// CoreTypeFromAlias is an outer alias of a core type: Aliases[Alias].
	CoreTypeFromAlias
)

type EnumDesc

type EnumDesc struct {
	Cases []string
}

EnumDesc represents an enum type.

func (EnumDesc) Kind

func (EnumDesc) Kind() string

type Export

type Export struct {
	// Name is the export name.
	Name string

	// ExternType distinguishes the export kind.
	ExternType byte

	// ExternIndex is the index into the appropriate namespace.
	ExternIndex uint32

	// Ascribed is the export's optional type ascription -- `(export "f"
	// (func $f) (func (type $t)))` -- or nil when it carries none. What a
	// component exports has the ascribed type, which the exported item's own
	// type must be a subtype of. wit-component ascribes every export of the
	// shim components it emits.
	Ascribed *ExternDesc
}

Export represents a component export binding.

type ExternDesc added in v0.6.0

type ExternDesc struct {
	Sort  byte
	Index uint32
	Eq    bool
}

ExternDesc is one externdesc of the binary format: what an import, an export's type ascription, or an import/export declaration inside a component or instance type says the item is.

Sort is the sort byte: 0x00 core module, 0x01 func, 0x02 value, 0x03 type, 0x04 component, 0x05 instance. For every sort but type, Index is the type index of the item's declared type (a core module type for 0x00, which is a CORE type index). For a type, Eq reports the bound: true for `(eq Index)`, false for `(sub resource)`, which names no index and introduces a fresh abstract resource type.

type FixedListDesc added in v0.6.0

type FixedListDesc struct {
	Element TypeRef
	Length  uint32
}

FixedListDesc represents a fixed-length list, list<T, N> (🔧 in the Component Model spec): exactly Length elements, N > 0. Its Canonical ABI is a homogeneous tuple's: the elements are laid out back to back at the element's alignment, with no pointer or length, and flatten to the element's flattening Length times. Its Value has a dynamic list's shape -- the Go slice of a fixed-width primitive element, else a []Value -- of exactly Length elements.

func (FixedListDesc) Kind added in v0.6.0

func (FixedListDesc) Kind() string

type FlagsDesc

type FlagsDesc struct {
	Names []string
}

FlagsDesc represents a flags type (set of named booleans).

func (FlagsDesc) Kind

func (FlagsDesc) Kind() string

type FuncDesc

type FuncDesc struct {
	Params  []FuncParam
	Results FuncResults
	// Async is true for an `async func` component-func type (deftype tag 0x43,
	// vs the synchronous 0x40). A canon lift/lower's own async CanonOpt (0x06)
	// is separate; the Canonical ABI requires the two to agree, but that
	// cross-check is a validation concern, not decode.
	Async bool
}

FuncDesc represents a function type.

func (FuncDesc) Kind

func (FuncDesc) Kind() string

type FuncParam

type FuncParam struct {
	Name string
	Type TypeRef
}

type FuncResult

type FuncResult struct {
	Name string
	Type TypeRef
}

type FuncResults

type FuncResults struct {
	Unnamed *TypeRef     // non-nil if tag was 0x00
	Named   []FuncResult // non-empty if tag was 0x01
}

FuncResults captures the two forms of result lists: - Unnamed: a single unnamed result (tag 0x00) - Named: zero or more named results (tag 0x01)

type FutureDesc

type FutureDesc struct {
	Element *TypeRef // nil if the future carries no element type
}

FutureDesc represents a `future<T>` (or bare `future` with no element) async-ABI type. Element is nil for the bare form. Same opaque-handle treatment as StreamDesc.

func (FutureDesc) Kind

func (FutureDesc) Kind() string

type Import

type Import struct {
	// Name is the import name (e.g., "wasi:io/streams#input-stream").
	Name string

	// ExternType distinguishes the import kind (e.g., component, instance, func, value, type, module).
	ExternType byte

	// ExternIndex is the item's declared type index: the functype of a func
	// (0x01), the instancetype of an instance (0x05), the componenttype of a
	// component (0x04), the core module type of a core module (0x00, a CORE
	// type index). Unused for a type import (0x03), whose bound is below.
	ExternIndex uint32

	// TypeEqIndex, valid when ExternType == 0x03 (type) and TypeEqBound is
	// true, is the component type index this type import is declared equal to
	// (an `import "x" (type (eq N))` bound, what wit-component/cargo-component
	// emit for a world's exported types). Such an import resolves through to
	// type N -- see typespace.go's resolveTypeDepth -- rather than being
	// opaque. A `sub` (resource) type bound leaves TypeEqBound false.
	TypeEqIndex uint32
	TypeEqBound bool
}

Import represents a component import binding.

type InlineExport

type InlineExport struct {
	Name    string
	Sort    byte
	SortIdx uint32
}

InlineExport represents an inlined export in an instance.

type Instance

type Instance struct {
	Kind         byte   // 0x00 = instantiate, 0x01 = inline exports
	ComponentIdx uint32 // used if Kind == 0x00
	// CoreInstancesBefore is how many core instances the binary defines
	// before this one. Definitions are instantiated in the order they
	// appear, so those are instantiated first.
	CoreInstancesBefore uint32
	Args                []InstantiateArg
	Exports             []InlineExport
}

Instance represents a component instance (section 5).

type InstanceDesc

type InstanceDesc struct {
	// Exports maps each type-sort export name to its type. A name absent
	// from this map was either not exported at all, or was exported but this
	// decoder could not resolve it structurally (a `sub`-bound/abstract
	// resource export, or a type-sort alias).
	Exports map[string]TypeRef

	// Types holds the deftypes declared locally within this instancetype's
	// own body (instancedecl tag 0x01), plus one nil placeholder per other
	// type-sort-index-producing instancedecl (a type-sort alias, or a
	// `sub`-bound export) this decoder cannot resolve structurally, in
	// declaration order -- see typeBody.read.
	Types []TypeDesc

	// Outer maps each nil slot of Types that aliases a type of an enclosing
	// type index space ("alias outer"), or is exported as one ("eq" of such
	// a slot), to what it aliases.
	Outer map[uint32]OuterAlias

	// Decls are its declarations, every one, in order: what a type check
	// computes the instance type from. Exports and Types are what the ABI
	// needs of them, kept apart so it does not walk them.
	Decls []TypeDecl
}

InstanceDesc represents an instance type (collection of exports).

An instancetype opens its own nested type-sort index space, the same way a nested component opens its own (see Component.Outer) -- so Types and the TypeIndex side of an Exports TypeRef both index into THIS InstanceDesc's own space, never into the enclosing component's TypeSpace. A TypeRef here with TypeIndex set is only ever resolvable through Types directly (see resolveAlias's case 0x00, which globalizes it into the enclosing Component's escape range before handing it to a caller) -- never through an ordinary Resolver.

func (InstanceDesc) Kind

func (InstanceDesc) Kind() string

type InstantiateArg

type InstantiateArg struct {
	Name    string
	Sort    byte
	SortIdx uint32
}

InstantiateArg represents an argument to instantiate a component.

type ListDesc

type ListDesc struct {
	Element TypeRef
}

ListDesc represents a list (unbounded array).

func (ListDesc) Kind

func (ListDesc) Kind() string

type MapDesc added in v0.4.0

type MapDesc struct {
	Key   TypeRef
	Value TypeRef
}

MapDesc represents a map<K,V>: an unordered association of keys to values. Per the Canonical ABI's despecialize() step, a map has no wire representation of its own -- it is byte-for-byte identical to list<tuple<K,V>> (same alignment, size, flattening, and lift/lower), so every ABI function that handles MapDesc does so by delegating to its TupleDesc/ListDesc counterpart with a synthetic `tuple<Key,Value>` element rather than repeating the layout. A map's Value is therefore the same shape as list<tuple<K,V>>: a []Value of two-element []Value pairs ([]Value{key, value}), in whatever order the guest produced them -- a map carries no ordering guarantee.

Key is restricted by the spec's own `keytype` grammar (design/mvp/ Explainer.md) to bool, an integer, char, or string -- a conservative subset of `valtype` picked to simplify bindings generation, deliberately excluding f32/f64 (float equality/NaN) and every composite, handle, and async type. See IsValidMapKeyPrimitive.

func (MapDesc) Kind added in v0.4.0

func (MapDesc) Kind() string

type OptionDesc

type OptionDesc struct {
	Element TypeRef
}

OptionDesc represents an optional value.

func (OptionDesc) Kind

func (OptionDesc) Kind() string

type OuterAlias added in v0.6.0

type OuterAlias struct {
	Count, Index uint32
}

OuterAlias is "alias outer Count Index": type Index of the type index space Count levels out -- 1 being the component (or component type) the declaring type is defined in, 0 the declaring type's own.

type OwnDesc

type OwnDesc struct {
	ResourceType uint32
}

OwnDesc represents owned handle to a resource.

func (OwnDesc) Kind

func (OwnDesc) Kind() string

type PrimitiveDesc

type PrimitiveDesc struct {
	Prim string // "bool", "s8", "u8", "s16", "u16", "s32", "u32", "s64", "u64", "f32", "f64", "char", "string"
}

PrimitiveDesc represents a primitive value type (bool, s32, u64, string, etc.).

func (PrimitiveDesc) Kind

func (p PrimitiveDesc) Kind() string

type RawSection

type RawSection struct {
	ID   byte
	Size uint32
}

RawSection represents a section header we parsed but did not fully decode.

type RecordDesc

type RecordDesc struct {
	Fields []RecordField
}

RecordDesc represents a record type (struct-like) with named fields.

func (RecordDesc) Kind

func (RecordDesc) Kind() string

type RecordField

type RecordField struct {
	Name string
	Type TypeRef
}

type ResourceDesc

type ResourceDesc struct {
	Rep  TypeRef // representation type (usually a primitive)
	Dtor *uint32 // optional destructor function index
}

ResourceDesc represents a resource type.

func (ResourceDesc) Kind

func (ResourceDesc) Kind() string

type ResultDesc

type ResultDesc struct {
	Ok  *TypeRef // optional
	Err *TypeRef // optional
}

ResultDesc represents a result type (success or error).

func (ResultDesc) Kind

func (ResultDesc) Kind() string

type Start

type Start struct {
	FuncIdx     uint32
	Args        []uint32
	ResultCount uint32
}

Start represents the start section (section 9).

type StreamDesc

type StreamDesc struct {
	Element *TypeRef // nil if the stream carries no element type
}

StreamDesc represents a `stream<T>` (or bare `stream` with no element) async-ABI type. Element is nil for the bare form. Phase 0 treats a stream value as an opaque i32 handle throughout the ABI layer (like own/borrow); Element is recorded for completeness but not otherwise consumed until stream/future runtime support lands.

func (StreamDesc) Kind

func (StreamDesc) Kind() string

type TupleDesc

type TupleDesc struct {
	Elements []TypeRef
}

TupleDesc represents a tuple (unnamed record).

func (TupleDesc) Kind

func (TupleDesc) Kind() string

type Type

type Type struct {
	// Index is the type index in the type section.
	Index uint32

	// Kind is a human-readable string representation ("func", "record", "variant", etc.).
	// For now, we stub most kinds.
	Kind string

	// Descriptor is the full semantic representation of the type (enum, record, func, etc).
	// It is set during parsing and contains the complete structure for ABI and other uses.
	Descriptor TypeDesc

	// Raw holds the raw bytes of this type definition (for round-trip verification).
	Raw []byte
}

Type represents a value type in the component type section. For now, we store the raw index and a textual kind for easier debugging.

type TypeDecl added in v0.6.0

type TypeDecl struct {
	Kind TypeDeclKind

	// Type is the definition of a TypeDeclType.
	Type TypeDesc

	// Alias is the alias of a TypeDeclAlias.
	Alias AliasDef

	// CoreType is the definition of a TypeDeclCoreType.
	CoreType *CoreTypeDef

	// Name and Desc are the name and the declared type of a TypeDeclImport
	// or TypeDeclExport.
	Name string
	Desc ExternDesc
}

TypeDecl is one declaration of a component or instance type, in the order the type declares them. A type opens index spaces of its own (see InstanceDesc), so every index a declaration carries -- in Type, in Alias, in Desc -- names an item of the enclosing type's own spaces, unless an outer alias put it there.

type TypeDeclKind added in v0.6.0

type TypeDeclKind byte

TypeDeclKind says what one declaration of a component or instance type is. Its values are the declaration tags of the binary format.

const (
	// TypeDeclCoreType is a core type definition (core:type): TypeDecl.CoreType.
	// It opens the next index of the type's own core type index space, not of
	// a component-level one.
	TypeDeclCoreType TypeDeclKind = 0x00
	// TypeDeclType is a type definition: TypeDecl.Type.
	TypeDeclType TypeDeclKind = 0x01
	// TypeDeclAlias is an alias: TypeDecl.Alias.
	TypeDeclAlias TypeDeclKind = 0x02
	// TypeDeclImport is an import, which only a component type has:
	// TypeDecl.Name and TypeDecl.Desc.
	TypeDeclImport TypeDeclKind = 0x03
	// TypeDeclExport is an export: TypeDecl.Name and TypeDecl.Desc.
	TypeDeclExport TypeDeclKind = 0x04
)

type TypeDesc

type TypeDesc interface {

	// Kind returns the human-readable kind string for this descriptor
	// (e.g. "func", "record", "u32"). This is the single source of truth
	// for Type.Kind; there is no separate walk that derives it.
	Kind() string
	// contains filtered or unexported methods
}

TypeDesc represents a full component type descriptor, capturing the complete structure of a deftype. It is built by walking the component binary, mirroring the exact byte-consumption of the existing walker but also recording the semantic structure for use by the Canonical ABI and other tools.

type TypeRef

type TypeRef struct {
	// Exactly one of these must be set.
	Primitive string // e.g. "bool", "u32", "string", etc.; empty means use TypeIndex
	TypeIndex *uint32
}

TypeRef is either a reference to a primitive type (encoded as a byte name) or an index into the type table.

type TypeSpaceEntry

type TypeSpaceEntry struct {
	Kind TypeSpaceEntryKind

	// Def is the index into Types, valid when Kind == TypeSpaceDef.
	Def uint32

	// Alias is the index into Aliases, valid when Kind == TypeSpaceAlias.
	Alias uint32

	// Import is the index into Imports, valid when Kind == TypeSpaceImport.
	Import uint32

	// Export is the index into Exports, valid when Kind == TypeSpaceExport.
	Export uint32
}

TypeSpaceEntry is one entry in the component's full type index space. Exactly one of Def, Alias, Import is meaningful, selected by Kind.

type TypeSpaceEntryKind

type TypeSpaceEntryKind byte

TypeSpaceEntryKind distinguishes what produced a component type-index-space entry.

const (
	// TypeSpaceDef marks an entry produced by a type-section (id 7) deftype.
	TypeSpaceDef TypeSpaceEntryKind = iota
	// TypeSpaceAlias marks an entry produced by a type-sort alias (id 6,
	// Sort == 0x03).
	TypeSpaceAlias
	// TypeSpaceImport marks an entry produced by an import whose externdesc
	// names a type (id 10, ExternType == 0x03).
	TypeSpaceImport
	// TypeSpaceExport marks an entry produced by an export whose sort is type
	// (id 11, ExternType == 0x03) -- "export introduces an alias" of the
	// exported type.
	TypeSpaceExport
)

type VariantCase

type VariantCase struct {
	Name string
	Type *TypeRef // optional (nil means no payload)
}

type VariantDesc

type VariantDesc struct {
	Cases []VariantCase
}

VariantDesc represents a discriminated union.

func (VariantDesc) Kind

func (VariantDesc) Kind() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL