90 lines
6.3 KiB
Markdown
90 lines
6.3 KiB
Markdown
# First-class functions and explicit value captures
|
|
|
|
Owner: `compiler/pbs`. This specification defines PBS function values and closures. Runtime Registry/PBX layout, allocation, GC, resource limits and faults remain governed by the runtime contracts. It supersedes the retired nominal callback and `bind` model.
|
|
|
|
## Types and calls
|
|
|
|
`Fn(T1, T2) -> R` is a structural function type. Its identity is the ordered logical parameter and result types, excluding parameter names, target identity and captures. Named functions and lambdas with the same signature have the same function type. Incompatible signatures do not convert implicitly. Physical slot count alone is not a type identity.
|
|
|
|
A function value can be assigned, passed, returned and stored in a collection or object. A named top-level function is referenced by its identifier without an address operator. When overloaded, its expected function type must select exactly one compatible overload. Calls use ordinary parentheses.
|
|
|
|
```pbs
|
|
fn twice(value: int) -> int { return value * 2; }
|
|
fn invoke(value: int, transform: Fn(int) -> int) -> int {
|
|
return transform(value);
|
|
}
|
|
fn example() -> int {
|
|
let transform: Fn(int) -> int = twice;
|
|
return invoke(21, transform);
|
|
}
|
|
```
|
|
|
|
Function-returning functions use `-> Fn(int) -> int`. Function array elements use grouping, for example `array<(Fn(int) -> int)>`. Existing array vacancy and optional-read rules apply; accessing an empty slot does not fabricate a callable.
|
|
|
|
## Lambdas
|
|
|
|
The sole lambda form is `fn [captures](parameter: Type) -> Return { body }`. The capture list is mandatory, including `[]` for no captures. Parameter types and return type are explicit. The body is a block and values use explicit `return`; a trailing expression is not an implicit return. The initialized variable's type may be inferred from the lambda signature.
|
|
|
|
```pbs
|
|
fn createMultiplier(factor: int) -> Fn(int) -> int {
|
|
return fn [factor](value: int) -> int { return value * factor; };
|
|
}
|
|
```
|
|
|
|
A lambda may only access outer local bindings through its explicit capture list. Capture entries name unique available outer bindings. Parameters and local declarations have their ordinary lexical scopes. Captures are not hidden public parameters and do not affect the public Fn signature.
|
|
|
|
## Snapshot capture and object identity
|
|
|
|
Each capture fixes the binding's value when the closure is created. This includes mutable outer bindings: later assignment to the outer binding does not modify the capture. Assigning to a captured binding inside the closure is invalid. There are no automatic captures, reference captures or implicit shared cells for local variables.
|
|
|
|
```pbs
|
|
fn snapshot() -> int {
|
|
let bonus = 5;
|
|
let add = fn [bonus](value: int) -> int { return value + bonus; };
|
|
bonus = 20;
|
|
return add(10); // 15
|
|
}
|
|
```
|
|
|
|
Capturing an object reference preserves that reference's identity; it does not deep-copy the object. Field mutation remains governed by the object's field access rules. Closures sharing the same object observe its mutations. Separate object instances retain separate state. Adapting a method to Fn requires an explicit lambda capturing its receiver; bare method extraction is not introduced.
|
|
|
|
```pbs
|
|
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;
|
|
};
|
|
}
|
|
```
|
|
|
|
## Object lifetime and frame execution
|
|
|
|
Closures are managed objects. They may escape their creator and remain reachable through globals, fields, arrays or other captures across frames. The GC traces their captures; unreachable closures and environments are collectible under the ordinary runtime contract.
|
|
|
|
An invocation runs to completion within its logical frame. PBS offers no coroutine, suspension/resumption construct or `sync` syntax. The existing frontend publishes FRAME_ROOT and the existing lifecycle assembler creates the guarded frame wrapper. This feature must reuse that lifecycle without adding an alternative frame loop or synthetic integration. Retaining a closure object across frames is different from retaining a suspended invocation.
|
|
|
|
## Lowering and validation
|
|
|
|
The frontend emits typed Fn descriptors and capture metadata, MAKE_CLOSURE, GET_CAPTURE and CALL_CLOSURE through the common IR. Named function values also use runtime Closure objects with empty captures. Captured multi-slot groups and function parameters/results must remain complete. Nested invocations use their own environments. Receiver adapters preserve receiver identity and contract dispatch order.
|
|
|
|
Function creation and calls remain subject to existing resource checks and runtime faults. No quota relaxation, allocation rescue GC, automatic scheduler or special fault isolation is introduced.
|
|
|
|
`declare callback`, callback barrel exports and `bind(context, function)` are retired source forms and must be rejected. Existing programs and examples must use structural Fn and explicit lambdas. Historical provenance and negative tests may mention the removed forms.
|
|
|
|
Conformance must compile actual PBS through production PBX and execute it in the production VM. Required cases include signature errors, explicit capture enforcement, snapshots, escaped closures, shared and isolated objects, collection transport, nested closures and function captures, receiver/contract integration, and reachable/unreachable closure behavior across the existing frame lifecycle and GC. Installed knowledge must package this specification and a compilable example.
|
|
|
|
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
|
|
|
|
|
|
## Parameterized contract integration
|
|
|
|
[Generic contracts](generic-contracts.md) extend nominal contract declarations with explicit type arguments. Valid Array/Fn/optional/tuple compositions preserve their existing logical and physical rules after substitution. No generic-only Dynamic transport, view wrapper, altered resource limit or new runtime opcode is introduced.
|
|
|
|
[Generic structs and free functions](generic-structs-and-free-functions.md) extend
|
|
that concrete model to state and bodies. A closed free-function application such
|
|
as `identity<int>` supplies an ordinary concrete Fn through an empty-environment
|
|
Closure. Lambdas inside specialized bodies preserve explicit captures and complete
|
|
logical value groups. The open template never becomes a polymorphic Fn value.
|