feat(pbs): implement typed arrays, optional binding and contract execution
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
# Typed arrays and optional execution
|
||||
|
||||
Owner: `compiler/pbs`. 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.
|
||||
|
||||
## Types and construction
|
||||
|
||||
`array T` denotes a fixed-length reference to positions holding values of T or no value. `array[N] T` denotes N nested array levels, where N is a positive integer literal. `array[1] T` and `array T` are equivalent. Depth belongs to the type; allocation length belongs to the constructor. The compiler bounds expanded type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST.
|
||||
|
||||
```pbs
|
||||
let enemies: array Enemy = new array(10);
|
||||
let groups: array[2] Enemy = new array(3);
|
||||
let scores: array int = [10, 20, 30];
|
||||
let empty: array Enemy = [];
|
||||
```
|
||||
|
||||
`new array(length)` requires an expected array type. It allocates 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 an array type from its elements. Expected types propagate through annotated bindings, assignments, parameters, returns and nested value expressions. Incompatible elements are errors; they do not produce a public Dynamic type.
|
||||
|
||||
Arrays are invariant in element type and depth. 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.
|
||||
|
||||
`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.
|
||||
|
||||
## 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 atomic refusals 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, invalid depth, 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](../../../specs/compiler-languages/pbs/3.%20Core%20Syntax%20Specification.md)
|
||||
- [Static semantics](../../../specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md)
|
||||
- [Dynamic semantics](../../../specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md)
|
||||
- [Existing type runtime alignment](input-and-existing-type-runtime-alignment.md)
|
||||
|
||||
List/Set/Map, growth, iteration, equality and hashing policies belong to the separate SDK collections discussion. A future list capacity does not create logical elements; fixed array length does.
|
||||
Reference in New Issue
Block a user