Files
prometeu-studio/discussion/lessons/DSC-0080-pbs-closures-and-indirect-calls/LSN-0084-pbs-function-values-and-explicit-captures.md
T
bquarkz 240216170c feat(pbs): add parametric arrays and concrete generic contracts
Support explicit contract type parameters, canonical nominal applications,
recursive substitution, concrete implementations and instantiated editor views.
Complete parametric Array syntax and contextual construction integration.

Preserve type origins across imports and reexports, fix trait argument stack
order, and relocate global slots before lifecycle assembly. Publish specs,
installed examples and consolidated discussion lessons.

Validate frontend, common pipeline, architecture, LSP and installed knowledge
gates, plus the full production VM conformance corpus with 14 generic fixtures.
2026-10-20 11:30:00 +01:00

5.4 KiB

id, ticket, title, created, tags
id ticket title created tags
LSN-0084 pbs-closures-and-indirect-calls PBS Function Values and Explicit Captures 2026-10-17
compiler
pbs
runtime-integration

Context

Owner: compiler/pbs. PBS needed functions usable as ordinary values for game logic and agent-authored programs. Its nominal callback declarations and bind model did not provide the chosen structural function surface. Runtime support for closures already existed; source typing, lowering, tooling and executable integration still had to be delivered together.

The accepted DEC-0068 was implemented through PLN-0147. Both are completed workflow artifacts; this lesson preserves their durable rationale and outcome.

Consolidated decision

Fn(int) -> int identifies the ordered parameter/result types. Named functions and lambdas with that signature can be assigned, passed, returned and stored. Calls use ordinary parentheses. Overloaded function identifiers need an expected signature that selects exactly one target.

Lambdas use fn [captures](name: Type) -> Return { ... }. Captures, parameter annotations, result annotation and block are explicit, including empty []. This makes dependencies visible to both programmers and code-generating agents. The cost is deliberate verbosity; implicit capture and expression-body shorthand are not alternative forms.

Captures snapshot values at creation. Captured bindings cannot be reassigned, even when their source bindings were mutable. Capturing an object reference preserves object identity and permitted field mutation. Shared state therefore uses explicit objects instead of hidden shared lexical cells.

declare struct Counter(pub mut value: int);
fn createCounter() -> Fn() -> int {
    let counter = new Counter(0);
    return fn [counter]() -> int {
        counter.value += 1;
        return counter.value;
    };
}

Each factory call creates independent state. Two closures capturing the same counter intentionally share state. Arrays use array<(Fn() -> int)> and existing optional-read rules. Methods become function values through explicit lambdas capturing their receiver. The old declare callback, callback barrel exports and bind(context, function) are rejected.

Objects and frames

A closure is a managed object with the same reachability lifecycle as other objects. Returning from its creator does not destroy it. Globals, arrays, fields and other captures can retain it across frames. GC traces its environment and collects unreachable closures and objects.

An invocation completes within its frame. Keeping a closure alive across frames does not suspend an invocation. PBS has no coroutine or sync syntax. The frontend already publishes FRAME_ROOT; the existing lifecycle assembler supplies the guarded wrapper and its return. Reuse that integration rather than introducing a new loop or frame-ending operation for closures.

Implementation

The AST and type parser represent structural Fn inputs/results and explicit lambda captures. Semantic analysis creates an isolated capture/parameter scope, checks returns and signatures, and rejects uncaptured outer locals. Editor traversal uses lambda scopes so references, rename and completion preserve binding identity.

Lowering registers deterministic generated functions and ordered typed capture metadata. MAKE_CLOSURE creates values, GET_CAPTURE reads environments, and CALL_CLOSURE invokes the expected signature. Named functions use empty capture lists. Captures do not become public parameters. Existing common IR/PBX registry and runtime contracts supply the execution machinery without production changes to frame assembly or runtime authority.

Complete logical groups must survive capture and return: a tuple or contract receiver cannot be treated as one slot simply because its containing closure occupies one slot. Imported functions retain provider callable identity.

Validation and pitfalls

The production VM executes nine closure programs returning 42 and six allocation quota/ownership cases. A separate fixture uses the real lifecycle wrapper for three frames: a stored closure and captured object survive the first collection, execute in the next frame, then become collectible after their root is cleared. Each frame discards another 1,200 closures. This proves both retention and release.

The final Gradle gates execute 513 tests without failures; 13 existing disabled tests and two existing runtime JSON-schema enum gaps are recorded explicitly. Installed knowledge includes the owner specification and a compiled example.

Common mistakes to avoid:

  • Treating frame completion as destruction of all closure objects.
  • Adding coroutine/sync machinery merely to retain a function value.
  • Capturing a mutable local as a hidden shared cell instead of a snapshot.
  • Deep-copying captured objects and losing intended shared identity.
  • Testing only opcode emission while missing runtime roots, imports or full groups.
  • Leaving editor visitors or installed examples on the retired callback model.

References