Files
prometeu-runtime/docs/specs/runtime/02b-vm-function-values-and-closures.md
T
bquarkz a2275932a5
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
Keep PBX at v0 and simplify Jenkins quality gate
2026-10-14 14:35:44 +01:00

6.6 KiB

VM Function Values and Closures

Domain: VM closures and function values Function: normative

Didactic companion: Typed Callables and Frame-Owned Continuations.

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, Registry/PBX and host ABI.

Random core integration

Random references 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. 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 for independent fuel, debugger behavior and failure semantics. Frontend Init and Frame assembly is unchanged.