Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
119 lines
6.6 KiB
Markdown
119 lines
6.6 KiB
Markdown
# VM Function Values and Closures
|
|
|
|
Domain: VM closures and function values
|
|
Function: normative
|
|
|
|
Didactic companion: [Typed Callables and Frame-Owned Continuations](../../../discussion/lessons/DSC-0052-vm-closures-captures-and-dynamic-calls/LSN-0061-typed-callables-and-frame-owned-continuations.md).
|
|
|
|
## 1 Typed First-Class Functions
|
|
|
|
Registry Fn (tag 4) contains Signature: ordered logical parameter/result TypeIds.
|
|
Optional names are metadata. Identity is exactly these lists, excluding FunctionId,
|
|
captures and physical widths. Duplicate Fn keys reject without ID remapping or
|
|
variance. One Vec2 result and two Float results differ despite equal slot counts.
|
|
Structural expansion through Array elements and Fn parameters/results MUST be
|
|
finite; nominal Struct/Trait stop expansion. Forward references, recursive calls,
|
|
captured Fn values and runtime object cycles remain legal.
|
|
|
|
Fn occupies one Value slot, an 8-byte/8-aligned guest HeapRef in typed storage, and
|
|
defaults to Null. Invoking absence traps. Fn is allowed in parameters/results,
|
|
Struct/Array/Dynamic; REF_* retain their category rules and Fn does not implement
|
|
Trait implicitly. Syscalls are not first-class values.
|
|
|
|
## 2 Instances and Captures
|
|
|
|
Every value uses a heap Closure, including empty captures:
|
|
`Closure { fn_type_id, function_id, typed_capture_components[] }`.
|
|
Distinct creation has distinct identity; copying a reference preserves identity.
|
|
Equality compares handles, never code/environment. Target and capture bindings
|
|
are immutable; objects referenced by them may remain mutable.
|
|
|
|
Immutable bindings are captured by value. Shared mutable lexical bindings use
|
|
private typed Struct cells with ordinary field operations, common to creator and
|
|
closures. Another factory can allocate another cell. No Cell category or
|
|
SET_CAPTURE is introduced; language lowering belongs to each frontend.
|
|
|
|
PBX v0 MUST include exactly one captures section, kind 8: little-endian
|
|
`function_count:u32`, then per FunctionId `capture_count:u32` and ordered capture
|
|
TypeIds:u32. Outer count equals the function table; empty lists are explicit.
|
|
Offsets/widths/maps derive at load. Records, capacities and graph work use existing
|
|
budgets. Images lacking this section or using old closure encodings reject.
|
|
|
|
## 3 Calls and Environments
|
|
|
|
Opcodes are u16, immediates u32, all little-endian:
|
|
|
|
| Instruction | Immediates | Stack / attempted cost |
|
|
| --- | --- | --- |
|
|
| MAKE_CLOSURE 0x52 | FunctionId, FnTypeId | capture groups -> Fn; 8+C |
|
|
| CALL_CLOSURE 0x53 | expected FnTypeId | args..., Fn -> results... after RET; 6 |
|
|
| GET_CAPTURE 0x57 | capture index | append complete capture group; 2+W |
|
|
| CALL_TRAIT 0x58 | TraitTypeId, method index | args..., receiver, ImplementationId -> results...; 6 |
|
|
|
|
C is declared capture-slot sum; W is indexed capture width. Charge once per
|
|
attempt including traps. CALL/RET retain 5/4; zero budget executes nothing and
|
|
positive budget admits a whole instruction, which may overshoot.
|
|
|
|
CALL_CLOSURE validates expected Fn type and target signature. CallFrame retains
|
|
the Closure as environment root, without hidden arg0 in public parameters.
|
|
GET_LOCAL addresses public parameters/locals; GET_CAPTURE reads that frame's
|
|
indexed environment. Nested calls own separate environments. Nonempty-capture
|
|
bodies cannot be entered by direct CALL or host preparation without environment.
|
|
A bound-method Fn can use an explicit adapter capturing its receiver.
|
|
|
|
CALL_TRAIT validates the complete view and resolves FunctionId through the
|
|
immutable implementation table. Callee gets concrete receiver first, then explicit
|
|
method arguments; ImplementationId is not a parameter. Exact method signatures
|
|
and empty target captures are required. Absent/malformed/stale/incompatible views
|
|
fault. No lookup by name, implicit wrappers, variance or adaptations are added.
|
|
|
|
## 4 Verification, Faults and Resources
|
|
|
|
Expected FnTypeId supplies parameter/result groups even for unknown concrete
|
|
targets. Known mismatch rejects loading; Unknown retains full runtime checks.
|
|
Validate every instruction and metadata before image publication. Creation,
|
|
call and capture access validate whole groups and reserve capacity before consume
|
|
or publication. Refusal preserves operands/owners and publishes no partial object
|
|
or frame; provisional reservations refund and attempted cycles remain. No quota
|
|
rescue GC. Use existing distinct NullReference/InvalidHandle/Type/Resource traps.
|
|
Ordinary Fn calls can invoke syscalls, mutate and fault: no purity flag, fault
|
|
isolation, separate budget, guest unwind or rollback of earlier body effects.
|
|
SystemOS lifecycle invocations use the separate budget described below.
|
|
|
|
## 5 Context, GC and Host
|
|
|
|
VM owns one PC, operand/call stacks and globals directly. FRAME_SYNC retains
|
|
frames/locals/environments and resumes next PC in normal gameplay bodies. It is
|
|
forbidden during lifecycle hooks and their callees. Budget exhaustion
|
|
retains the same logical frame. Last-root RET completes entry, rooting results
|
|
before threshold GC. Recurring host entry remains FunctionId 0 with init once.
|
|
|
|
Threshold GC opportunities are FRAME_SYNC and successful last-root RET. Roots
|
|
include globals, live stack values, Closures retained by every active CallFrame
|
|
and legally retained native/host roots. Trace whole capture groups and shared
|
|
cells; unreachable cycles collect. Results remain roots until consumed/replaced,
|
|
reset/unload. No GC at ordinary callee RET or allocation/quota rescue.
|
|
HeapRef copies/inspection snapshots establish no guest roots or cross-session
|
|
imports. Ordinary guest callbacks are Fn calls in the main execution context.
|
|
Optional SystemOS lifecycle entry uses Registry roles and the controlled boundary
|
|
described below; it does not introduce arbitrary native reentry.
|
|
|
|
See [memory](03-memory-stack-heap-and-allocation.md),
|
|
[Registry/PBX](02c-program-registry-and-pbx-v0.md) and
|
|
[host ABI](16-host-abi-and-syscalls.md).
|
|
|
|
## Random core integration
|
|
|
|
[Random references](02e-vm-owned-random-core.md) are valid capture, parameter and result groups. Existing roots retain the generator; copying captures aliases its state.
|
|
|
|
## System-owned lifecycle entry
|
|
|
|
Optional zero-argument, zero-result, capture-free lifecycle targets are bound by
|
|
[Registry roles](02c-program-registry-and-pbx-v0.md#optional-lifecycle-roles).
|
|
They are ordinary functions called through a controlled SystemOS boundary, not
|
|
closure values or replacement boot entries. The boundary retains the existing
|
|
stacks and roots, appends its frame, and returns to SystemOS immediately on outer
|
|
completion. See [lifecycle execution](09a-coroutines-and-cooperative-scheduling.md#controlled-lifecycle-calls)
|
|
for independent fuel, debugger behavior and failure semantics. Frontend Init and
|
|
Frame assembly is unchanged.
|