docs: consolidate canonical specs and preserve PBS reference IDs

This commit is contained in:
2026-10-28 15:11:00 +00:00
parent 9504f4694a
commit 3a3417eb44
74 changed files with 3231 additions and 270 deletions
@@ -82,7 +82,7 @@ Before implementation starts, PBS must define at least:
7. AST Specification.
8. Diagnostics Specification.
9. Lowering IRBackend Specification.
10. Shared acceptance specs in `docs/general/specs` (Conformance, Compatibility, Verification).
10. Shared acceptance specs in `docs/specs/compiler` (Conformance, Compatibility, Verification).
## 11. Decision Rule
@@ -39,8 +39,8 @@ This document does not define:
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
1. Runtime authority ([provider specifications](../../../../../runtime/docs/specs/runtime/README.md); [mirror and provenance policy](../../../vm-arch/README.md))
2. Bytecode authority ([provider Core ISA](../../../../../runtime/docs/vm-arch/ISA_CORE.md))
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
@@ -126,7 +126,7 @@ They are runtime views over an underlying identity-bearing value together with t
### 7.5 Function values and closures
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).
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](15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
## 8. Identity, Aliasing, and Copy Behavior
@@ -177,7 +177,7 @@ At minimum, those roots include:
- currently active local/frame state,
- reachable fields of reachable struct instances,
- service singleton roots,
- retained callback state that remains reachable,
- retained closure state that remains reachable,
- and any other runtime roots required to preserve already-observable PBS behavior.
If a GC-managed value remains reachable through the normative runtime state, the implementation must preserve its continued semantic availability.
@@ -325,4 +325,7 @@ This document is ready to move beyond temporary draft status only when:
## 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter supplies shared reachability and ownership rules; Array storage
and complete-group packing are defined by that owner.
@@ -180,23 +180,27 @@ This document is healthy when:
## 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter preserves syntax and type arguments in the AST; the owner chapter
defines Array application admissibility and execution.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
Array spelling and construction are owned by [Core Syntax](3.%20Core%20Syntax%20Specification.md)
and the Array chapter; AST, diagnostics and lowering MUST consume that same syntax.
## Parameterized contracts
Contract declarations and barrel items preserve ordered type-parameter names and individual spans. Applied type references preserve ordered child arguments and spans. Implements and as carry a complete target type reference. Semantic imported bindings retain the original declaration and importing lexical scope rather than inventing nominal origins. Existing visitors must traverse type arguments as well as inner/group/Fn/tuple children.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md).
## Concrete generic structs and free functions
Structs and free functions preserve ordered parameter declarations and spans. Explicit applied function references preserve type arguments and their source span. Implements preserves its binder, full applied owner and target. Substitution rewrites every field, signature, annotation and executable body/capture position with a declaration-local environment. Concrete application provenance retains original declaration, canonical logical arguments and requesting use; it is not an executable runtime template.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
## Guest hook marker identity
@@ -299,27 +299,31 @@ This document is ready to move beyond temporary status only when:
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
The [PBS input and value alignment contract](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
## 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter owns diagnostic classification and source attribution; the owner
chapter defines which Array forms are rejected.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
Array spelling and construction are owned by [Core Syntax](3.%20Core%20Syntax%20Specification.md)
and the Array chapter; AST, diagnostics and lowering MUST consume that same syntax.
## Parameterized contracts
Parameterized contract diagnostics distinguish exact arity (E_SEM_CONTRACT_ARITY), undeclared/duplicate parameters (E_SEM_CONTRACT_PARAMETER), invalid applications (E_SEM_CONTRACT_ARGUMENT), incompatible or incomplete implementations (E_SEM_CONTRACT_SIGNATURE), duplicate pairs (E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION), invalid owners/modules (E_SEM_CONTRACT_OWNER / E_SEM_CONTRACT_OWNER_MODULE), invalid coercions (E_SEM_CONTRACT_COERCION), and bounded expansion/resource exhaustion (E_SEM_CONTRACT_EXPANSION). Barrel parameter disagreement uses E_LINK_CONTRACT_PARAMETERS. Existing invalid Array/Fn/optional/Self diagnostics also apply after substitution.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md).
## Concrete generic structs and free functions
Generic diagnostics distinguish duplicate/unbound parameters, exact arity, raw or improperly inferred application, unjustified symbolic capabilities, invalid substituted positions, constructor errors, collapsed overloads, invalid bound owners, overlap and bounded expansion. Preserve declaration and requesting-use locations with a short instantiation chain. Editor projections retain symbolic parameter, concrete argument and generic origin identities. Generated instance names and host stacks do not replace source explanations.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
## Guest lifecycle diagnostics and conformance
@@ -241,27 +241,31 @@ At frontend `IRBackend` emission time:
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
The [PBS input and value alignment contract](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
## 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter owns source-to-common-IR projection; the owner chapter defines
Array storage, optional carriers and complete-group requirements.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
Array spelling and construction are owned by [Core Syntax](3.%20Core%20Syntax%20Specification.md)
and the Array chapter; AST, diagnostics and lowering MUST consume that same syntax.
## Parameterized contracts
The frontend substitutes each closed application and emits a concrete nominal Trait descriptor shared by equivalent uses. Distinct logical applications remain distinct despite shared physical carriers. Concrete implementation functions take the receiver first. CALL_TRAIT evaluates and roots the receiver before arguments, evaluates arguments left to right, then places the complete receiver/ImplementationId view after the argument groups as required by the runtime ABI. Preserve exact signatures, absence, ImplementationId zero, ownership, GC and quotas; generic calls do not add a Dynamic ABI or adaptation wrapper.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md).
## Concrete generic structs and free functions
Instantiate structs, free functions and owner-bound implementations within PBS before publishing executable descriptors. Registry receives concrete fields, signatures, bodies, capture groups and targets. Specialized free-function references use existing empty-environment Closure values; Fn remains structural. Preserve receiver identity, implementation zero, singletons, rooting, GC, ownership, evaluation/fault order and quotas. No generic Dynamic/boxing ABI, opcode, descriptor category or runtime instantiation engine is introduced.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
## Lowering optional runtime hook roles
@@ -0,0 +1,120 @@
# Typed arrays and optional execution
Status: Normative. Owner: `compiler/pbs`.
Scope: Typed Arrays and Optional Execution.
This specification defines the source contract for typed arrays and their integration with existing optional, struct and contract semantics. Runtime Registry, PBX, ownership, limits and faults remain governed by the runtime specifications. The completed implementation and conformance gates are recorded in [LSN-0083](../../../../discussion/lessons/DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md) and its evidence.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Types and construction
`array<T>` denotes a fixed-length reference to positions holding values of T or no value. Nesting is compositional: `array<array<Enemy>>` holds array references. The compiler bounds structural type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST. Allocation length belongs to the constructor, not the type.
```pbs
let enemies = new array<Enemy>(10);
let contextual: array<Enemy> = new array<>(10);
let omitted: array<Enemy> = new array(10);
let groups: array<array<Enemy>> = new array<>(3);
let scores: array<int> = [10, 20, 30];
let empty: array<Enemy> = [];
```
`new array<T>(length)` supplies its own type, including when the binding has no annotation. T must resolve to a valid element type. `new array<>(length)` and `new array(length)` are equivalent sugars requiring an expected array type. The length never supplies element-type information. All forms allocate only the outer array: each position is empty, with no implicit subarray, element construction or callback.
Every array literal, including a nonempty literal, requires an expected array type. The compiler must not infer its type from its elements. Expected types propagate through annotated local/global bindings, assignments, arguments with a resolved single callable signature, returns and nested value expressions. This migration does not expand overload resolution; contextual construction without sufficient expected type is an error. Incompatible explicit constructor types and literal elements are errors; they do not produce a public Dynamic type.
Arrays are invariant in element type and nesting. Assignment and argument passing share the array reference. The runtime's shared storage carrier must not make different PBS array types interchangeable. `array<optional T>` is invalid, including through grouped types. `optional (array<T>)` remains valid and distinguishes an absent array from a present array whose positions are empty.
Type delimiters can be adjacent to assignment: `let a: array<array<int>>=new array<>(3);` is valid. Parsing consumes type closers contextually while preserving expression comparisons such as `x >= y`. This does not introduce shift operators. Optional, `result<Error>` and `Fn(...) -> ...` retain their existing spellings.
Legacy `array T`, `array[N] T`, and `array<T>[N]` are rejected. `T[]`, `[]T`, `array !! T`, `new T[n]` and `new array[n]` are not alternative spellings. PBS exposes neither a null value nor a Dynamic type.
The frontend AST retains recursive element types and their spans. Constructor nodes distinguish explicit type arguments, diamond and omission; explicit construction types must reach semantic analysis, source tooling and PBS lowering without relying on a destination annotation. Common backend IR and runtime storage do not acquire PBS syntax rules.
## Operations and ordering
- `values.length` returns long and includes empty positions. Length is fixed; zero is valid.
- `values[index]` returns `optional T`. Empty positions return none; populated positions return some(value). Numeric zero is present.
- `values[index] = value` stores T and replaces the previous position.
- `values.clear(index)` empties a position without changing length and returns unit.
Allocation lengths, indices and clear indices accept int and long literals, variables and expressions. The compiler promotes int to long without loss in these operations only. This does not introduce general implicit numeric conversions. Lengths must satisfy the runtime's u32 and resource bounds; long values must not be truncated.
Receiver, index and value expressions are evaluated once, left to right. Array literals evaluate elements in source order. Invalid indices fault, including accesses to a zero-length array; they must never be reported as none. Runtime type and resource failures retain their original meanings.
## Optional control flow
```pbs
if let enemy = enemies[1] {
enemy.takeDamage(10);
} else {
// Runs only when the position is empty.
}
```
`if let name = expression` requires optional T and evaluates its expression once. For some, the success block receives name of type T. For none, the success block is skipped and the optional else branch runs. The binding exists only inside the success block and must not leak into else or following statements. Outer bindings retain their identities after the conditional.
`value else fallback` evaluates fallback only for none. `some(value)`, contextual `none`, optional parameters/results, tuple payloads and nested optional values preserve their complete source types and groups. The existing `hasSome()` and `hasNone()` methods take no arguments and return bool. Optional function fallthrough yields none, following existing PBS rules; a trailing expression in a function body is not an implicit return.
## Runtime representation
Array positions use runtime `Array<Dynamic>` internally. An empty position is the untyped-null group `[Null, Null]`. A present position carries the exact runtime TypeId and payload for its statically checked PBS value. Runtime-supported single-slot payloads, including numeric values, are stored directly. Runtime multi-slot values use its immutable Dynamic boxing contract; the compiler must not introduce a heap box per single-slot integer.
Presence must be checked using the Dynamic tag before extraction. `DYN_CAN_UNPACK` alone is insufficient because untyped null can be compatible with nullable types. Type incompatibility must fault rather than becoming absence. Clearing restores the complete empty Dynamic group.
PBS optional values use private nullable Struct carriers: null denotes none and a private instance contains the full payload for some. Named tuples remain flattened at callable boundaries and use private storage carriers where a single Registry type is required. These private carriers are inaccessible to source programs. They preserve nested optional distinctions, tuple value behavior and reference aliases within payloads.
Lowering must keep complete receiver/index/value groups rooted across allocations, calls and collection operations. GC, native ownership, quota accounting, costs and per-instruction refusal preservation remain runtime contracts. No failure may publish partially initialized handles or be suppressed as none; no quota may be relaxed to satisfy conformance.
## Struct and contract integration
Existing PBS struct and contract rules apply unchanged: structs have reference identity; field visibility and `pub mut` control access; positional and named constructors obey overload selection and definite assignment; receiver `this`, fields and grouped values must execute faithfully. Runtime default initialization does not authorize exposure of a partially constructed source value.
`contract` and `implements` lower to typed Registry Trait descriptors and implementation tables. Adaptations preserve receiver and ImplementationId, including valid ID zero. `CALL_TRAIT` must use the selected method signature and complete argument/result groups. Struct and service owners are supported; service adaptations preserve singleton identity. This execution base is independent of future closure support.
## Diagnostics, tooling and conformance
Diagnostics must reject missing expected array types for contextual construction, unresolved explicit element types, excessive nesting, removed syntax, optional elements, incompatible invariant arrays, non-integral sizes/indices and non-optional if-let operands. Editor types and hints use PBS array notation. Hover, completion, definitions, references and rename must respect success-only binding scope and source element identity.
Conformance must compile real PBS through typed IR and production PBX into the production loader/VM. Required cases include vacancy versus zero, alias mutation, contextual literals, nested arrays, int/long bounds, lazy and single evaluation, multi-slot groups, constructors and contract dispatch, service identity, resource refusal and GC/ownership. Assembly-only probes are insufficient. Installed knowledge must package this specification and executable examples.
## Related specifications
- [Core syntax](3.%20Core%20Syntax%20Specification.md)
- [Static semantics](4.%20Static%20Semantics%20Specification.md)
- [Dynamic semantics](9.%20Dynamic%20Semantics%20Specification.md)
- [Existing type runtime alignment](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md)
[SDK List and Cursor](21.%20SDK%20List%20and%20Cursor%20Specification.md) define logical size, growth and
snapshot traversal above private fixed-length arrays. List capacity does not
create logical elements; fixed array length does. Set/Map, equality and hashing
policies remain separate concerns.
See [Runtime Random integration](20.%20Runtime%20Random%20Integration%20Specification.md) for opaque generator aliases in typed storage and captures.
[Map/Keyval](24.%20SDK%20Map%20and%20Keyval%20Specification.md) stores V in generic node fields and therefore
admits optional values. Its outer lookup/previous-value optional describes entry
existence independently of stored V; some(none) is distinct from absent none.
This does not change Array's direct optional-element restriction.
## Parameterized contract integration
[Generic contracts](16.%20Generic%20Contracts%20Specification.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](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md) reuse
these contextual construction positions and storage rules. A generic T field can
hold an optional value, but substituting an optional value type into array<T>
remains invalid. Array's private packing does not become a generic argument ABI.
SDK collections add logical checks before physical Array operations and terminate
logical refusals with TRAP_EXPLICIT. Their multi-instruction methods use the
[List mutation-phase contract](21.%20SDK%20List%20and%20Cursor%20Specification.md#mutation-preparation-visible-writes-and-faults)
and [Linked contract](22.%20SDK%20Linked%20and%20Cursor%20Specification.md#mutation-phases-and-lifetime);
per-instruction storage guarantees do not imply whole-method rollback.
@@ -0,0 +1,99 @@
# First-class functions and explicit value captures
Status: Normative. Owner: `compiler/pbs`.
Scope: First-Class Functions and Captures.
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.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## 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](20.%20Runtime%20Random%20Integration%20Specification.md) for opaque generator aliases in typed storage and captures.
## Parameterized contract integration
[Generic contracts](16.%20Generic%20Contracts%20Specification.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](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.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.
@@ -0,0 +1,85 @@
# PBS Generic Contracts
Status: Normative. Owner: `compiler/pbs`.
Scope: Generic Contracts.
This specification extends nominal contracts with explicit type parameters. Registry, PBX, instruction, ownership and resource contracts remain governed by the runtime provider. [Set, SDK Identity and hashing](23.%20SDK%20Set%20and%20Identity%20Specification.md) are consumers with their own public policy; the examples below illustrate generic language syntax, not the SDK Identity declaration.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Declaration and application
```pbs
declare contract Identity<T> {
fn hash(e: T) -> int;
fn equals(a: T, b: T) -> bool;
}
declare contract Converter<A, B> {
fn convert(value: A) -> B;
}
```
A parameterized declaration has one or more distinct ordered type parameters. Their scope is the contract's signatures, including nested type references. A type parameter is not the receiver. `Self` retains its existing meaning and validity restrictions.
Applications supply explicit ordered type arguments with exact arity: `Identity<int>` and `Converter<Enemy, str>`. The declaration's raw name, omitted arguments, `<>`, default arguments and blanket generic implementations are not value types or inference mechanisms. Nonparameterized contracts remain valid. [Generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md) add restricted owner-bound implementation families; they do not introduce blanket implementations for arbitrary owners.
The same compositional type grammar applies in annotations, nested applications, implementation targets and expression-form `as`. Existing contextual angle closers and expression comparisons retain their meanings. A barrel exports the declaration, for example `pub contract Identity<T>;`, preserving its origin and ordered parameters rather than exporting a particular application.
## Identity and compatibility
An application's identity is the defining nominal contract declaration plus its ordered canonical logical argument identities. Import aliases resolve before this identity is formed. If `Opponent` aliases the same `Enemy` declaration, `Identity<Opponent>` and `Identity<Enemy>` are identical. Equal names, method shapes or physical layouts do not merge different declarations or applications. Phantom arguments still distinguish applications.
Applications are invariant. A conversion between argument types does not establish a conversion between their contract applications. Existing explicit reference-view conversion can select another implementation actually supplied by the concrete receiver; it does not manufacture variance.
## Substitution and composition
Substitution traverses every type position in each signature, preserving parameter names, tuple labels, order and source provenance. It supports valid composition with existing builtins, nominal values, arrays, other applied contracts, Fn, optional and named tuples. Each resulting position remains subject to the existing type, return, optional/result and storage rules; substitution does not legalize an otherwise invalid position.
Normalize substituted signatures before deriving physical parameter/result groups. One logical parameter can contain several physical values. A shared physical carrier does not erase logical argument identity: distinct `Identity<array<X>>` applications remain nominally distinct even when their arrays share internal storage representation.
## Implementations and values
```pbs
declare service IntIdentity {}
implements Identity<int> for IntIdentity using strategy {
fn hash(e: int) -> int { return e; }
fn equals(a: int, b: int) -> bool { return a == b; }
}
fn equalSeven() -> bool {
let identity: Identity<int> = IntIdentity;
return identity.equals(7, 7);
}
```
Structs and services are the supported owners. An implementation belongs to the owner's declaring module and follows existing visibility rules. Implementations are complete and unique per `(owner, instantiated contract)`. One owner may implement several applications of the same contract. Implementation/callable identities include the full application, preventing collisions between those methods. Contract methods are not injected into the direct method namespace of their owner.
Named service singletons and constructed struct values supply strategies. Contextual assignments, arguments and returns, and explicit `value as Identity<int>`, select the concrete implementation. Conversion preserves the receiver and selected implementation without allocating an adapter wrapper or duplicating a singleton. Associated members such as `Enemy.identity` are not introduced.
## Recursion and bounded analysis
Register a nominal application anchor before expanding its signatures. A recurrence to an existing key forms a finite graph and is valid within existing resource limits. An application family that continually introduces new arguments, such as `Growing<T>` returning `Growing<array<T>>`, must be rejected with a clear expansion diagnostic.
Expansion, substitution and identity processing are bounded in work, storage and depth. Resource exhaustion and nonterminating specialization must not become hangs, host stack overflows, missing-method errors or ordinary argument-mismatch diagnostics.
## Execution and tooling
The frontend emits a concrete nominal Trait descriptor for each distinct required application, sharing the descriptor for equivalent uses across modules. Open type parameters do not reach executable signatures. Implementation functions receive the concrete owner first, followed by complete substituted argument/result groups.
Existing Registry/PBX and `REF_TO_TRAIT`/`CALL_TRAIT` mechanisms execute these records. Preserve typed absence, valid ImplementationId zero, receiver identity, rooting, GC, native ownership and quotas. Generic calls do not introduce a Dynamic argument ABI or boxing merely because an argument was a type parameter. Existing storage-specific packing remains governed by that storage's contract.
Navigation reaches generic declarations, parameters and argument declarations. Hover, completion and signature help show instantiated signatures with canonical source names. Arity, unresolved parameters, invalid applications/coercions, incomplete or duplicate implementations and expansion failures have localized diagnostics. Compilation and editor projections share the same type resolution.
## Conformance
Compile real PBS through typed IR and production PBX into the production loader, verifier and VM. Cover multiple parameters/applications, several applications on one owner, imports/aliases/reexports, nominal origin, phantom arguments, composed and multi-slot payloads, finite recursion, expanding recursion rejection, service/struct views, typed absence, implementation zero, GC and resource refusal.
A specialized contract and a manually written concrete equivalent must exhibit the same behavior without generic-only adaptation/boxing. Identical image bytes and a performance improvement are not required. Installed knowledge packages this specification and a runnable source example. Generic structs/functions are defined by the separate [owner specification](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md), sharing canonical identities, provenance and bounded expansion with contracts. Bounds, variance, inheritance/default methods, generic reflection, runtime instantiation and collection algorithms remain outside these extensions.
@@ -0,0 +1,284 @@
# Concrete Generic Structs and Free Functions
Status: Normative. Owner: `compiler/pbs`.
Scope: Generic Structs and Free Functions.
This specification adds parameterized state and executable
bodies to the nominal, concrete application model of generic contracts. It applies
uniformly to SDK modules and program sources. Registry, PBX, VM admission, resource
limits and instruction semantics remain governed by the existing provider contracts.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Declarations and identity
Structs and module-level named free functions may declare one or more distinct,
ordered type parameters. Applications have exact arity. Type parameters have
identity by declaration or binder and ordinal position; their spelling is lexical
presentation, not a globally substitutable symbol.
```pbs
declare struct Box<T>(value: T) {
fn get() -> T { return this.value; }
fn set(value: T) { this.value = value; }
}
declare struct Pair<K, V>(key: K, value: V);
fn identity<T>(value: T) -> T { return value; }
```
An application is identified by its nominal source declaration and ordered,
canonical logical arguments after alias resolution. Aliases and reexports of the
same declaration share applications. Homonymous declarations from different
origins, phantom arguments and logically different types remain distinct even
when fields, signatures or physical carriers coincide. Applications are invariant;
numeric or reference conversions between arguments do not convert their containers.
Struct assignment shares the existing object reference and does not deep-copy it.
The raw name of a parameterized struct is not a closed type, including inside its
own declaration. Open parameters exist only in the authorized declaration scopes
and must not reach executable metadata.
## Construction and expected types
```pbs
let a = new Box<int>(42);
let b: Box<int> = new Box<>(42);
let c: Box<int> = new Box(42);
```
Explicit construction supplies its application. Diamond and omitted arguments
require a sufficient, compatible expected application at the existing contextual
Array positions: annotated bindings, assignments, resolved callable parameters,
returns and value expressions with an expected type. Values do not infer type
arguments: `let d = new Box(42);` is invalid. There is no partial inference, default
argument or additional overload search to discover generic arguments.
Named constructors use the applied owner, for example `new Box<int>.make(42)`.
Substitution preserves existing constructor selection, evaluation order, definite
field initialization, visibility, `this` and completion rules. A parameter has no
implicit constructor or universal default; `new T()` is invalid.
Every completing constructor path MUST explicitly assign every field, in ordinary
and generic structs, including fields of opaque builtin type Random. Assignment
in only one conditional branch or in a loop that may execute zero times is
insufficient. Runtime reference defaults are provider behavior and do not exempt
PBS constructors from this rule. Controlled null-provider fixtures are described
in [Runtime Random integration](20.%20Runtime%20Random%20Integration%20Specification.md).
## Composition and symbolic capabilities
Arguments and substituted uses compose with valid builtins, nominal values,
applied structs/contracts, Array, Fn, optional, tuples and existing return/result
positions. Each position retains its existing restrictions. Normalize logical
types before deriving physical groups, preserving labels, names, order and every
slot of a multi-slot value.
Array's element restriction is not a global generic restriction. A T field can
hold `Box<optional int>`; a field declared `array<T>` makes the application with
T=optional int invalid. Revalidate all concrete positions after substitution.
Templates are validated symbolically before relying on concrete arguments. An
unconstrained T can be stored, assigned compatibly, passed and returned. It gains
no arithmetic, comparison, members or construction from a particular application.
`value + value` on T is invalid even when the only requested application uses int.
Known operations of declared containers remain available; indexing array<T>, for
example, produces optional T. Additional capabilities require explicit composition:
```pbs
declare struct ComparedBox<T>(value: T, identity: Identity<T>) {
fn matches(other: T) -> bool {
return this.identity.equals(this.value, other);
}
}
```
This does not introduce bounds, implicit equality/hash or opportunistic member
lookup on an argument.
## Complete substitution, validation and Self
Substitute fields, constructor/method signatures and complete bodies, including
local annotations, nested applications and constructions, references/calls,
lambdas and capture environments. Rewriting signatures alone is insufficient.
Ordinary methods use their owner's type parameters; they do not declare another
generic parameter list.
Self denotes the complete applied owner in its existing valid locations. It means
Box<int> inside that application and Box<Enemy> inside the other. Header fields
must still spell recursive types explicitly, such as `optional Node<T>`; the
feature does not expand Self's valid locations. Existing privacy, pub/pub mut,
receiver and direct-versus-contract method rules remain unchanged.
For every required owner application, validate its fields, constructors and all
methods, including uncalled methods. Dead-code elimination must not change source
acceptance. Method/constructor identities include their source declaration,
applied owner and existing signature identity. Distinct overloads that collapse
after substitution reject the application and identify both declarations. In
particular, set(T) and set(int) collide at T=int without an implicit preference.
## Owner-bound implementations and coherence
```pbs
declare contract Reader<T> { fn read() -> T; }
implements<T> Reader<T> for Box<T> using box {
fn read() -> T { return box.get(); }
}
```
A parameterized implementation's owner must directly apply a declared generic
struct. Every owner argument is a distinct binder parameter, and all binder
parameters are bound through the owner. Binder names need not match the struct's
parameter names. Arbitrary owners, unbound parameters, narrower patterns such as
Box<array<T>>, and repeated arguments restricting the family are invalid.
The rule belongs to the owner's declaration module. Its target resolves to a
contract and may compose the owner-bound parameters under existing type rules.
Implementations are complete with exact substituted signatures. Emitted owners,
targets and methods are concrete. Contract methods are not injected into the
owner's direct namespace. Views preserve receiver, implementation and identity
without a wrapper required by parameterization.
Uniqueness is by concrete (owner, contract) pair. Two declarations overlap if an
admissible application could produce the same pair. Compare canonical nominal
origins and arguments with symbolically owner-bound parameters. Detect
generic/generic, generic/closed and closed/closed collisions before the conflicting
application is used. Different contract applications for an owner remain valid
when their pairs cannot coincide. Bounded analysis must not enumerate only used
applications, choose file/import order, prefer closed rules or silently succeed
after exhausting its budget.
## Free functions, overloads and Fn
References and calls provide explicit type arguments, such as identity<int>(42).
An argument may mention a parameter in an enclosing template but must become
concrete before emission. There is no value, result or expected-Fn inference,
function diamond or default generic argument. `identity<>` and a polymorphic Fn
value for open `identity` are invalid.
An applied function's identity includes its source declaration and ordered logical
arguments, including phantom arguments. Equivalent uses share the application;
different declarations remain different targets despite identical concrete
signatures. Symbolic validation, definition scope, complete body substitution,
normalization and bounded expansion apply to required function applications too.
`f<int>` considers generic free functions with matching type arity. A reference
or call without type arguments does not select a generic template. Ordinary
overloads remain subject to existing rules. After explicit binding, use existing
concrete signature resolution. Consistent renaming does not create overloads:
f<T>(value:T) and f<U>(value:U) are duplicates when otherwise signature-equivalent.
Substituted collisions in the filtered generic candidate set are errors.
```pbs
let transform: Fn(int) -> int = identity<int>;
let answer = transform(42);
```
Closed references use the existing Closure mechanism with an empty environment.
Fn stays structural by logical parameters/results, excluding target identity,
names and captures. Distinct targets may share a compatible Fn descriptor.
Lambdas in specialized bodies preserve explicit capture semantics and complete
groups. Bare method extraction remains invalid. Calls preserve canonical apply,
existing named/positional forms, order and single evaluation.
## Definition scope, imports and barrels
Each declaration/binder has its own substitution environment. Names in a template
body bind in its definition scope; type argument names bind at the use. Caller
and callee parameters with the same spelling must not capture one another.
Instantiation does not resolve private helpers in the caller or export them.
```pbs
pub struct Box<T>;
pub struct Pair<K, V>;
pub fn identity<T>(value: T) -> T;
```
Barrels export the parameterized declaration, ordered parameters and signature,
not an enumeration of closed instances. Preserve the original definition through
imports/aliases/reexports and make the necessary body available to the compiler
under existing visibility rules. This does not add an open-template PBX format.
The application grammar extends the existing ordered type argument syntax to
struct/free-function declarations, barrels, owner-bound implements and named
function reference expressions. Calls continue to use ordinary parentheses/apply.
Nested applications and adjacent closers preserve spans. Complete type-argument
references must remain distinct from ordinary <, > and >= comparisons without
changing their meanings or adding shifts. Malformed source retains localized
diagnostics and recovery. Fields, ordinary Fn values and methods gain no generic
parameter list from this grammar.
## Expansion, diagnostics and concrete execution
Share logical identity, substitution environments, provenance and bounded
expansion infrastructure across PBS structs, functions and contracts. Keep each
category's layout/callable rules explicit and keep PBS rules in the frontend.
Register nominal and callable anchors before expanding dependencies. Revisiting
the same application forms a finite graph, including cross-category field/body
dependencies. Families requiring indefinitely new applications are diagnosed,
including growth through uncalled methods of a used owner.
Analysis, normalization, substitution, coherence and materialization are bounded
in depth, work and storage. Exhaustion must not become a hang, host stack overflow,
misleading missing method or ordinary argument mismatch. Frontend budgets do not
increase provider limits.
Errors preserve the original declaration and requesting use, with a short chain
such as `main -> wrap<Enemy> -> Box<Enemy>`. Cover unbound/duplicate parameters,
arity, raw/inferred application, invalid positions/capabilities, incomplete
construction, overload collisions, invalid implementation owners/rules, overlap
and expansion. Generated names and Java stacks do not replace source explanation.
Navigation, references/rename, hover, completion, signature help, symbols,
formatting and semantic tokens share compilation resolution/substitution. Distinguish
symbolic parameter, concrete argument and generic origin, including imported code.
Emit only concrete Struct/Trait/Fn descriptors, callables, fields, signatures,
capture environments and implementation functions. Preserve logical identity
independently of storage width. Existing Struct/Array/Trait/Fn, direct calls,
REF_TO_TRAIT/CALL_TRAIT and Closure execute the result. Preserve receiver,
singletons where applicable, typed absence, valid ImplementationId zero, rooting,
GC, ownership, faults, evaluation and quotas. Genericity must not impose Dynamic,
reboxing or an adapter wrapper as its argument ABI; existing storage packing
retains its own contract. No new opcode, PBX category or runtime instantiation
engine is required. A provider-contract gap requires explicit decision revision.
## Qualification and boundaries
Conformance compiles real source through typed IR and production PBX into the
production loader, verifier and VM. Cover multiple arguments/applications, origin,
aliases/reexports/phantom identity, constructors/Self/all methods, composition and
multi-slot groups, free functions/apply/Fn, captures, finite/expanding recursion,
coherence, GC, ownership and quota refusal. Include negative cases for symbolic
operations, unused invalid methods, inferred applications, alpha-equivalent
duplicates and provenance diagnostics.
A complete multi-module fixture must combine Box<T>, Reader<T>, owner-bound
implements<T>, read<T>, read<int> as Fn and imports/aliases, returning 42. Compare
specialized structs/functions with handwritten concrete equivalents for behavior,
identity/lifetime and absence of adaptation imposed solely by T. Record provider
revision/configuration, complete fixture counts, metadata counts and artifact
sizes. Identical PBX bytes and a performance improvement are not required.
Ship and verify specifications and executable examples in installed knowledge.
Regress Array, ordinary/applied structs/contracts, Self, constructors, Fn/captures
and lifecycle. No mandatory requirement is deferred to a collection implementation.
Independent generic methods, generic contract methods/lambdas, polymorphic Fn,
function type inference, bounds, variance, defaults, user specialization and
blanket/narrower implementation patterns are outside this feature. Lifecycle
signatures remain concrete. Collection APIs/algorithms, default equality/hash,
iteration protocols and List logical bounds/slot transfer are separate decisions.
## Related specifications
- [Generic contracts](16.%20Generic%20Contracts%20Specification.md).
- [Typed arrays and optional execution](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md).
- [First-class functions and captures](15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
- [Concrete Registry and PBX handoff](../../compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md).
- [SDK Map and Keyval](24.%20SDK%20Map%20and%20Keyval%20Specification.md), a two-parameter source consumer
preserving separate key/value policies and complete optional/grouped fields.
@@ -0,0 +1,147 @@
# PBS input and existing value runtime alignment
Status: Normative. Owner: `compiler/pbs`.
Scope: Input and Existing Type Runtime Alignment.
Common ABI authority:
[typed Registry/PBX](../../compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md) and
[runtime catalogs](../../compiler/24.%20Runtime%20Catalog%20Support%20Specification.md).
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Source types and exact carriers
| PBS source | Runtime identity | Ordered slots |
| --- | --- | --- |
| `int` | Int32 | Int32 |
| `long` | Int64 | Int64 |
| `float` | Float | Float (binary64) |
| `bool` | Bool | Bool |
| `str` | String | String |
| builtin `color` shell | color | Int64 constrained to RGBA8888 |
| builtin `vec2` shell | vec2 | Float x, Float y |
| builtin `pixel` shell | pixel | Int64 x, Int64 y, Int64 color |
The canonical builtin metadata determines a shell's identity; its source name
is not an ABI lookup rule. Equal widths do not permit substitution. Function
metadata MUST declare ordered parameter and result identities. Slot counts are
checked caches derived from those identities. Calls, locals and returns MUST
preserve entire value groups. A vec2 is one logical value with two slots;
a named output tuple is a fixed sequence of logical results, not a heap object.
`int` and `long` are distinct. Integer literals default to `int`; explicit
`long` contexts (annotations, parameters and results) validate literals in the
Int64 range and materialize them with that carrier. Out-of-range literals MUST
be diagnosed, never replaced by zero. A typed variable does not change type
because it appears in another expected context. Mixed int/long operations
require an explicit conversion. Existing `as` syntax expresses conversion:
```pbs
let frames: long = 2147483648;
let offset: int = 10;
let wide = offset as long;
let narrow = frames as int;
```
The final conversion faults if its value is outside Int32 range. Numeric
conversions use published math/mathf conversion intrinsics, without adding
math service facades. Int32/Int64 arithmetic preserves runtime wrapping;
Float overflow and range-invalid conversions preserve runtime faults.
Defaults are owned by the runtime storage contract: numeric zero, Float +0,
Bool false, nullable String null, transparent color, zero vec2 and zero pixel.
This does not introduce implicit source-variable initialization: VM locals
start null and PBS definite-assignment rules still apply. NaN/infinity are not
valid guest numeric defaults.
## Public input API
Import `Pad`, `Button` and `Touch` from `@sdk:input`. Button is a closed nominal
PBS enum with cases Up, Down, Left, Right, A, B, X, Y, L, R, Start and Select.
It identifies a button; it does not contain input state or perform a query.
Locals and typed function parameters may carry Button values, including values
selected during execution. Strings, integer indices and unrelated enums are
not valid Button arguments.
| Public operation | Result |
| --- | --- |
| `Pad.pressed(button: Button)` | bool |
| `Pad.released(button: Button)` | bool |
| `Pad.down(button: Button)` | bool |
| `Pad.hold(button: Button)` | long, held logical frames |
| `Touch.pressed()`, `Touch.released()`, `Touch.down()` | bool |
| `Touch.hold()` | long, held logical frames |
| `Touch.x()`, `Touch.y()` | long |
```pbs
import { Pad, Button, Touch } from @sdk:input;
fn jump(button: Button) -> bool {
return Pad.pressed(button);
}
fn held() -> long {
let jump_button = Button.A;
return Pad.hold(jump_button);
}
```
Pad dispatches to `LowPad.<button>_<query>()`, for example
`LowPad.a_pressed()`. All 48 combinations map to the published direct endpoint.
Each call MUST evaluate its selector once and execute exactly one chosen
query. It MUST NOT read unselected buttons, speculate input faults or collect
all button states. Constant specialization is optional; dynamic dispatch must
work without optimization.
All 54 VM queries take zero arguments and no receiver. Button never crosses
the intrinsic boundary as a selector. Touch x/y use current IDs 0x2134/0x2135
and Int64 results. No new device, button-state object, snapshot or multi-pad
contract is introduced. Known input without an available platform faults with
TRAP_UNAVAILABLE; it never fabricates false or zero. Unknown and retired IDs
are invalid even in unreachable code.
## Migration and diagnostics
The old Input root and intermediate InputPad/InputTouch/InputButton objects
are removed. Replace `Input.pad().a().pressed()` with
`Pad.pressed(Button.A)` and `Input.touch().x()` with `Touch.x()`.
`let button = Input.pad().a();` is invalid; `let button = Button.A;` is valid.
Migration diagnostics must point to the replacement surface. Hover, completion,
exports and examples must advertise the same API and exact return types.
When a consumer requires int coordinates, explicitly narrow a Touch result
with `as int`; do not silently change the query's ABI.
## Lowering and observable order
PBS owns source enum dispatch and typed metadata. Common code owns catalog
resolution, PBX validation and emission. The frontend MUST NOT maintain a
second intrinsic or constant catalog. SDK executable methods admit the existing
switch expression with value arms, apply and explicit numeric conversions
needed by this facade; other unsupported SDK constructs remain diagnosed.
For named application such as `f apply (y: effect_y(), x: effect_x())`, evaluate
Y then X exactly once, store complete groups in temporary locals, and reload
in x,y parameter order. Reordering expressions instead of values is invalid.
Builtin constants are groups resolved by the shared constant catalog.
`vec2.zero` materializes two Float slots; no intrinsic endpoint is invented.
Colors may use a published constant or an independently published intrinsic.
Function metadata must cover SDK wrappers such as Gfx.clear. Validation must
not infer missing identities from widths or omit the full installed example.
Preserve the existing lifecycle assembly and physical boot FunctionId zero.
## Conformance
The PBS source-to-production-PBX corpus and production runtime harness must
cover all 54 input queries with controlled input and exactly-one-query checks,
known-unavailable behavior, typed selectors, int/long boundaries and explicit
conversions, Float/String/Bool, color/vec2/pixel groups, multiple returns and
named-argument effects. Keep common registry wrong-carrier, retired-ID and stale
signature tests active. Record runtime hash, Studio revision, platform and
configuration. A catalog-only pass does not replace successful PBS execution
or `:prometeu-app:installedKnowledgeTest`.
@@ -0,0 +1,129 @@
# Service constants and runtime math
Status: Normative. Owner: `compiler/pbs`.
Scope: Service Constants and Runtime Math.
Common catalog authority: compiler/general. Numeric behavior,
exact identities, faults and virtual costs remain owned by the runtime.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Services are the public namespaces
A service groups methods and immutable constants. The service barrel entry exports
both; constants are not independently exported as top-level symbols. This applies
to project code and SDK interfaces. Import aliases preserve the service identity.
```pbs
// @app:settings/main.pbs; mod.barrel contains: pub service Settings;
declare service Settings {
declare const base: int = 40;
declare const answer: int = base + 2;
fn read() -> int { return answer; }
}
```
Consumers can import `Settings` and read `Settings.answer`. Constants use the same
explicit type and constant-expression rules as top-level constants. Constant
initializers cannot invoke functions. Qualified dependencies are permitted;
unqualified names inside a constant initializer resolve in its owning service
before the top-level constant scope. Duplicate constants, a constant sharing a
method name, unresolved references, type mismatches and dependency cycles are
compile-time errors. Assignments to constants are invalid.
Reading `Service.constant` materializes its value without creating a singleton or
calling a getter. Ordinary methods retain existing service semantics. Constant
members are included in completion, hover, definition and document symbols.
## SDK math services
```pbs
import { math } from @sdk:math;
import { mathf as numbers } from @sdk:mathf;
fn example(counter: long, angle: float) -> float {
let bounded = math.clamp(counter, 0 as long, 100 as long);
return math.to_float(bounded) + numbers.sin(angle) + numbers.pi;
}
```
`math` supplies `min`, `max`, `clamp` and `abs`, each with exact `int` and `long`
overloads. `mathf` supplies `min`, `max`, `clamp`, `abs`, `floor`, `ceil`, `trunc`,
`round`, `sqrt`, `sin`, `cos` and `atan2`, all with `float` arguments and results.
`atan2` takes `(y, x)`; angles are radians. `float` is the runtime's finite binary64.
The six conversions are:
| Source call | Argument | Result |
| --- | --- | --- |
| `math.to_i64` | int | long |
| `math.to_i32` | long | int |
| `math.to_float` | int | float |
| `math.to_float` | long | float |
| `mathf.to_i32` | float | int |
| `mathf.to_i64` | float | long |
These are 26 exact intrinsic signatures in total. There are no identity
conversions. A mixed `int`/`long` call to `math.min` is invalid; the diagnostic
requires explicit conversion. Existing contextual integer literal rules do not
authorize implicit conversion of an already typed argument. Arithmetic opcode
promotion rules are unchanged.
## Binding and materialization
SDK service method signatures may carry `[IntrinsicCall(name = "...", version = 1)]`
and terminate with `;`. They have no PBS body or implicit numeric receiver in their
runtime signature. This reserved declaration form is restricted to SDK interfaces.
The generated callable loads its ordered arguments and invokes the exact common
catalog identity. No frontend numeric ID/cost map or host math implementation is
introduced. Normal compilation uses local versioned resources, not a runtime checkout.
SDK service constants may use `BuiltinConst` and omit their initializer:
```pbs
declare service mathf {
[BuiltinConst(target = "mathf", name = "pi", version = 1)]
declare const pi: float;
}
```
`mathf.pi` and `mathf.tau` MUST materialize `IRVMBuiltinConstantDefinition` values:
`0x400921FB54442D18` and `0x401921FB54442D18`. They are ordinary constant loads,
never synthetic intrinsic calls or host-calculated values. A constant expression
cannot replace a mathematical call: executable calls with literal arguments MUST
remain executable, including when their result is discarded or optimization runs.
## Numeric conformance
The runtime contract specifies signed zeros, subnormals, finite overflow, checked
conversions and ties-to-even rounding. For example, `sqrt(-0)` preserves -0,
`abs(-0)` produces +0, `round(2.5)` produces 2 and `round(3.5)` produces 4. Negative
nonzero sqrt and inverted clamp limits trap NUMERIC_DOMAIN. Integer abs(MIN) and
out-of-range conversions trap NUMERIC_RANGE. The frontend MUST preserve these
outcomes, argument order and virtual cycle accounting.
Integration evidence MUST begin with PBS source and end at the production VM.
The checked-in independent corpus combines provider MPFR-verified rows with exact
published contract examples. Tests require all 26 signatures, constants, mixed-type
rejections, explicit conversions, signed zeros, subnormals, extrema, range/domain
faults and atan2 axes. Both optimized and unoptimized emission are exercised.
The harness compares exact result bits and trap codes, and checks each executed
instruction's charge against the provider opcode contract and each numeric call
against its independent fixture cost. A full-budget run must charge their sum.
Constant-only probes additionally require exactly a load and root return cost.
Local qualification requires macOS/arm64 dev and release with runtime revision,
configuration and catalog/oracle hashes recorded. macOS/x86_64 and Linux/x86_64
remain separately pending; local results and cross-compilation do not qualify them.
## References
- [Common runtime catalog support](../../compiler/24.%20Runtime%20Catalog%20Support%20Specification.md)
- [Runtime numeric contract](../../../../../runtime/docs/specs/runtime/02d-gameplay-math-and-numeric-semantics.md)
- [Production conformance harness](../../../../tools/pbx-conformance/README.md)
@@ -136,7 +136,7 @@ Every accepted change MUST update, when relevant:
- diagnostics documentation,
- conformance tests,
- compatibility matrix/changelog.
- For executable FE/BE conformance-relevant code changes, the backend conformance matrix (`docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`) MUST be updated and pass hard-gate policy checks.
- For executable FE/BE conformance-relevant code changes, the backend conformance matrix (`docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`) MUST be updated and pass hard-gate policy checks.
## 12. Conflict Resolution
@@ -0,0 +1,82 @@
# PBS Runtime Random Integration
Status: Normative. Owner: `compiler/pbs`.
Scope: Runtime Random Integration.
This specification defines the PBS projection of runtime Random v1. The runtime owns the algorithm, heap identity, validation, atomicity, resource accounting and virtual cycles. The common catalog is the binding authority; the frontend does not implement a generator.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Source surface
```pbs
import { Random, random } from @sdk:random;
fn draw() -> long {
let seed: long = 42;
let generator: Random = random.new(seed);
let alias = generator;
random.next(generator);
return random.range(alias, 0 as long, 100 as long);
}
```
Game SDK 1 exports the opaque builtin `Random` and service namespace `random` from `@sdk:random`. Both may be imported with aliases. The exact v1 signatures are:
| Operation | PBS signature | Runtime result/cost |
| --- | --- | --- |
| `random.new` | `(seed: long) -> Random` | New independent generator; 32 cycles |
| `random.next` | `(rng: Random) -> long` | Next word reinterpreted as signed Int64; 8 cycles |
| `random.nextf` | `(rng: Random) -> float` | Exact binary64 grid value in `[0,1)`; 12 cycles |
| `random.range` | `(rng: Random, min: long, max: long) -> long` | Integer in `[min,max)`; `4 + 8*N` cycles |
`new` is accepted as a callable declaration/member name; the `new Type(...)` allocation expression remains distinct. `new Random()` is invalid. The builtin has no public fields, source constructor, implicit Struct/Trait adaptation, receiver defaults or hidden seed. Only `random.new` allocates a generator. The API does not expose helpers, clone, reseed, split, snapshot or a global generator. Seeds are Int64 bit patterns: zero, negatives and extrema are valid. An existing `int` binding requires an explicit conversion to `long`; contextual long literals remain governed by the numeric specification.
## Identity and storage
Random is runtime BuiltinId `0x0016`, with one opaque nullable reference slot. Program TypeIds are local identities, not BuiltinIds. The frontend MUST register this exact builtin and MUST NOT model its payload as a source Struct or emit `NEW` to construct it.
Assignment, parameter passing, returns and capture copy a reference to the same state. Calling `random.new` twice with the same seed creates equal initial sequences that evolve independently. Copying an existing handle does not fork the sequence. All output operations consume the same stream, including a unit-width range and calls whose results are discarded.
The reference MUST retain identity and ownership in locals, globals, fields, arrays, function parameters/results and captures. Captures use the existing snapshot rules: the copied reference continues to identify the shared generator. Reachable references MUST remain valid across runtime collection.
PBS does not expose a `null` literal or a public `Dynamic` type. Runtime reference defaults remain null at the provider boundary. PBS constructors MUST explicitly initialize every field on every completing path, including Random fields; an empty constructor cannot expose that runtime default. Existing global-initializer restrictions remain unchanged; an unsupported arbitrary call in a global initializer does not become legal because it returns Random.
Typed arrays use their existing private `Array<Dynamic>` representation. Packing Random MUST preserve its exact runtime TypeId and direct reference without cloning state or adding a multi-slot box. A present typed-null Random element MUST remain distinguishable from an empty array position: presence is checked by tag before exact extraction. Consuming that null generator raises the runtime null-reference fault rather than treating the element as absent.
## Evaluation, faults and billing
All four operations are deterministic and mutate guest state; only `new` may allocate. Determinism means reproducibility from the same state and ordered inputs. The compiler MUST NOT execute, fold, eliminate or reorder these calls based on literals, seeds or the deterministic flag. Discarding a result MUST retain the call and its mutation.
Arguments MUST be evaluated in source order. Named application may rearrange already evaluated carriers into signature order but MUST NOT change the order of their effects.
`range` requires `min < max`, with exact long arguments and no swapping, clamping, absolute-value or Float conversion. The runtime charges base 4 before checks and 8 for each attempted draw. Acceptance on attempt 64 succeeds; 64 rejections raise the rejection-limit trap at 516 intrinsic cycles. A unit interval consumes a word and costs 12. Argument evaluation, calls, storage and other bytecode instructions have their own costs.
The runtime contract governs fault precedence and atomicity: wrong carriers, null/invalid references, invalid limits and resource refusals retain the applicable identities. Failed operations do not publish partial state or handles, but executed cycles are not refunded. Compiler and SDK MUST preserve these semantics without a second validator, generator or cycle emulator in production.
## Conformance
The source corpus MUST run the production PBS → common IR → PBX → runtime path with optimization on and off, and repeat equal ordered inputs to compare exact bits, faults and cycles. Required coverage includes:
- all four signatures, real SDK imports/aliases and incompatible-source diagnostics;
- provider vectors for seeds `0`, `1`, `42`, `-1`, Int64 MIN/MAX, integer and Float draws;
- aliases, independent equal-seed objects, mixed outputs, discarded draws and positional/named argument effects;
- locals/globals/fields/arrays/parameters/results/captures, private Dynamic and retained roots across collection;
- unit/extreme intervals, excluded upper bound, invalid bounds and real rejection followed by acceptance;
- exact intrinsic charges and replay/optimizer agreement.
Null receivers and present typed-null Array elements MUST be covered by separately identified controlled provider fixtures. Such fixtures may suppress a fully initialized field store after compilation to exercise provider reference defaults; they MUST NOT depend on accepting incomplete source constructors. Rare synthetic rejection paths, cap rollback, malformed carriers and native reference provenance remain separately identified provider evidence. Tests MUST reuse the provider's controlled fixtures without adding injection or alternate algorithms to the public SDK. Record runtime revision, platform, profiles, toolchain, features and source/catalog/oracle/lockfile fingerprints. Local results do not qualify unexecuted platforms or the reference game.
## References
- [Typed arrays and optional execution](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md).
- [First-class functions and captures](15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
- [Runtime math and exact numeric carriers](19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md).
- [Runtime Random v1](../../../../../runtime/docs/specs/runtime/02e-vm-owned-random-core.md).
- [Provider handoff](../../../../../runtime/docs/vm-arch/random-producer-handoff.md).
@@ -0,0 +1,213 @@
# SDK List and snapshot Cursor
Status: Normative. Owner: `compiler/pbs`.
Scope: SDK List and Cursor.
List and Cursor algorithms belong to the executable PBS
SDK. Typed storage, complete stored-group transfers and terminal failure are
language-neutral compiler/runtime mechanisms. Logical checks are SDK algorithms. This contract builds on
[arrays and optional](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md),
[generic structs](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md) and
[generic contracts](16.%20Generic%20Contracts%20Specification.md).
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Type, identity and construction
The SDK exports the ordinary generic struct `list<T>` and contract `Cursor<T>`
from its collections module. Applications are invariant. A directly optional
element, including through grouping, is invalid; `optional (list<T>)` is valid.
Nested valid arrays, structs, contracts, functions and value groups keep their
normal types and identities. An unrelated user declaration named list does not
acquire SDK behavior.
`new list<T>()` creates size zero and capacity 16. `new list<T>(capacity)` creates
size zero with exactly that capacity, including zero. Contextual `new list()`
and `new list(capacity)` require an expected concrete List type. Constructor
values do not infer T. Only the backing array is allocated; elements are absent.
List has stable reference identity. Assignment and parameter passing share that
identity; aliases observe mutations even when growth replaces its private backing
array. Storage, internal nodes and private compiler bindings are inaccessible to
clients. No public Dynamic or universal element type is introduced.
## Logical positions and operations
Every observable List satisfies `0 <= size <= capacity`. Size includes holes.
Capacity is physical storage and never makes additional indices accessible.
Zero and false are present values, distinct from holes.
| Operation | Result | Behavior |
| --- | --- | --- |
| `size()` | long | Logical positions, including holes |
| `capacity()` | long | Physical backing length |
| `xs[i]` | optional T | Present value or hole at `0 <= i < size` |
| `xs[i] = value` | unit | Replace one valid position without extending size |
| `add(value)` | unit | Append at size; do not fill earlier holes |
| `insert(i, value)` | unit | Insert at `0 <= i <= size`; shift slots and holes right |
| `clearAt(i)` | unit | Clear a valid position without shifting or changing size |
| `removeAt(i)` | optional T | Return old content, shift left, clear old tail, decrement size |
| `clear()` | unit | Clear all contents and size, preserve capacity |
| `resize(n)` | unit | Grow with holes or clear discarded suffix; set logical size |
| `reserve(n)` | unit | Grow exactly to n only when n exceeds capacity |
| `trim()` | unit | Set capacity exactly to size, including zero |
| `cursor()` | Cursor<T> | Complete immediate snapshot of present occurrences |
Removing a hole still removes its position and decrements size. Shrink, removal
and clear discard all hidden suffix references: regrowing must not resurrect old
values. Physical shrinking occurs only through trim. `resize(0)` preserves capacity.
Receiver and arguments are evaluated once in source order. Indices, lengths and
capacities accept int and long with localized lossless promotion; this does not
add general numeric conversion. No long value may be truncated.
SDK checks reject invalid logical indices, negative lengths/capacities and requests
above Array's u32 structural maximum before mutation with TRAP_EXPLICIT and a
source location. This includes indices inside physical capacity. Physical Array
instructions that actually execute retain their own fault/resource classification.
Failures are never translated into none. Growth arithmetic must not overflow or
truncate; clamping applies only to a valid requested length.
## Capacity policy
When required size r exceeds capacity c, automatic growth is:
```text
candidate = max(r, c + max(1, ceil(c / 2)))
new capacity = min(Array structural maximum, candidate)
```
Calculate without overflow. Clamp only if r itself fits the structural maximum;
otherwise raise the applicable provider failure. Explicit reserve uses exactly n,
never shrinks and preserves size. Trim uses exactly size. Old and candidate arrays
may coexist; neither discarded references nor replaced storage promise immediate
GC or immediate quota recovery.
## Mutation preparation, visible writes and faults
Transfer whole stored groups, presence tags and reference identities; do not
unpack and rebox all existing elements during shifting. Prepare validation,
next size, inserted values, candidates and optional return carriers before the
first visible write. This preparation does not prove all later instructions
infallible. Values/receiver/argument effects already evaluated are not rolled back.
With growth, construct a private candidate and copy prefix/suffix directly into
their final positions; store the new value privately, then install storage and
length in sequence. Without growth, prepare the inserted stored group in a private
one-slot array, shift with overlap-safe ARRAY_COPY, copy that complete prepared
slot, then update length. Both copies retain scratch, validation and charging,
including empty copies. This one-slot preparation is charged allocation, not a
promise of allocation-free insertion or whole-array reconstruction.
Removal prepares its optional result, shifts the suffix, clears the old tail and
updates length. Clear and in-capacity resize clear the selected interval in index
order before assigning length. Growing resize prepares/copies a private candidate
before installing storage and length. Reserve/trim prepare/copy candidates and
replace storage only. Indexed replacement/clearAt alter a single checked position.
| Outcome | Guarantee |
| --- | --- |
| Logical rejection or preparation refusal before the first visible write | Preserve previous size, backing, capacity, slots and collection roots. Unpublished candidates obey normal ownership/quotas; immediate quota recovery is not promised. |
| Successful return | All collection invariants, cleanup, groups, identity and snapshot contracts hold. |
| Internal/resource fault after the first visible write | Propagate the fault; earlier writes can remain and collection invariants can be incomplete. No rollback, safe reuse, retry or automatic recovery is promised. |
The last row explicitly replaces the former whole-mutation refusal guarantee.
Individual instruction failure still preserves its own entry operands/storage.
No catch, poison flag or recovery API is introduced. The SDK inserts no user
callbacks or explicit suspension during mutation updates. BudgetExhausted and
pauses are resumable instruction boundaries, not faults or rollback. The host or
debugger may observe intermediate state; a method is not an atomic region.
## Cursor protocol
```pbs
declare contract Cursor<T> {
fn hasNext() -> bool;
fn next();
fn current() -> optional T;
}
```
The shared SDK implementation captures one private immutable singly linked,
non-circular node per present occurrence. It uses no snapshot array and retains
no source-slot or editable source-node association. List capture scans logical
positions and preserves increasing index order, duplicates and complete values.
Capture finishes before returning; failure exposes no partial Cursor.
A nonempty Cursor starts on its first node. `hasNext()` tests for a successor.
`next()` advances only when a successor exists; otherwise it does nothing.
`current()` reports the current node without advancing. Only a snapshot born
empty reports none. Repeated calls never advance beyond the last node.
| Snapshot and position | hasNext() | current() |
| --- | --- | --- |
| Empty, initially or after any next | false | none |
| [A], initially or after any next | false | some(A) |
| [A, B], initially | true | some(A) |
| [A, B], after one or any further next | false | some(B) |
Consume the current value before deciding whether to advance:
```pbs
while true {
if let value = cursor.current() {
// Consume value.
} else {
break;
}
if cursor.hasNext() {
cursor.next();
} else {
break;
}
}
```
A hasNext-only loop skips the last element. Waiting for current to become none
does not terminate a nonempty snapshot. There is no index, reset, removal, clone
or new for-in protocol. Another complete traversal creates another snapshot.
Captured object references preserve identity and observe subsequent field mutation.
Later List insertions, replacements, removals, clear, resize and backing changes
do not alter the captured sequence. Snapshot links and captured values are not
rewritten. The Cursor retains only its current node and suffix, allowing consumed
prefixes to become unreachable. It keeps the final node/value while reachable.
Other owners remain independent; reclamation happens through normal GC.
The outer optional describes node existence. A future producer with optional T
must distinguish `some(none)` from an empty Cursor. Type/resource faults remain
faults. List itself rejects directly optional elements.
## Reuse, costs and conformance
The shared implementation is independent of List representation.
[Stack/Queue](25.%20SDK%20Stack%20and%20Queue%20Specification.md) capture in their LIFO/FIFO removal orders.
[Linked](22.%20SDK%20Linked%20and%20Cursor%20Specification.md) uses Cursor<T> for forward and reverse captures.
[Set](23.%20SDK%20Set%20and%20Identity%20Specification.md) produces Cursor<T>; Map<K,V> uses
Cursor<keyval<K,V>> as specified by [Map/Keyval](24.%20SDK%20Map%20and%20Keyval%20Specification.md).
Set/Map gain no ordering guarantee between captures.
A captured keyval association is read-only
and does not follow later association replacement; referenced objects stay shared.
Map owns entry production and Keyval representation while reusing this protocol.
For n logical List positions and k present occurrences, capture takes O(n) work
and O(k) additional nodes; next follows one link in O(1). Each node costs allocation,
ownership and eventual GC work. Do not promise lower memory than arrays, zero
allocation or allocation-free optional results. All complete groups remain rooted
through allocations and calls; provider quotas remain unchanged.
Conformance must execute real PBS through common IR and PBX in the production VM.
It covers every operation, constructor/type rule, logical bounds, exact growth,
holes and full groups, aliases, the entire Cursor table, snapshot independence,
shared object mutation, non-List producers, refusals before and after visible mutation with and without
growth, prefix reclamation, last-node retention, editor projections and installed
SDK/spec/example distribution. Neutral storage/copy/terminal paths also require non-PBS tests.
Value search/removal, sorting, bulk APIs, new equality, public nodes, deep freezing,
general effect/transaction syntax and Linked/Set/Map implementations are out of scope.
@@ -0,0 +1,146 @@
# SDK Linked and bidirectional snapshot capture
Status: Normative. Owner: `compiler/pbs`.
Scope: SDK Linked and Cursor.
Linked algorithms belong to executable PBS SDK source.
Typed storage, faults, ownership, GC and quotas remain generic
compiler/provider mechanisms. This contract builds on [generic structs](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md),
[arrays and optional](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md) and the
[shared Cursor protocol](21.%20SDK%20List%20and%20Cursor%20Specification.md#cursor-protocol).
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Type, identity and construction
The collections SDK exports `linked<T>`. It is an ordinary invariant generic
struct with stable reference identity: aliases observe mutations of the same
collection. `new linked<T>()` creates an empty collection. Contextual construction
follows generic struct rules, requiring a concrete expected application; constructor
values do not infer T. There is no capacity argument.
A directly optional element, including through grouping, is invalid.
`optional (linked<T>)` remains valid, as do otherwise valid element types containing
optional fields. Values retain their complete groups and normal identities,
including tuples, native values, arrays, functions and contract views. No public
Dynamic, universal Element or wrapper node is introduced.
Storage consists of private doubly linked nodes, each containing one present
value. Logical size equals node count. Empty collections have no head or tail;
one-node collections have the same head and tail. Neighbor links are reciprocal,
forward and backward traversals agree, and there are no extra predecessor or
successor nodes beyond the ends. Nodes and private helpers are not a public API.
## Operations and bounds
| Operation | Result | Behavior |
| --- | --- | --- |
| `size()` | long | Number of elements |
| `first()` / `last()` | optional T | End value, or none when empty |
| `xs[i]` | optional T | Present value at a valid index |
| `xs[i] = value` | unit | Replace a valid position without changing size |
| `add(value)` | unit | Append |
| `addFirst(value)` | unit | Prepend |
| `insert(i, value)` | unit | Insert at `0 <= i <= size` |
| `removeAt(i)` | optional T | Remove and return a valid position |
| `removeFirst()` / `removeLast()` | optional T | Remove and return end value, or none when empty |
| `clear()` | unit | Remove all elements and set size to zero |
| `cursor()` | Cursor<T> | Capture first to last |
| `reverseCursor()` | Cursor<T> | Capture last to first |
Reading, replacing and removing by index require `0 <= i < size`; invalid indices
raise TRAP_EXPLICIT even when empty. Insertion accepts size, including zero in an empty
collection. Other insertion indices raise TRAP_EXPLICIT. Every valid position contains
an element, so indexed read/removal returns a present optional. Zero and false are
present values. Empty-end results do not suppress type or resource faults.
Insertion/removal changes the logical indices of following elements. Replacement
preserves size. There are no holes, clearAt, capacity, reserve, trim or resize.
Duplicate occurrences are preserved; no equality or uniqueness rule is imposed.
Value search/removal is outside this API, consistently with List.
Size is nonnegative long. Indices accept int and long with localized lossless
promotion, without general numeric conversion or truncation. The SDK checks the
current size against the maximum signed long before incrementing, using SDK comparisons
and terminal TRAP_EXPLICIT; an unrepresentable next size is rejected before arithmetic or
mutation. Array's u32 structural maximum is not a Linked size limit. Provider
quotas and applicable structural limits can refuse allocation much earlier.
Receiver/arguments evaluate once in source order, including named application.
## Snapshots and costs
Both capture methods return the existing Cursor<T> contract and preserve its
complete state table. A nonempty cursor starts on its first captured value;
hasNext asks whether a successor exists; next without a successor does nothing.
Only a snapshot born empty has an absent current. Repeated next retains the final
value. Capturing `[A, B, C]` produces `[A, B, C]` or `[C, B, A]` respectively.
Each capture completes before return and owns private immutable singly linked,
non-circular snapshot nodes, independent of the collection's doubly linked nodes.
It uses no snapshot array or live association with editable source nodes.
Subsequent insertion, replacement, removal and clear cannot change the captured
sequence. Shared objects retain identity and later field changes remain visible.
There is no removal/reset through Cursor or public node access.
End operations locate their nodes without traversal. Indexed operations search
from the nearer end and remain O(n) in the worst case. Both captures cost O(n)
work and O(n) additional nodes; next follows one link in O(1). Allocation,
optional-carrier preparation, ownership and eventual GC retain their normal
costs. Repeated indexed reads are not an efficient traversal strategy.
## Mutation phases and lifetime
Before the first visible write, prepare bounds, next size, candidate nodes,
optional results and complete field values. Insertion updates previous.next or
head, then next.previous or tail, then length. Removal prepares its result and
neighbors, updates the same two sides, then length. Indexed replacement updates
only value; clear assigns head, tail and length in that order. Source algorithms
own these choices; the VM has no Linked instruction, publication schema or syscall.
A logical rejection or preparation refusal before mutation preserves the previous
head/tail/size, elements and neighbor links. Successful return restores all public
invariants. An internal/resource fault after the first visible write propagates
without rollback: earlier writes may remain and topology/size can be incomplete.
No safe reuse, retry or automatic recovery is promised. This explicitly replaces
the former whole-method refusal guarantee, and is not a basic-consistency claim.
Previously evaluated argument effects remain ordinary source effects.
Individual instruction failures preserve their own entry state. Operand/call/
optional preparation remains charged and can fail; sequential stores are not a
transaction. No user callback or explicit suspension is inserted during updates.
BudgetExhausted and debugger pauses can stop between instructions and resume at
the current PC without completing or undoing the method. Host/debugger observation
is not atomic. No catch, poison flag or recovery API is introduced.
Unpublished candidates follow normal ownership and quotas. Capture failure returns
no partial Cursor and does not change the source. Removal and clear release
collection references to discarded nodes and payloads. Doubly linked cycles are
collected by normal tracing when unreachable; no immediate reclamation is promised.
Snapshots retain payloads, not the editable source topology; consumed prefixes
become collectible while the last current value stays retained until released.
## Conformance and distribution
Qualification executes real PBS through common IR/PBX and the production verifier
and VM, with ordinary and optimized producer paths. Cover the full API in empty,
single and multi-node states, reciprocal links and size, nearest-end lookup, all
bounds, int/long and single/named evaluation, complete groups and identity,
optional-element diagnostics, both Cursor orders/states and mutation independence.
Independently observe all original fields, link carriers, nodes and groups around
quota refusals, including node/result/operand preparation. Exercise ordinary GC
safepoints for removed nodes/values, clear, snapshots and prefix/final release.
Neutral stores/copy/terminal failure also require non-PBS producers and
malformed/dead instruction coverage. Regress shared Array/List/generic/contract/Cursor behavior and editor/LSP
projections. Ship the specification and executable example with installed SDK
knowledge, compile the actual packaged example outside the checkout and execute
its emitted PBX with the production provider.
See [generic Registry/PBX storage](../../compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md)
for the language-neutral instruction contract.
@@ -0,0 +1,253 @@
# SDK Set, Identity and hashing
Status: Normative. Owner: `compiler/pbs`.
Scope: SDK Set and Identity.
Set algorithms belong to executable PBS SDK source. Typed
reference queries, storage, admission, faults and resource limits are generic
compiler/provider mechanisms. This contract builds on [generic structs](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md),
[generic contracts](16.%20Generic%20Contracts%20Specification.md), [Array/optional](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
and the [shared snapshot Cursor](21.%20SDK%20List%20and%20Cursor%20Specification.md#cursor-protocol).
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Types, construction and operations
The `@sdk:collections` module exports invariant ordinary generic `set<T>` and the
nominal contract `Identity<T>`:
```pbs
declare contract Identity<T> {
fn hash(value: T) -> long;
fn equals(left: T, right: T) -> bool;
}
```
Import the SDK declarations with `import {set, Identity, Cursor} from @sdk:collections;`.
Another user contract named Identity does not become the SDK contract through its spelling.
`new set<T>()` selects the SDK default for T. `new set<T>(identity)` takes an
explicit `Identity<T>` service/struct value. Contextual `new set()` and diamond
construction require an existing expected application; argument values do not infer
T. Type applications and strategies are invariant. Associated members such as
Enemy.identity, blanket implementations and generic reflection are not introduced.
No-strategy construction for T without a default is a localized source error.
Explicit-strategy construction remains valid for otherwise supported grouped/native
T, even though the generic owner also declares a no-argument constructor. Direct
optional T, including grouped optional, is invalid with either constructor.
`optional (set<T>)` and elements with optional fields remain valid.
| Operation | Result | Behavior |
| --- | --- | --- |
| add(value) | bool | True on inclusion; false for an equal existing element |
| contains(value) | bool | Membership under the selected policy |
| remove(value) | bool | True only when an equal element was removed |
| clear() | unit | Release table/nodes and reset size to zero |
| size() | long | Number of elements |
| isEmpty() | bool | size equals zero |
| cursor() | Cursor<T> | Complete independent snapshot |
Set has stable reference identity: aliases observe the same collection. A duplicate
add preserves the original stored reference and does not grow the table. Removing
an absent value is false. There is no positional indexer, tryGet, capacity argument,
capacity/reserve/trim API or public node. Insertion/iteration order is not guaranteed.
Receiver and arguments evaluate once in source order, including named application.
An unrelated user declaration named set gains none of the SDK-specific rules.
## Equality policy and obligations
| T | Default policy |
| --- | --- |
| int / long | Value equality in the static domain of T; int widens exactly to Int64 for hashing |
| bool | Value equality; false/true map to Int64 0/1 for hashing |
| str | Exact resident UTF-8 content, without normalization or case folding |
| float | Finite Float equality; +0 and -0 are equal and hash equally |
| Source structs, arrays, Fn and Random | Instance identity, independent of mutable fields/elements, code/captures or generator state |
| contracts | Identity of the fully validated receiver, independent of view/ImplementationId |
| Tuples and other native values | Explicit Identity required; no automatic composition |
Services represented as ordinary singleton references retain the same instance
semantics when they are valid element types. There is no public Dynamic, universal
cross-numeric equality, structural fallback or equality based on private value
carrier identity. Hash collisions do not imply equality. All signed long digest
bits, including negative values, are retained.
Two distinct gameplay objects with equal fields remain distinct under defaults.
An explicit strategy may define content equality and collapse such instances.
Actual stored references remain shared; no deep freezing/copying occurs. Identity
must define a stable equivalence relation while stored and satisfy
`equals(a,b) => hash(a) == hash(b)`. The converse is not required. Strategy
configuration and relevant content must remain coherent. Remove from every affected
collection before changing content used by equality/hash, then reinsert. A cached
old hash does not stabilize mutable equality. The SDK cannot prove these obligations
and does not introduce purity, readonly or effect-system requirements.
Every value preserves its complete logical group and reference aliases through
callbacks, nodes, calls, allocations, rehash and capture. A tuple's private storage
carrier is not that tuple's source identity. Groups/native owners retain ordinary
storage packing and quota costs.
## Private representation and growth
Set uses a private array of buckets with private chained nodes. Each node stores
the complete cached long hash, full T and its next link. It does not depend on the
public linked collection or a universal Element. Hash selects candidates and
equals resolves collisions, including deliberately identical hashes.
Empty construction has no nonempty bucket table. First successful inclusion uses
8 buckets. For current capacity c and next size r, grow when r exceeds
`floor(3*c/4)`; new capacity is `min(2*c, 4294967295)`. Arithmetic uses long and
must not overflow. At the maximum Array capacity, chaining can continue within
checked signed-long size and provider quotas, accepting increased occupancy.
Array's u32 structural bound limits buckets, not the count of chained elements.
An unrepresentable next size is rejected before addition/mutation.
For positive capacity, select the bucket with signed remainder and correction:
```text
bucket = hash % capacity
if bucket < 0: bucket += capacity
```
Do not abs the digest, narrow to int, or assume every capacity is a power of two.
Removal does not shrink. Clear releases table/node references and returns to lazy
empty state. Discarded objects and old storage follow normal tracing and other
owners; immediate collection or quota recovery is not guaranteed.
Rehash prepares independent buckets/nodes/topology from cached hashes. It preserves
published links until installation and preserves payload reference identities.
It does not invoke hash/equals. Old and candidate structures coexist under ordinary
quotas; private carriers can add allocation/ownership work. Installation uses
ordinary typed stores. Whole-table reconstruction on every mutation is not the
algorithm, and preparing a candidate does not make later source instructions atomic.
Search cost depends on hash distribution, occupancy and callback cost; the worst
case is O(N). Growing rehash costs O(new buckets + N) work and additional nodes/table.
String hashing additionally costs work proportional to content. Expected lookup
or amortized growth claims do not promise constant instruction cost, no allocation,
adversarial resistance or allocation-free optional carriers.
## Guard, mutation phases and faults
Operations calling Identity use a private guard. A callback cannot reenter
add/remove/clear/contains on the same Set, including aliases; reject before
structural changes through the private terminal TRAP_EXPLICIT path. During callback
preparation the original structure is consistent: size/isEmpty/cursor may read it
without invoking Identity. Capturing a Cursor may still fail resources.
Validation, hashing/equality/search, next sizes, nodes/tables and value/return
carriers are prepared before structural writes. No user callback or explicit
suspension occurs in the sequence that applies structural changes. Rehash/capture
never call strategies. The guard is released on successful return, including
ordinary false results.
| Outcome | Guarantee |
| --- | --- |
| Refusal before the first structural write | Prior elements/topology are unchanged; external argument/callback effects and provisional allocations are not undone |
| Successful return | Size, topology, buckets, groups, identity, cleanup and guard invariants hold |
| Internal/resource fault after structural mutation starts | Earlier writes may remain and invariants may be incomplete; no rollback, safe reuse, retry or automatic recovery |
Installing the guard is already a write. Callback fault can leave it active while
elements remain unchanged. Structural preservation is not bit-for-bit preservation
of the whole Set object. No catch/finally, poison flag or recovery API is added;
permitted callback reads do not establish post-fault safe reuse. Mutations of other
Sets/objects are not rolled back, and the guard does not prove strategy stability.
Faults are never translated into false/none.
Per-instruction refusal preserves that instruction's applicable entry state, not
earlier successful instructions. BudgetExhausted/debugger pauses are resumable
instruction boundaries; execution resumes at its PC. A source method is not an
atomic observation region for host/debugger inspection.
## Snapshot Cursor
Cursor uses the existing shared implementation and full state table. A nonempty
snapshot begins on the first captured element; hasNext tests a successor; next
without a successor keeps the final value. Only an empty-born Cursor reports
current absent. Consume current before deciding whether to advance:
```pbs
let snapshot = values.cursor();
while true {
if let value = snapshot.current() {
// Use value.
} else { break; }
if snapshot.hasNext() { snapshot.next(); }
else { break; }
}
```
Capture allocates one private immutable singly linked node per element and completes
before returning. Failure returns no partial Cursor and preserves source structure.
Snapshot nodes retain payload values, not editable Set nodes/bucket positions.
Later inclusion/removal/clear/growth cannot rewrite the capture. Referenced objects
remain shared and later field mutation remains visible; iteration order between
captures is not guaranteed. There is no live/fail-fast iterator, reset, removal
through Cursor or new for-in protocol.
For B buckets and N elements, capture is O(B+N) work/O(N) extra nodes and next O(1).
Consumed prefixes can become unreachable; final current node/value stays retained
until the Cursor releases it. Ordinary allocations, carriers, owners, GC and quotas
apply without relaxation.
## Hash facade and typed query boundary
`@sdk:hash` exports `hash.i64(long)->long`, `hash.f64(float)->long`,
`hash.text(str)->long`, `referenceHash<T>(T)->long` and
`referenceEquals<T>(T,T)->bool`. Generic reference wrappers require explicit type
arguments and accept exactly eligible reference categories; grouped/optional value
carriers and arbitrary scalar/Dynamic values do not become references.
The reference wrappers lower complete groups to REF_IDENTITY_HASH 0x0097 and
REF_IDENTITY_EQ 0x0098. Contracts validate receiver and ImplementationId, including
valid zero, before querying receiver identity. Concrete and valid trait views agree.
Both sides of equality validate left-to-right; an absent/different left cannot
suppress an invalid right. Invalid handles/groups remain faults. TypeIds are static
program metadata, not guest selectors. Reference hashes do not root objects or
provide persistent cross-session IDs.
Scalar wrappers use hash.i64@1 0x4100, hash.float@1 0x4101 and hash.string@1 0x4102.
Hash-v1 preserves the provider's XXH64 seed-zero digest bits. Numeric hashes cost
8 cycles; String costs 8 plus UTF-8 bytes. Finite Float bit hashing normalizes both
zeros, never converts numerically to integer, and rejects non-finite inputs.
Provider-level canonical null String hashes to zero and differs from empty text;
PBS adds no public null syntax or optional-element admission. Reference hash costs
8+w(T), equality 4+w(left)+w(right). Valid queries have bounded borrowed execution
without guest/scratch allocation or user callbacks; wrapper/call costs are separate.
Compiler verification, emission and optimization must preserve complete groups,
provenance/null admission, fault order, attempt costs, zero-budget/overshoot and
unused-result effects. Defaults are resolved by private trusted bindings at
concrete logical types, not by enabling == on unconstrained T. Existing user
contracts named Identity retain their own nominal identity and signatures.
## Qualification, distribution and related consumers
Qualify the hash facade from real PBS through PBX into the production VM before
Set algorithms. Test ordinary/optimized source and neutral producers, independent
provider vectors, negative hashes, complete contract groups, Float boundaries,
String owners, aliases/mutation, GC/stale handles and malformed/dead instructions.
Strategy counters and deliberate collisions must demonstrate callback-free
rehash/capture and alias-safe reentrancy. Observe measured old/candidate memory
peaks and instruction-prefix refusal state, separating guard effects and structural
writes. Controlled test-only fault injection must be identified separately from
natural production quota cases.
Ship this English specification, SDK source and executable examples in installed
knowledge; compile actual installed examples outside the checkout and execute their
PBX. Normal compilation uses versioned Studio catalogs/resources without a sibling
checkout. Runtime ownership, limits and semantics remain the provider contract;
Set adds no VM collection instruction/syscall or provider source change.
Identity/hash are reused by [Map/Keyval](24.%20SDK%20Map%20and%20Keyval%20Specification.md). Its API, representation
and implementation are separate consumers; sharing policy does not impose a shared
physical table or universal entry type. See the
[common typed Registry contract](../../compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md)
and [catalog consumer rules](../../compiler/24.%20Runtime%20Catalog%20Support%20Specification.md).
@@ -0,0 +1,192 @@
# SDK Map and read-only Keyval associations
Status: Normative. Owner: `compiler/pbs`.
Scope: SDK Map and Keyval.
Map algorithms execute as PBS SDK source. This contract
builds on [generic structs](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md),
[Array/optional](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md),
[Set/Identity/hash](23.%20SDK%20Set%20and%20Identity%20Specification.md) and the
[shared snapshot Cursor](21.%20SDK%20List%20and%20Cursor%20Specification.md#cursor-protocol).
Registry/PBX, storage, ownership, faults and resource limits remain provider contracts.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Types, construction and public API
`@sdk:collections` exports invariant ordinary generic structs `map<K,V>` and
`keyval<K,V>`, alongside the nominal `Identity<T>` and shared `Cursor<T>` contracts.
Applications retain nominal origin through imports, aliases and reexports. User
homonyms and untrusted SDK attributes acquire no reserved behavior.
```pbs
import {map, keyval, Identity, Cursor} from @sdk:collections;
let scores = new map<str, int>();
let contextual: map<str, int> = new map();
let entry = new keyval<str, int>("player", 42);
let previous: optional int = scores.put(entry);
```
Map offers `new map<K,V>()` and `new map<K,V>(identity: Identity<K>)`. Keyval offers
`new keyval<K,V>(key: K, value: V)`. Diamond/omitted type arguments require a
sufficient expected application; constructor values do not infer type arguments.
Every constructor initializes its fields before returning.
Directly optional K, including grouping, is invalid for Map with either constructor.
V may be optional. Independent keyval admits all valid generic field compositions,
including optional K/V. Optional of the Map itself remains valid. Array's direct
optional-element restriction does not apply to V fields in private Map nodes.
| Operation | Result | Behavior |
| --- | --- | --- |
| m[key] | optional V | none for absent key, some(stored value) for a present key |
| m[key] = value | No previous value | Insert or replace V |
| containsKey(key: K) | bool | Membership under selected key identity |
| put(entry: keyval<K,V>) | optional V | Insert/replace; return previous V if present |
| remove(key: K) | optional V | Remove; return previous V if present |
| clear() | unit | Remove associations, release table, restore lazy empty state |
| size() | long | Number of associations |
| isEmpty() | bool | size equals zero |
| cursor() | Cursor<keyval<K,V>> | Complete independent entry snapshot |
| entry.key() | K | Captured key reference/value |
| entry.value() | V | Captured value reference/value |
Receivers and arguments evaluate once in source order, including named application.
Map indexing expects K and does not apply the additional int-to-long index promotion
of Array/List/Linked. Complete key/value groups cross source calls unchanged.
Map has stable reference identity: aliases observe the same mutations.
Only one association exists for each key equivalence class; values may repeat.
Replacement changes only V and preserves the original stored K, cached hash and
size. It never triggers growth. Replacing the representative key requires removing
the entry and reinserting the new key. put reads association components without
retaining its keyval instance as an editable internal node. remove of an absent
key returns none without changing associations/topology. Prepare previous-value
carriers before replacement or unlinking.
Insertion/iteration order is unspecified. There are no keys/values projections,
capacity constructors, capacity/reserve/trim, bulk APIs, redundant tryGet, public
nodes, universal Element or positional indexing contract.
## Presence and optional payloads
The outer optional of read/put/remove describes association existence, independently
of V. For `map<str, optional int>`, absence is none, present V=none is some(none),
and present V=some(7) is some(some(7)). containsKey is true for a stored none;
assigning none as V does not remove an association. Zero/false and complete
multi-slot groups remain present. Preserve deeper valid optional nesting.
Type/callback/resource faults never become none/false.
## Key Identity and read-only Keyval
Use the exact defaults and eligibility rules of Set: int/long/bool by static-domain
value; str by exact UTF-8 content; finite float equality with equal signed zeros;
source structs, arrays, Fn, Random and eligible services by instance; contracts by
fully validated receiver identity. Tuples and other types without a default require
an explicit Identity<K>. An unavailable default constructor must not invalidate an
otherwise valid explicit-strategy application. V requires no equality/hash capability.
Hash filters candidates and equals resolves collisions. Keep all signed-long hash
bits. Identity must define a stable equivalence relation while stored and satisfy
`equals(a,b) => hash(a) == hash(b)`. Relevant key content and strategy configuration
must remain coherent. Remove from affected collections before changing content
used by hashing/equality, then reinsert. Cached hashes do not stabilize mutable
equality. No structural fallback, freezing, purity proof or effect system is added.
Keyval has private fields and only key()/value() accessors, with no mutators.
It retains ordinary struct instance identity: separately constructed keyvals are
distinct under default Identity even when components match. Component comparison
requires explicit policy; unconstrained K/V gain no equality operator. Assignment
shares the keyval instance and payload aliases. Its association cannot be edited
through Map or follow later replacements; referenced objects remain mutable/shared.
## Private storage, rehash and costs
Map owns a private bucket array with private chained nodes containing full cached
long hash, K, V and next link. It is not implemented over Set/Linked and requires
no public keyval wrapper per internally stored association. Reuse Identity/hash,
common private arithmetic helpers and shared Cursor implementation.
Empty construction has no nonempty bucket table. First inclusion uses 8 buckets.
For capacity c and next size r, grow if r exceeds floor(3*c/4), to
min(2*c, 4294967295). Use checked long arithmetic. At maximum bucket capacity,
chaining can continue within checked signed-long size and ordinary quotas;
Array's u32 bound limits buckets rather than entry count. For positive capacity,
use signed hash remainder and add capacity when negative, without abs, narrowing
or assuming powers of two. Removal does not shrink. Clear returns to lazy state.
Rehash prepares independent nodes/topology from cached hashes, with no callbacks
or edits to published links before installation. Complete payload groups and
reference identities survive. Ordinary mutation does not reconstruct the whole
table. Old/candidate structures coexist under normal quotas and GC; preparation
does not make subsequent stores atomic. Search has worst case O(N), growing rehash
costs O(new buckets + N), and String hashing costs content-dependent work. No fixed
instruction cost, adversarial resistance or allocation-free optional is promised.
## Guard, preparation and failure boundaries
Read/write indexing, containsKey, put and remove install a private guard before
Identity callbacks. Reject callback reentry into these operations or clear on the
same Map, including aliases, through the private terminal TRAP_EXPLICIT path
before changing associations. During callback preparation, size/isEmpty/cursor
may inspect the consistent prior structure without invoking strategies.
Prepare checks, callbacks/search, next sizes, values, return carriers and candidate
structures before the first structural write. Structural stores are sequential,
without user callbacks or explicit suspension. Normal returns release the guard,
including absent reads/removals and insertion/replacement.
| Outcome | Guarantee |
| --- | --- |
| Refusal before structural writes | Prior associations/topology survive; guard, external effects and provisional allocations are not undone |
| Successful return | Size, table, groups, representative identity, cleanup, snapshot and guard invariants hold |
| Internal/resource fault after structural writes start | Earlier writes and incomplete invariants may remain; no rollback, retry, recovery or safe reuse guarantee |
Installing the guard is already a write. Callback faults can leave it active.
No catch/finally, poison flag or recovery API is introduced. Allowed callback reads
do not establish post-fault reuse. Per-instruction refusal preserves that
instruction's applicable entry state, not prior instructions. Budget/debugger
pauses are resumable instruction boundaries; a source method is not an atomic
observation region for host/debugger inspection.
## Entry snapshot and lifetime
cursor creates one new independent keyval and one immutable private snapshot node
per association, without editable Map-node/position links or hash/equals calls.
Capture completes before returning; failure returns no partial Cursor and leaves
source structure unchanged. Preserve the shared Cursor state table: nonempty-born
starts on first, hasNext tests successor, next without successor keeps last, and
only empty-born has absent current. No reset, mutation or new for-in is added.
Later insertions/replacements/removals/clear/rehash cannot rewrite captured
associations. Mutations of referenced objects remain visible; order between captures
is unspecified. Capture costs O(B+N) work and O(N) additional storage, including
N keyvals, N nodes and applicable carriers. next is O(1). Consumed prefixes may
become unreachable, while final current stays retained until its Cursor releases it.
Preserve complete groups and roots/owners across calls, allocation, hashing,
rehash, returns and snapshots. Replacement/removal/clear release obsolete Map
references; snapshots/other owners remain independent. Tracing and native owners
retain normal costs; immediate GC/quota recovery is not guaranteed.
## Qualification and distribution
Compile real source through typed IR/PBX into the production loader/verifier/VM,
using ordinary/optimized producers and independent debug/release harness profiles.
Cover the full API, optional presence, evaluation order, representative retention,
identity/collisions/negative hashes, all Cursor states, groups/aliases, resource
prefix refusals, memory coexistence and real GC. Counters establish callback-free
rehash/capture. Distinguish natural production quotas from named test-only
post-write injection, never shipped in production SDK. Missing mandatory fixtures
fail qualification. Regress existing collections, hashing and language boundaries.
Package this English specification, SDK source and executable examples in installed
knowledge. Compile actual installed examples outside the checkout using installed
JARs and execute their PBX. No collection syscall/opcode, changed ABI/catalog policy,
quota relaxation or provider source mutation is required.
@@ -0,0 +1,146 @@
# SDK Stack and Queue
Status: Normative. Owner: `compiler/pbs`.
Scope: SDK Stack and Queue.
Algorithms execute as PBS SDK source over existing typed
storage, complete-group copies, terminal checks and shared snapshot Cursor.
This contract builds on [Array/optional](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md),
[generic structs](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md) and
[List/shared Cursor](21.%20SDK%20List%20and%20Cursor%20Specification.md#cursor-protocol).
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Types, identity and construction
`@sdk:collections` exports ordinary invariant nominal structs `stack<T>` and
`queue<T>`. Directly optional T, including grouping, is invalid; optional of the
collection and valid payloads containing optional fields remain valid. Tuple,
native, contract, function and reference groups retain their complete types and
owners. No extra cell per element circumvents Array's optional restriction.
Project homonyms/copied metadata acquire no SDK authority. Imports, aliases,
reexports and specializations preserve original SDK identity and privacy.
`new stack<T>()` / `new queue<T>()` create size zero and capacity 16. Their
one-argument constructors create size zero and exactly that capacity, including
zero. Diamond/omitted type arguments require an expected concrete application;
values do not infer T. Capacity accepts int/long with localized lossless promotion,
without general conversion/truncation. Negative/above-u32 capacity is rejected.
Collection references have stable identity through backing replacement. Assignment
and parameter passing share mutations. Payload objects remain shared instances;
duplicates and repeated aliases are separate occurrences, without deep copies or
structural equality. Storage, start, length and private helpers are inaccessible.
## Public API
| Collection | Operation | Result and behavior |
| --- | --- | --- |
| Both | size() | long count of present occurrences |
| Both | capacity() | long physical backing length |
| Both | isEmpty() | bool, size equals zero |
| Both | peek() | optional T, next removal value; none when empty |
| Both | clear() | unit, discard contents and preserve capacity |
| Both | cursor() | Cursor<T>, complete removal-order snapshot |
| Stack | push(value: T) | unit, append at top |
| Stack | pop() | optional T, remove top; none when empty |
| Queue | enqueue(value: T) | unit, append at back |
| Queue | dequeue() | optional T, remove front; none when empty |
Stack consumes LIFO, Queue FIFO. Receiver/arguments evaluate once in source order,
including named calls. Zero/false are present. Faults remain faults, never absence.
No indexer, holes, reserve/trim/resize, bounded/bulk variant, public nodes or
mutation/reset through Cursor exists.
## Capacity and private storage
`0 <= size <= capacity <= 4294967295`. Initial capacity does not cap collection size.
When required r exceeds c, automatic growth chooses
`min(4294967295, max(r, c + max(1, ceil(c/2))))`, after checking r itself fits.
Arithmetic uses checked long values without narrowing; zero grows to one.
Invalid logical requests terminate through the private SDK TRAP_EXPLICIT binding
with source attribution. Actual Array instructions retain their physical faults.
Ordinary quotas can refuse earlier. Removal/clear never shrink capacity.
Stack owns a dense array occupying exactly `[0,size)`, with top at size-1.
Queue owns a circular array occupying size logical positions from start. Empty
Queue has start zero; otherwise capacity is positive and start is below capacity.
Circular addressing avoids zero-capacity access/remainder. Every inactive slot is
empty after successful operations. Neither collection is a List/Linked adapter;
inclusion creates no collection node and dequeue never shifts remaining values.
Stack growth privately copies its dense prefix and inserts the value. Queue
growth privately copies occupied suffix and wrapped prefix directly into `[0,size)`,
then inserts at size; it installs backing, start=0 and size in that sequence.
Old storage is not edited during candidate preparation. Complete groups and payload
identities survive copies, including native owners. In-capacity insertion does not
rebuild the whole backing. End operations without growth cost O(1) apart from normal
value/carrier work; growth and clear cost O(n), plus physical capacity allocation.
## Mutation phases and lifetime
Prepare checks, next count, payloads, optional returns (including typed absence)
and candidates before visible mutation. Source-selected write sequences are:
| Operation | Writes after preparation |
| --- | --- |
| In-capacity push/enqueue | Inactive destination slot, then size |
| Growing push | Prepared backing, then size |
| Growing enqueue | Prepared backing, start=0, then size |
| Nonempty pop | Clear old top, then size |
| Nonempty dequeue | Clear front, next start (zero when empty), then size |
| Stack clear | Clear occupied slots in index order, then size=0 |
| Queue clear | Clear occupied slots in FIFO order, then start=0, then size=0 |
Reads, capture and empty removals do not write the collection. Before the first
visible write, rejection/preparation refusal preserves old backing, slots, start
and size; argument effects/provisional allocations are not undone. Success restores
all invariants. Later internal/resource faults may retain writes and incomplete
invariants, without rollback, safe reuse, retry or recovery. Per-instruction refusal
preserves its own entry state, not earlier instructions. No callback/explicit
suspension occurs between update stores. Budget/debugger pauses remain resumable
instruction boundaries; a method is not an atomic host observation region.
Removal clears the discarded slot; clear removes all occupied references while
retaining empty backing. Later reuse cannot resurrect old payloads. Old/candidate
arrays, multi-slot packing, optional carriers, copy scratch and snapshots coexist
under unchanged quotas/GC. No allocation-free insertion/result, immediate collection
or immediate quota return is promised.
## Removal-order snapshot Cursor
Stack captures top → base, Queue front → back. Inserting 20,22 yields Stack
snapshot 22,20 and Queue snapshot 20,22. Capture completes before returning and
owns one immutable private singly linked non-circular node per occurrence, with
no snapshot array/source-slot association. It costs O(n) work/additional nodes;
refusal returns no partial Cursor and leaves the source unchanged.
Reuse the entire shared table: a nonempty Cursor starts on first; hasNext tests
successor; next without successor does nothing; only empty-born current is none.
Consume current before deciding whether to advance. Captured sequence/order is
independent of later insertion/removal/growth/clear; referenced objects still share
later field changes. Consumed prefixes can become collectible, while final current
node/value remain retained until the Cursor releases them.
## Conformance and distribution
Qualify real PBS through common IR/PBX and production loader/VM, using ordinary
and optimized producers and runtime debug/release profiles. Cover complete APIs,
context/types/origin/privacy, exact capacities/growth/maximum checks, zero/false,
complete groups and ownership, order/duplicates/aliases, source/named evaluation,
wrap-around/wrapped growth, fill/drain/reuse, snapshots and sharing.
Measure coexisting arrays/carriers, quota preparation/write boundaries with
independent original-object observations and successful-prefix comparisons. Keep
explicit test-only post-write probes separate from natural refusal frequencies.
Observe actual GC collections for discarded values/replaced backings and snapshot
prefix/final release. Ship this spec and executable example in installed knowledge,
compile real installed-JAR examples outside the checkout and execute emitted PBX.
Regress shared storage/generic/Cursor behavior; retain provenance and limitations.
Runtime storage, ISA, quotas, faults and GC remain unchanged provider contracts.
@@ -20,10 +20,10 @@ This document defines syntax only. Runtime behavior, optimizer policy, and bytec
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
1. Runtime authority ([provider specifications](../../../../../runtime/docs/specs/runtime/README.md); [mirror and provenance policy](../../../vm-arch/README.md))
2. Bytecode authority ([provider Core ISA](../../../../../runtime/docs/vm-arch/ISA_CORE.md))
3. This document
4. Legacy references (`docs/specs/random/pbs_old/*`)
4. Retired PBS drafts are historical context only and carry no normative authority.
If a rule here conflicts with higher authority, it is invalid.
@@ -76,8 +76,8 @@ Keywords are not valid identifiers.
Active keywords in `.pbs`:
- `import`, `from`, `as`
- `service`, `host`, `fn`, `apply`, `bind`, `new`, `implements`, `using`, `ctor`
- `declare`, `struct`, `contract`, `error`, `enum`, `callback`, `global`, `Self`, `this`
- `service`, `host`, `fn`, `apply`, `new`, `implements`, `using`, `ctor`
- `declare`, `struct`, `contract`, `error`, `enum`, `global`, `Self`, `this`
- `pub`, `mut`
- `let`, `const`
- `if`, `else`, `switch`, `default`, `for`, `from`, `until`, `step`, `while`, `break`, `continue`, `return`
@@ -96,6 +96,10 @@ Reserved (not active syntax in v1 core):
- `spawn`, `yield`, `sleep`
- `match`
Retired source forms `declare callback` and `bind(...)` MUST be rejected;
[function values and captures](15.%20First-Class%20Functions%20and%20Captures%20Specification.md)
defines their replacement. Retired tokens are not active declaration/call syntax.
Note:
- `host` is used only by reserved SDK/toolchain `declare host` surfaces in v1 core; ordinary user-authored modules MUST reject those declarations.
@@ -366,7 +370,7 @@ Rules:
### 7.2 First-class function values
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).
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](15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
### 7.3 Services
@@ -380,7 +384,7 @@ ServiceMember ::= 'fn' Identifier ParamList ReturnAnn? Block | ConstDecl
Rules:
- `declare service Name { ... }` declares a nominal service type together with its canonical module-owned singleton value `Name`.
- A service body contains method declarations and `declare const` members. SDK service intrinsic signatures may terminate with `;`; see [Service constants and runtime math](../../../compiler/pbs/specs/service-constants-and-runtime-math.md).
- A service body contains method declarations and `declare const` members. SDK service intrinsic signatures may terminate with `;`; see [Service constants and runtime math](19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md).
- Service methods have an implicit receiver binding `this` of type `Self` and do not declare `this: Self` explicitly.
- Services do not declare fields.
- Services do not declare `ctor`.
@@ -446,7 +450,7 @@ Rules:
- A `declare const` initializer is required unless another specification explicitly permits a reserved declaration-only shell such as builtin constant metadata.
- A `declare const` initializer, when present, MUST be a constant expression as defined by static semantics.
- `declare const` values are compile-time constants, not runtime-initialized module storage.
- A reserved top-level builtin constant shell MAY use attributes such as `BuiltinConst(...)` and omit the initializer when another specification explicitly defines VM-owned materialization.
- A reserved top-level or SDK service builtin constant shell MAY use attributes such as `BuiltinConst(...)` and omit the initializer when another specification explicitly defines VM-owned materialization.
## 8. Type syntax
@@ -611,7 +615,7 @@ Rules:
- `new Type(args...)` is the canonical struct construction surface.
- `new Type.ctorName(args...)` is the canonical named-constructor surface.
- Struct construction arguments are positional and follow the declared struct field order.
- `as` is reserved in expressions for explicit contract-view conversion only; it does not denote a general cast surface in v1 core.
- `as` expresses explicit contract-view conversion or the supported numeric conversions defined by [input and value alignment](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md). It is not an unrestricted cast.
- A contract-view `as` target is a visible contract type, including explicit arguments such as `Identity<int>`, never a qualified module path. Existing numeric conversions retain their value-alignment rules.
- `this` is an implicit receiver name available only inside struct method, service method, and `ctor` bodies.
- `Self` is valid only inside struct method declarations, service method declarations, and `ctor` declarations.
@@ -1199,25 +1203,27 @@ 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter owns the source syntax and spans consumed by that feature.
Retired `declare callback`, callback exports and `bind(...)` are rejected. They do not provide alternative spellings for Fn or lambdas.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
Parameterized contracts use explicit angular arguments in annotations, nested types, implements and as. Barrels export the ordered parameter list. Raw generic uses, empty argument lists and default arguments are invalid; existing contextual closers and Array construction sugars remain unchanged.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md).
## Concrete generic structs and free functions
Struct and module-level free-function declarations and their barrel items accept ordered type parameters. Explicit function applications are reference expressions; calls use existing parentheses/apply. Generic construction supports explicit arguments and contextual diamond/omission. Owner-bound `implements` accepts its own parameter binder and a full applied owner. Independent method parameters, function diamond/inference and polymorphic Fn remain invalid. The owner specification defines exact arity, comparison disambiguation and recovery.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
## Controlled guest lifecycle marker syntax
@@ -20,8 +20,8 @@ It is intended to:
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
1. Runtime authority ([provider specifications](../../../../../runtime/docs/specs/runtime/README.md); [mirror and provenance policy](../../../vm-arch/README.md))
2. Bytecode authority ([provider Core ISA](../../../../../runtime/docs/vm-arch/ISA_CORE.md))
3. `3. Core Syntax Specification.md`
4. This document
@@ -87,7 +87,7 @@ Rules:
- `Init` is valid only on a top-level userland `fn` declaration with lifecycle-admissible signature.
- `Frame` is valid only on a top-level userland `fn` declaration with lifecycle-admissible signature.
- `InitAllowed` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
- `Host` is invalid on ordinary user-authored modules, top-level `fn`, struct methods, service methods, callbacks, contracts, and constants.
- `Host` is invalid on ordinary user-authored modules, top-level `fn`, struct methods, service methods, lambdas, contracts, and constants.
- `Host` metadata is consumed by the compiler during host-binding lowering.
- `AssetLowering` MUST declare exactly the named argument `param`.
- `AssetLowering.param` MUST be a zero-based integer literal that names a valid host parameter position.
@@ -95,7 +95,7 @@ Rules:
- `AssetLowering` metadata is consumed by backend-owned host-call lowering to rewrite the targeted symbolic `Addressable` operand into runtime-facing `asset_id`.
- The `Host` attribute syntax itself is not exported as runtime metadata; instead, its canonical identity participates in PBX host-binding emission as defined by the Host ABI Binding specification.
- `BuiltinType` is valid only on a reserved top-level `declare builtin type` declaration.
- `BuiltinConst` is valid only on a reserved top-level `declare const` declaration that omits an initializer.
- `BuiltinConst` is valid on reserved top-level and SDK service `declare const` shells that omit an initializer, as defined by [service constants and runtime math](19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md).
- `IntrinsicCall` is valid on a method signature inside a reserved `declare builtin type` body or an SDK service body. SDK service signatures have no implementation body and bind their exact declared argument/result carriers to the common intrinsic catalog.
- Builtin metadata is consumed by the compiler during VM-owned builtin and intrinsic lowering rather than by host-binding lowering.
- `Init` and `Frame` are consumed by lifecycle analysis and lowering rather than by ordinary runtime reflection.
@@ -195,7 +195,7 @@ The following constructs are callable in v1 core:
- top-level `fn`,
- struct methods on concrete receivers,
- contract values,
- callback values,
- structural `Fn` values,
- service methods,
- host methods on declared host owners,
- builtin intrinsic methods on declared builtin types.
@@ -252,7 +252,7 @@ Rules:
- Project init must be colocated with `[Frame]`.
- PBS static semantics and lowering admit those markers and translate them into a typed `IRLifecycleDeclaration`.
- PBS MUST NOT materialize module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard; those artifacts belong to common lifecycle assembly.
- `InitAllowed` is valid only on SDK host methods and is invalid on userland `fn`, `global`, `service`, `const`, `struct`, `contract`, and callback surfaces.
- `InitAllowed` is valid only on SDK host methods and is invalid on userland `fn`, `global`, `service`, `const`, `struct`, `contract`, and lambda surfaces.
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Host` attribute.
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Capability` attribute.
- A `Host` attribute MUST declare exactly the named arguments `module`, `name`, and `version`.
@@ -349,7 +349,7 @@ Rules:
### 3.6 Structs, services, methods, and contracts
Service constants follow [Service constants and runtime math](../../../compiler/pbs/specs/service-constants-and-runtime-math.md).
Service constants follow [Service constants and runtime math](19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md).
They are immutable members exported with their service. Qualified constant reads
materialize the constant without constructing a singleton or invoking a method.
@@ -376,7 +376,7 @@ Rules:
- A named `ctor` declared in a struct body is not a method, but it does introduce an implicit under-construction `this`.
- A `ctor` has no declared return annotation and is not a `fn`.
- A `ctor` completes by falling off the end of its body after initializing the enclosing struct instance.
- Every field of the enclosing struct must be definitely assigned on every completing `ctor` path.
- Every field of the enclosing struct must be definitely assigned on every completing `ctor` path, including ordinary/generic owners and opaque Random fields. Provider reference defaults do not exempt PBS constructors; [generic construction](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md#construction-and-expected-types) owns this complete rule.
- Named constructors participate in overload resolution by name plus parameter signature.
- `return;` and `return expr;` are both invalid inside `ctor` bodies.
- Methods declared in a struct body belong to the direct method namespace of that concrete struct type.
@@ -395,7 +395,7 @@ Rules:
- Methods declared directly inside a struct or service follow the visibility of their enclosing owner declaration; they do not have independent visibility.
- A struct value or service singleton value may be coerced to a contract value when exactly one visible `implements Contract for Owner ...` applies.
- Contract coercion may happen by explicit `expr as ContractType` or by contextual typing in assignments, parameter passing, and returns.
- `as` in expression position is reserved for explicit contract coercion only; no other cast semantics exist in v1 core.
- `as` supports explicit contract coercion and the numeric conversions owned by [input and value alignment](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md); other casts remain invalid.
- The contract in `expr as ContractType` is resolved through ordinary scope/import rules and may carry explicit type arguments. Aliases preserve declaration identity.
- A contract value carries the underlying struct reference or service singleton value together with the selected contract implementation for runtime dispatch.
- Calling `contractValue.method(...)` uses dynamic dispatch through the contract value.
@@ -442,7 +442,7 @@ fn demo() -> int {
### 3.7 Structural function values
[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.
[First-class functions and explicit value captures](15.%20First-Class%20Functions%20and%20Captures%20Specification.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
@@ -457,7 +457,7 @@ Rules:
- `apply` is an infix operator that is right-associative.
- `f1 apply f2 apply x` is defined as `f1 apply (f2 apply x)`.
- `f1 apply f2 apply f3 apply params` is defined as `f1 apply (f2 apply (f3 apply params))`.
- The left operand of `apply` must resolve to one of: a callable candidate set, a bound struct method target, a bound service method target, a contract-method target, or a callback value.
- The left operand of `apply` must resolve to one of: a callable candidate set, a bound struct method target, a bound service method target, a contract-method target, or a `Fn` value.
- The right operand of `apply` is an argument expression.
- If the callable input arity is `0`, the argument expression must be `()`.
- If the callable input arity is `1`, the argument expression is checked against the carrier type of the single input slot.
@@ -497,7 +497,7 @@ Rules:
- If the selected callable output arity is `1`, the result of `apply` is the carrier type of the single output slot.
- If the selected callable output arity is `2..6`, the result of `apply` has the named output tuple shape of the selected callable.
- Multi-slot output tuple results expose their labels for member projection.
- If the selected callable is a callback value, the visible multi-slot output labels come from the callback type rather than from the original source `fn`.
- If the selected callable is a `Fn` value, the visible multi-slot output labels come from the `Fn` type rather than from the original source `fn`.
- If the selected callable returns `()`, the application result is unit.
Example:
@@ -749,10 +749,10 @@ At minimum, deterministic static diagnostics are required for:
- invalid named constructor target,
- unresolved named constructor overload,
- ambiguous named constructor overload,
- incompatible top-level `fn` assignment to callback type,
- 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,
- incompatible top-level `fn` assignment to `Fn` type,
- ambiguous overloaded top-level `fn` assignment to `Fn` type,
- attempted assignment of service method to `Fn` type,
- attempted assignment of host method to `Fn` type,
- `apply` on a non-callable target,
- arity mismatch in `apply`,
- argument type mismatch in `apply`,
@@ -816,28 +816,29 @@ At minimum, deterministic static diagnostics are required for:
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
The [PBS input and value alignment contract](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
## 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter supplies shared static checks; Array-specific admissibility and
contextual construction are defined by that owner.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
Application identity combines the defining nominal declaration with ordered canonical logical arguments after alias resolution. Applications are invariant. Substitution preserves existing type-position restrictions, names, labels and complete groups across Array, Fn, optional, tuples and nested contracts. A struct/service may implement several applications, with complete unique implementations in its owner module. Finite instance recursion is accepted within resource limits; unbounded expansion receives a bounded diagnostic.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
The [generic contract chapter](16.%20Generic%20Contracts%20Specification.md)
owns the complete application, substitution, coherence and bounded-validation rules.
Compilation and editor analysis MUST share that resolution.
## Concrete generic structs and free functions
Templates are checked symbolically in definition scope. Required concrete owners validate all methods and constructors, including unused methods. Substitute complete bodies and applied Self; preserve position restrictions, invariant nominal/phantom identity and logical groups. Explicit function applications filter generic overloads by type arity; ordinary calls never infer them. Bound owner implementations require complete exact signatures and symbolic overlap rejection before use. Finite recursive applications are anchored; expanding type/body families are bounded errors.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
The [generic struct and free-function chapter](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md)
owns the complete application, substitution, coherence and bounded-validation rules.
Compilation and editor analysis MUST share that resolution.
## Controlled guest lifecycle admission
@@ -562,11 +562,11 @@ new coverage; existing behavior MUST NOT regress.
A barrel exports a parameterized contract declaration with the same ordered parameters as its source declaration. Imported bindings retain the original declaration and lexical source scope, including aliases in signatures of dependencies. A local alias never creates another nominal type. Implementations remain in the declaring module of the concrete struct/service owner.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md).
## Concrete generic structs and free functions
Generic struct/function barrels export declarations and ordered parameters, including complete function signatures, rather than enumerated specializations. Imports and aliases preserve nominal origins and definition-scoped bodies/private helpers. Specializations are shared across equivalent uses and do not export private dependencies. SDK and program sources use the same language machinery.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
@@ -56,8 +56,8 @@ This document does not define:
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
1. Runtime authority ([provider specifications](../../../../../runtime/docs/specs/runtime/README.md); [mirror and provenance policy](../../../vm-arch/README.md))
2. Bytecode authority ([provider Core ISA](../../../../../runtime/docs/vm-arch/ISA_CORE.md))
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
@@ -45,8 +45,8 @@ This document does not define:
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
1. Runtime authority ([provider specifications](../../../../../runtime/docs/specs/runtime/README.md); [mirror and provenance policy](../../../vm-arch/README.md))
2. Bytecode authority ([provider Core ISA](../../../../../runtime/docs/vm-arch/ISA_CORE.md))
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
@@ -242,7 +242,7 @@ changes the rule:
- user-declared structs,
- services,
- contracts,
- callbacks,
- function values,
- `optional`,
- `result`,
- and any type with runtime-variable or heap-defined width.
@@ -563,4 +563,4 @@ The current temporary contract is:
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
The [PBS input and value alignment contract](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
@@ -13,7 +13,7 @@ Its purpose is to make runtime behavior convergent across implementations by fix
- runtime evaluation of expressions and statements,
- abrupt completion and propagation behavior,
- runtime behavior of effect surfaces such as `optional` and `result`,
- the execution boundary between ordinary PBS code, callbacks, contract calls, and host-backed calls.
- the execution boundary between ordinary PBS code, function values, contract calls, and host-backed calls.
## 2. Scope
@@ -22,7 +22,7 @@ This document defines:
- the observable execution model of PBS core,
- evaluation order for expressions, statements, and blocks,
- runtime branch selection for `if` and `switch`,
- runtime application behavior for `apply`, call sugar, methods, contracts, callbacks, and host-backed call surfaces,
- runtime application behavior for `apply`, call sugar, methods, contracts, function values, and host-backed call surfaces,
- runtime behavior of `optional`, `result<E>`, `else`, `!`, and `handle`,
- abrupt completion (`return`, `break`, `continue`) and trap propagation,
- determinism requirements that affect execution behavior.
@@ -39,8 +39,8 @@ This document does not define:
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
1. Runtime authority ([provider specifications](../../../../../runtime/docs/specs/runtime/README.md); [mirror and provenance policy](../../../vm-arch/README.md))
2. Bytecode authority ([provider Core ISA](../../../../../runtime/docs/vm-arch/ISA_CORE.md))
3. `3. Core Syntax Specification.md`
4. `4. Static Semantics Specification.md`
5. This document
@@ -265,7 +265,7 @@ The same observable call model applies to:
- struct methods,
- service methods,
- contract calls,
- callback calls,
- `Fn` calls,
- host-backed calls.
Callable-specific dispatch may differ internally, but it does not change the user-visible sequencing model defined in this document.
@@ -281,7 +281,7 @@ If a callable returns:
### 11.3 Closure creation and invocation
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).
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](15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
## 12. Branch Selection
@@ -377,11 +377,14 @@ This document is ready to move beyond temporary draft status only when:
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
The [PBS input and value alignment contract](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
## 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.
The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
defines the complete type, optional-flow and storage contract.
This chapter supplies common evaluation and abrupt-completion rules; Array-specific
evaluation, presence and mutation rules are defined by that owner.
## Controlled pause and resume hooks
+55 -5
View File
@@ -1,5 +1,7 @@
# PBS Specs
Owner: `compiler/pbs`. Canonical source: `docs/specs/compiler-languages/pbs`.
This directory contains the normative PBS specification set.
## Installed Quickstart (Informative)
@@ -82,7 +84,7 @@ Specs define the official PBS language/frontend contract.
They exist to make behavior, constraints, and interfaces stable across implementations and reviews.
Cross-language acceptance rules are not defined here.
Those are maintained in `docs/general/specs`.
Those are maintained in `docs/specs/compiler`.
## Expected Format
@@ -143,12 +145,60 @@ That means:
- and Studio/LSP consume that contract without becoming owners of PBS semantic presentation assets.
The `@sdk:random` module exports `Random` and `random`. Use an explicit long seed;
copying a generator shares its state. Read `pbs:spec:runtime-random-integration.md`
copying a generator shares its state. Read `pbs:spec:20`
and `pbs:example:game:1:src/random.pbs` for the exact contract and a small example.
## Parameterized contracts
Parameterized nominal contracts, concrete frontend specialization, implementation/coercion rules, composition, recursion and production conformance are defined by the owner specification.
## Authority and reading order
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
Read syntax and static semantics (3–4), module/SDK resolution (5), host/intrinsic
boundaries (6–8), execution/memory (9–10), and compiler projections (11–13).
Thematic chapters 14–25 own their complete feature contracts. Base chapters
retain syntax, AST, diagnostics and lowering responsibilities and refer to those
owners for detailed rules. The accepted explicit-initialization rule in chapter 17
applies to every completing ordinary/generic constructor, including Random fields.
[General compiler specifications](../../compiler/README.md) own shared handoff
and acceptance; the [runtime mirror policy](../../../vm-arch/README.md) identifies
the provider's separate ABI/execution authority. Keep those boundaries explicit.
## Chapter index
- [1. Language Charter](1.%20Language%20Charter.md)
- [2. Governance and Versioning](2.%20Governance%20and%20Versioning.md)
- [3. Core Syntax Specification](3.%20Core%20Syntax%20Specification.md)
- [4. Static Semantics Specification](4.%20Static%20Semantics%20Specification.md)
- [5. Manifest, Stdlib, and SDK Resolution Specification](5.%20Manifest%2C%20Stdlib%2C%20and%20SDK%20Resolution%20Specification.md)
- [6. VM-owned vs Host-backed](6.%20VM-owned%20vs%20Host-backed.md)
- [6.1. Intrinsics and Builtin Types Specification](6.1.%20Intrinsics%20and%20Builtin%20Types%20Specification.md)
- [6.2. Host ABI Binding and Loader Resolution Specification](6.2.%20Host%20ABI%20Binding%20and%20Loader%20Resolution%20Specification.md)
- [7. Cartridge Manifest and Runtime Capabilities Specification](7.%20Cartridge%20Manifest%20and%20Runtime%20Capabilities%20Specification.md)
- [8. Stdlib Environment Packaging and Loading Specification](8.%20Stdlib%20Environment%20Packaging%20and%20Loading%20Specification.md)
- [9. Dynamic Semantics Specification](9.%20Dynamic%20Semantics%20Specification.md)
- [10. Memory and Lifetime Specification](10.%20Memory%20and%20Lifetime%20Specification.md)
- [11. AST Specification](11.%20AST%20Specification.md)
- [12. Diagnostics Specification](12.%20Diagnostics%20Specification.md)
- [13. Lowering IRBackend Specification](13.%20Lowering%20IRBackend%20Specification.md)
- [14. Typed Arrays and Optional Execution Specification](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
- [15. First-Class Functions and Captures Specification](15.%20First-Class%20Functions%20and%20Captures%20Specification.md)
- [16. Generic Contracts Specification](16.%20Generic%20Contracts%20Specification.md)
- [17. Generic Structs and Free Functions Specification](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md)
- [18. Input and Existing Type Runtime Alignment Specification](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md)
- [19. Service Constants and Runtime Math Specification](19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md)
- [20. Runtime Random Integration Specification](20.%20Runtime%20Random%20Integration%20Specification.md)
- [21. SDK List and Cursor Specification](21.%20SDK%20List%20and%20Cursor%20Specification.md)
- [22. SDK Linked and Cursor Specification](22.%20SDK%20Linked%20and%20Cursor%20Specification.md)
- [23. SDK Set and Identity Specification](23.%20SDK%20Set%20and%20Identity%20Specification.md)
- [24. SDK Map and Keyval Specification](24.%20SDK%20Map%20and%20Keyval%20Specification.md)
- [25. SDK Stack and Queue Specification](25.%20SDK%20Stack%20and%20Queue%20Specification.md)
## Installed reference compatibility
Each numbered chapter is indexed as `pbs:spec:<number>`; this README is
`pbs:quickstart`. Published filename-based IDs for chapters 14–25 remain aliases
of the same canonical packaged text and hash. New callers should use the numbered
IDs returned by project context. The alias catalog is generated by the frontend
build from this single source directory. It does not read a second spec tree.
The internal resource path is `pbs-knowledge/specs/<numbered filename>.md`;
reference clients resolve IDs through the catalog instead of constructing paths.