feat(pbs): implement first-class functions and explicit captures

This commit is contained in:
2026-10-17 01:27:52 +01:00
parent 39df63581c
commit 2a418085d2
55 changed files with 996 additions and 459 deletions
@@ -0,0 +1,76 @@
# 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.
@@ -47,7 +47,7 @@ It must feel fluid for frame-driven gameplay code while remaining strict enough
- Runtime and bytecode authority override language preferences.
- Closed VM compatibility is mandatory.
- `FRAME_SYNC`-based execution semantics are preserved.
- The existing synthetic frame lifecycle is preserved; PBS exposes no sync or coroutine construct.
- Host API usage remains capability-gated and versioned.
- Canonical host primitive bindings remain reserved to SDK/toolchain-controlled `declare host` surfaces.
@@ -69,7 +69,7 @@ The following inputs are already fixed elsewhere and must not be contradicted he
- Struct values are reference-like and identity-bearing in v1 core.
- Service values are canonical module-owned singleton values in v1 core.
- `declare const` values are compile-time constants rather than mutable runtime module storage.
- `FRAME_SYNC` is the only normative safepoint in PBS v1.
- PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
- Core PBS v1 does not expose explicit lifetime-control syntax in ordinary user code.
## 6. Runtime Memory Spaces
@@ -124,16 +124,9 @@ Contract values do not introduce a new user-visible identity distinct from the u
They are runtime views over an underlying identity-bearing value together with the selected contract implementation used for dispatch.
### 7.5 Callback values
### 7.5 Function values and closures
Callback values are first-class callable values in PBS v1.
They may be assigned, passed, and returned, but callback identity is not promoted as a separate user-visible identity concept.
When formed through `bind(context, fn_name)`, a callback value retains:
- the target function,
- and the same captured struct context identity without copying it.
Closures are ordinary managed objects retaining their typed captures. Reachable closures may survive across frames; unreachable closures are eligible for GC. Their invocations do not suspend across frames. See [First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md).
## 8. Identity, Aliasing, and Copy Behavior
@@ -201,11 +194,11 @@ The language does not promise:
### 9.3 Safepoint relationship
`FRAME_SYNC` is the only normative safepoint in PBS v1.
PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
No user-visible program rule may depend on another safepoint existing.
Implementations may perform internal GC work outside `FRAME_SYNC` only if doing so creates no additional user-visible semantic effects.
GC timing remains a runtime concern and introduces no user callback or observable scheduling operation.
### 9.4 Observability
@@ -250,15 +243,9 @@ The normatively relevant cost facts in PBS v1 are:
- whether an operation crosses the host boundary,
- whether an operation may trap.
### 11.2 `bind`
### 11.2 Explicit capture storage
`bind(context, fn_name)` is retention-bearing and requires runtime storage sufficient to preserve:
- the callback target identity,
- the captured context,
- and the captured context's continued liveness while the callback value remains alive.
This document does not freeze the exact runtime layout used to implement that storage.
Closure creation retains the values named in its explicit capture list, including shared object identities. Lifetime follows ordinary reachability and runtime resource limits. Captured bindings cannot be reassigned.
### 11.3 Non-allocation-bearing surfaces by themselves
@@ -99,7 +99,7 @@ The v1 AST must represent, at minimum, declaration families for:
- `service`,
- `error`,
- `enum`,
- `callback`,
- structural `Fn` types and lambda expressions with explicit captures,
- `declare global`,
- `declare const`,
- and declaration nodes required by barrel/linking flow.
@@ -258,7 +258,7 @@ The mandatory warning identity for this rule is `W_SEM_IGNORED_VALUE`.
Tooling may surface qualitative cost facts as warnings or notes, especially for:
- retention-bearing `bind`,
- retention-bearing explicit closure captures,
- observable copy-versus-alias semantics,
- and host-boundary crossings.
@@ -163,7 +163,6 @@ BarrelItem ::= BarrelFnItem
| BarrelServiceItem
| BarrelGlobalItem
| BarrelConstItem
| BarrelCallbackItem
BarrelVisibility ::= 'mod' | 'pub'
BarrelFnItem ::= BarrelVisibility 'fn' Identifier ParamList ReturnAnn? ';'
@@ -175,7 +174,6 @@ BarrelEnumItem ::= BarrelVisibility 'enum' Identifier ';'
BarrelServiceItem ::= BarrelVisibility 'service' Identifier ';'
BarrelGlobalItem ::= BarrelVisibility 'global' Identifier ';'
BarrelConstItem ::= BarrelVisibility 'const' Identifier ';'
BarrelCallbackItem ::= BarrelVisibility 'callback' Identifier ';'
```
Rules:
@@ -191,7 +189,6 @@ Rules:
- Multiple `fn` barrel entries with the same identifier are allowed only when signatures differ (overload set).
- Barrel labels MAY differ from the implementation labels.
- A `fn` barrel entry must resolve to exactly one declaration in module scope.
- A `callback` barrel entry must resolve to exactly one top-level callback declaration in module scope.
- A `host` barrel entry must resolve to exactly one top-level `declare host` declaration in module scope.
- A `struct` barrel entry governs the visibility of the struct declaration and of all methods declared directly in that struct body.
- A `host` barrel entry governs the visibility of the host declaration and of all method signatures declared directly in that host body.
@@ -210,7 +207,6 @@ pub host Gfx;
pub enum GameState;
pub service Physics;
pub global Palette;
pub callback TickCb;
```
## 6. File grammar
@@ -272,7 +268,7 @@ Rules:
### 6.2 Top-level declarations
```ebnf
TopDecl ::= TypeDecl | CallbackDecl | FunctionDecl | GlobalDecl | ConstDecl | ImplDecl
TopDecl ::= TypeDecl | FunctionDecl | GlobalDecl | ConstDecl | ImplDecl
```
Top-level `let` forms and top-level executable statements are forbidden.
@@ -366,20 +362,9 @@ Rules:
- Contract values are formed from struct values or service singleton values by explicit or contextual conversion, as defined by static semantics.
- Structs do not have static methods in v1 core.
### 7.2 Callbacks
### 7.2 First-class function values
```ebnf
CallbackDecl ::= 'declare' 'callback' Identifier ParamList ReturnAnn? ';'
```
Rules:
- A callback declaration introduces a nominal callback type.
- A callback declaration defines exactly one callable signature.
- A callback declaration has no body.
- A callback declaration is distinct from `contract` and `fn`.
- A callback declaration may be exported through `mod.barrel` using `callback`.
- Callback values may be formed either by assigning a compatible top-level `fn` or by using `bind(context, fn_name)` under a callback-typed context.
Function types use `Fn(T1, T2) -> R`. Lambdas use `fn [captures](name: Type) -> Return { ... }`; `[]` and all signature annotations are mandatory. See [First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md).
### 7.3 Services
@@ -464,7 +449,7 @@ Rules:
```ebnf
TypeRef ::= OptionalType | TypePrimary
TypePrimary ::= SelfType | SimpleType | NamedTupleType | GroupType | UnitType
TypePrimary ::= FnType | SelfType | SimpleType | NamedTupleType | GroupType | UnitType
SelfType ::= 'Self'
SimpleType ::= Identifier
NamedTupleType ::= '(' NamedTupleField (',' NamedTupleField){0,5} ')'
@@ -586,11 +571,13 @@ ArgList ::= Expr (',' Expr)*
Literal ::= IntLit | FloatLit | StringLit | BoolLit
BoolLit ::= 'true' | 'false'
PrimaryExpr ::= Literal | Identifier | ThisExpr | NewExpr | BindExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block
PrimaryExpr ::= Literal | Identifier | ThisExpr | NewExpr | LambdaExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block
ThisExpr ::= 'this'
NewExpr ::= 'new' NewTarget '(' ArgList? ')'
NewTarget ::= Identifier ('.' Identifier)?
BindExpr ::= 'bind' '(' Expr ',' Identifier ')'
LambdaExpr ::= 'fn' '[' CaptureNames? ']' ParamList '->' TypeRef Block
CaptureNames ::= Identifier (',' Identifier)*
FnType ::= 'Fn' '(' (TypeRef (',' TypeRef)*)? ')' '->' TypeRef
SomeExpr ::= 'some' '(' Expr ')'
NoneExpr ::= 'none'
OkExpr ::= 'ok' '(' Expr ')'
@@ -635,9 +622,6 @@ Rules:
- Tuple expressions may be written with explicit labels (`(a: 1, b: 2)`) or positional sugar (`(1, 2)`).
- Positional tuple expression sugar requires an expected named tuple shape supplied by context.
- No single-slot tuple literal exists in v1 core syntax.
- `bind(context, fn_name)` is the canonical surface for explicit callback context binding.
- `bind(context, fn_name)` binds only the first parameter of `fn_name`.
- The second operand of `bind` is a function identifier, not an arbitrary expression.
- Mixing labeled and unlabeled tuple items in the same `TupleExpr` is a syntax error.
- Member selection of a struct, service, host, or contract method is valid only as an immediate call target; bare method extraction such as `let m = s.compute;` is invalid.
@@ -677,14 +661,12 @@ Diagnostics that require name resolution, overload resolution, or type context a
- invalid `ok(...)` construction form,
- invalid `err(...)` construction form,
- use of `ok(...)` or `err(...)` outside allowed result-flow positions,
- invalid `bind(...)` construction form,
- invalid `else` extraction form,
- invalid `if` expression form,
- invalid `switch` expression form,
- invalid `for` loop form,
- invalid `new` construction form,
- invalid enum case path,
- invalid callback declaration shape,
- invalid struct field access modifier surface,
- invalid struct method declaration shape,
- invalid service method declaration shape,
@@ -923,7 +905,6 @@ This section is the canonical reference example set for PBS v1 syntax.
It consolidates the primary surface forms used by tooling and conformance for:
- `apply` and call sugar,
- `bind` and nominal callbacks,
- overloads that differ by return shape,
- `optional`,
- `result<Error>`,
@@ -1019,45 +1000,21 @@ declare service Physics {
}
```
### 15.6 Nominal callback
### 15.6 Function values
```pbs
declare callback TickCb(dt: int) -> void;
fn on_tick(dt: int) -> void {
let _ = dt;
}
fn install(cb: TickCb) -> void {
cb apply 16;
cb(16);
}
fn demo_callback() -> void {
let cb: TickCb = on_tick;
install(cb);
fn twice(x: int) -> int { return x * 2; }
fn demo_function() -> int {
let f: Fn(int) -> int = twice;
return f(21);
}
```
### 15.7 Bound callback
### 15.7 Explicit captures
```pbs
declare callback UpdateCb(dt: int) -> void;
declare struct Enemy(pub hp: int);
fn enemy_tick(self: Enemy, dt: int) -> void {
let _ = self.hp;
let _ = dt;
}
fn install_update(cb: UpdateCb) -> void {
cb apply 16;
}
fn demo_bind(enemy: Enemy) -> void {
let cb: UpdateCb = bind(enemy, enemy_tick);
install_update(cb);
fn create_adder(n: int) -> Fn(int) -> int {
return fn [n](x: int) -> int { return n + x; };
}
```
@@ -1240,3 +1197,5 @@ fn test(e: Enum) -> str {
## Typed arrays and optional execution extension
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
Retired `declare callback`, callback exports and `bind(...)` are rejected. They do not provide alternative spellings for Fn or lambdas.
@@ -38,13 +38,13 @@ PBS distinguishes at least:
Rules:
- `declare struct`, `declare service`, `declare contract`, `declare error`, `declare enum`, `declare callback`, and `declare builtin type` introduce names in the type namespace.
- `declare struct`, `declare service`, `declare contract`, `declare error`, `declare enum`, and `declare builtin type` introduce names in the type namespace.
- `declare host` introduces names in the host-owner namespace.
- `let`, parameters, `declare const`, and `declare global` introduce names in the value namespace.
- `declare service Name` also introduces the canonical singleton value `Name` in the value namespace.
- Top-level `fn`, service methods, and host methods participate in the callable namespace.
- `fn` declarations are not first-class values in v1 core and therefore do not become ordinary value expressions.
- `bind(...)` is a callback-formation construct, not a general function-value construct.
- Named top-level functions can form first-class Fn values with structural signatures.
- Function values use structural `Fn` types and explicit lambda captures.
- `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
- `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
- A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner.
@@ -207,12 +207,12 @@ Rules:
- Each semantic parameter record MUST carry its canonical source/API name, zero-based order, type when known, and origin/source sufficient for implementation and diagnostics.
- A struct method is identified by `(struct type, method name, input tuple shape excluding the receiver slot, output tuple shape)`.
- A contract value is identified at the type level by its contract type and at runtime by an underlying concrete struct instance or service singleton value plus its selected implementation.
- A callback declaration defines a nominal callable type with exactly one input/output tuple shape.
- A function type defines an ordered parameter/result signature independent of names or captures.
- A service method is identified by `(service name, method name, input tuple shape, output tuple shape)`.
- A host method is identified by `(host owner name, method name, input tuple shape, output tuple shape)` within the PBS declaration surface.
- A builtin intrinsic method is identified within PBS declaration surface by `(builtin type name, method name, input tuple shape, output tuple shape)` and lowers further by canonical builtin/intrinsic metadata.
- A top-level `fn` is identified by `(name, input tuple shape, output tuple shape)`.
- A callback value is identified at the type level by its declared callback type and signature.
- Function value compatibility uses its structural signature.
- Contract signatures and barrel signatures must preserve the same callable shape.
- Canonical host primitive identity and binding are governed by the Host ABI Binding specification rather than by ordinary v1 core declaration identity alone.
- The compiler semantic model is the canonical owner of callable parameter names for completion, signature help, hover, diagnostics, and other editor-facing surfaces.
@@ -312,7 +312,6 @@ Rules:
- A non-builtin `declare const` initializer must not use:
- callable application or call sugar,
- `new`,
- `bind(...)`,
- `some(...)` or `none`,
- tuple expressions,
- block expressions,
@@ -436,70 +435,9 @@ fn demo() -> int {
}
```
### 3.7 Nominal callbacks
### 3.7 Structural function values
Rules:
- `declare callback Name(params...) -> R;` introduces a nominal callback type `Name`.
- A callback type is not a `fn`, and a `fn` declaration does not implicitly define a callback type.
- A value of callback type may be formed only from a compatible top-level `fn` in v1 core.
- A value of callback type may also be formed by `bind(context, fn_name)` when the surrounding static type context expects a callback type.
- Service methods are not assignable to callback values in v1 core.
- Host methods are not assignable to callback values in v1 core.
- Callback values do not capture local environment implicitly.
- Assignment of a top-level `fn` to a callback type succeeds only when exactly one visible overload matches the callback signature.
- `bind(context, fn_name)` succeeds only when exactly one visible top-level `fn` overload matches after consuming the first parameter with `context`.
- Valid expected callback contexts for `bind(context, fn_name)` include variable initialization with an explicit callback type, assignment to an explicitly typed callback location, argument passing to a callback-typed parameter, and return from a callback-typed function.
- The context expression in `bind(context, fn_name)` is evaluated once at bind time and stored explicitly in the resulting callback value.
- When that stored context is identity-bearing, the resulting callback preserves the same captured identity rather than copying an independent underlying object.
- `bind(context, fn_name)` does not introduce general closures; it is explicit partial binding of the first parameter only.
- Callback compatibility ignores labels and compares ordered input/output slot types plus the return-surface kind.
Example:
```pbs
declare callback TickCb(dt: int) -> void;
fn on_tick(dt: int) -> void {
}
fn install_tick() -> void {
let cb: TickCb = on_tick;
let _ = cb;
}
```
Bound example:
```pbs
declare callback UpdateCb(dt: int) -> void;
declare struct Enemy(hp: int);
fn update_enemy(self: Enemy, dt: int) -> void {
}
fn install_update(enemy: Enemy) -> void {
let cb: UpdateCb = bind(enemy, update_enemy);
let _ = cb;
}
```
Ambiguous overload example:
```pbs
declare callback TickCb(dt: int) -> void;
fn tick(dt: int) -> void {
}
fn tick(time: int) -> void {
}
fn install_tick() -> void {
let cb: TickCb = tick; // error: ambiguous overloaded fn assignment
}
```
[First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md) defines structural Fn compatibility, explicit snapshot captures and lambda typing. Assignment of a named function requires exactly one matching overload. Bare method extraction remains invalid; use an explicit receiver-capturing lambda.
### 3.8 Canonical application
@@ -801,7 +739,6 @@ At minimum, deterministic static diagnostics are required for:
- invalid contract coercion from concrete struct or service value,
- unresolved barrel function signature after label-insensitive matching,
- unresolved host barrel entry,
- unresolved callback barrel entry,
- invalid enum case path,
- invalid enum intrinsic member call,
- invalid named constructor target,
@@ -811,9 +748,6 @@ At minimum, deterministic static diagnostics are required for:
- ambiguous overloaded top-level `fn` assignment to callback type,
- attempted assignment of service method to callback type,
- attempted assignment of host method to callback type,
- use of `bind(...)` without an expected callback type,
- incompatible `bind(...)` context type for callback target,
- ambiguous overloaded top-level `fn` target in `bind(...)`,
- `apply` on a non-callable target,
- arity mismatch in `apply`,
- argument type mismatch in `apply`,
@@ -67,7 +67,7 @@ This document integrates the following accepted decisions:
The following inputs are already fixed elsewhere and must not be contradicted here:
- PBS prioritizes determinism and compatibility over ergonomics when the two conflict.
- `FRAME_SYNC`-based execution semantics remain preserved.
- The existing synthetic frame lifecycle remains preserved; PBS exposes no sync or coroutine construct.
- No non-deterministic async execution model is part of PBS v1.
- Function application is defined on the canonical `apply` surface, with call sugar desugaring to `apply`.
- `optional T` function fallthrough yields `none`.
@@ -93,7 +93,7 @@ User-visible sequencing is defined by:
VM-internal frame layout, temporary storage, and lowering steps are not observable unless they change one of the semantic effects above.
`FRAME_SYNC` is the only normative safepoint in PBS v1.
PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
## 6.1 Lifecycle bootstrap
@@ -161,7 +161,7 @@ The following expressions are evaluated exactly once where they appear:
- the payload expression of `some(expr)`,
- the operand of `expr!`,
- the operand of `handle expr { ... }`,
- the context expression of `bind(context, fn_name)`,
- explicit closure capture values,
- call receivers, callees, and argument expressions as required by the call rule above.
## 8. Blocks and Abrupt Completion
@@ -253,7 +253,7 @@ For the remap-only case, a short form such as `E1.case -> E2.case` is sugar for
`handle` does not intercept or convert traps.
## 11. `apply`, Call Sugar, and `bind`
## 11. Function application and closures
### 11.1 Canonical role of `apply`
@@ -279,22 +279,9 @@ If a callable returns:
- `optional<P>`, extraction remains explicit through `else`,
- `result<E> P`, propagation or processing remains explicit through `!` or `handle`.
### 11.3 `bind`
### 11.3 Closure creation and invocation
`bind(context, fn_name)` is the explicit callback-formation mechanism in PBS v1.
It:
- evaluates `context` exactly once,
- captures the same struct context identity without copying it,
- attaches that context to the resolved top-level function target,
- produces a callback value whose invocation behaves as if the target function were called with the captured context as its first argument.
At the language-semantics level, `bind` is trap-free.
Incompatible binding shape remains a compile-time matter rather than a runtime failure mode.
Retention and storage consequences of `bind` belong to `Memory and Lifetime Specification.md`.
Explicit capture lists snapshot values at creation. Object references retain identity. Calls complete within the current frame; objects may remain reachable between frames. See [First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md).
## 12. Branch Selection