feat(pbs): implement typed arrays, optional binding and contract execution

This commit is contained in:
2026-10-16 16:21:33 +01:00
parent c4e1b9055d
commit 39df63581c
51 changed files with 1902 additions and 68 deletions
@@ -0,0 +1,70 @@
---
id: LSN-0083
ticket: pbs-typed-collections-and-dynamic
title: PBS Arrays Optional and Contract Execution
created: 2026-10-16
tags: [compiler/pbs, runtime-integration]
---
# PBS arrays, optional values and contract execution
Owner: compiler/pbs. This lesson consolidates accepted DEC-0067 and completed PLN-0146 (DSC-0079). The [typed arrays specification](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md) is the normative reference; the [implementation evidence](../../evidence/DSC-0079-implementation/README.md) records the tested tree and commands.
## The original problem
Games need to reserve enemy positions before constructing enemies. Filling storage with fabricated objects or treating numeric zero as absence gives the wrong semantics. The runtime already offered Array, Dynamic, Struct and Trait, but their existence did not make PBS source executable: optional lowering, struct construction/fields and contract dispatch were incomplete.
The solution separates static source types, optional presence and physical storage. It also completes the existing struct/contract execution path instead of deferring it to closure work.
## The resulting source contract
```pbs
let enemies: array Enemy = new array(10);
let groups: array[2] Enemy = new array(3);
let scores: array int = [10, 20, 30];
if let enemy = enemies[1] {
enemy.takeDamage(10);
}
enemies.clear(1);
```
Arrays have fixed length, shared reference identity and invariant element/depth types. Allocation initializes only outer positions to empty; it does not create enemies or nested arrays. Both constructors and every array literal require an expected array type. Depth is a positive literal; compiler structural limits prevent unbounded expansion. Length and indices accept int/long without loss, with the promotion confined to these operations.
Reads return optional T. A vacant position is none, zero is present, and an invalid index faults. `if let` evaluates once and binds only in the success block. Optional fallback is lazy. Optional values, tuples, fields, parameters and results preserve complete groups. Optional array elements are rejected; an optional array itself is valid. PBS gains neither public Dynamic nor public null.
## How the implementation works
Array positions use internal Array<Dynamic>. Single-slot values are packed directly, while native multi-slot values use the runtime's immutable Dynamic boxing. A null Dynamic tag marks vacancy. Checking DYN_CAN_UNPACK alone is incorrect because a null carrier can be compatible with nullable types such as strings or references.
Private nullable Struct carriers represent optional values. None is null; some owns a carrier holding the complete payload. Named tuples are flattened across callable boundaries and privately boxed for storage. Tuple labels remain editorial metadata rather than changing compatible storage identity. Nominal struct and contract identities include declaration provenance, preventing unrelated modules from sharing a type merely because their names match.
The compiler emits actual struct allocations, field loads/stores, constructors, typed receivers, contract adapters and CALL_TRAIT. It selects overloads using parameter and result shapes and substitutes Self consistently in semantics and executable metadata. Imported calls retain their module identity. Services have a private singleton accessor so imports share the provider's instance.
Global initializers run through the file-init path in dependency order. This matters for reserved arrays: a source declaration must create storage before subsequent code uses it. Grouped global values use private carriers rather than losing slots.
## Lessons from failures found during implementation
- **VM availability is not frontend support.** A parser accepting an expression, or an assembly probe passing, says nothing about complete source lowering.
- **Presence and compatibility are different questions.** Test the Dynamic tag before unpacking; do not turn type or bounds faults into absence.
- **Global defaults are not nullable defaults.** VM global slots initially contain Int32 zero. The service singleton guard must recognize that initial state before publishing a reference.
- **A tuple is not just its first slot.** Optional extraction, field storage and callable transport must agree on full layouts. Tuples stored in private carriers must be flattened again when read.
- **Arity is insufficient for overloads.** Preserve input/output shape, Self substitution and module identity. Choosing a method by name and arity silently changes program meaning.
- **Lexical scope also exists during lowering.** Restore slot/type/owner/projection bindings after blocks and if-let branches; semantic scope checks alone do not preserve shadowed runtime locals.
- **Generated tests must be mandatory.** A runtime harness that scans only available files can pass while a producer stopped generating required fixtures. The structured corpus names every required case.
## Verified result and boundaries
The final gates executed 500 tests without failures; 13 pre-existing disabled tests are listed in the evidence. All 27 new PBS-to-production-PBX cases and 18 resource-refusal runs passed the real loader/VM, alongside 114 existing PBS fixtures and the common backend/catalog corpus. The integer-array case succeeds with one handle total. The GC case reclaims at least 1,100 discarded objects while preserving referenced objects, tuples and strings.
The GC safepoint is provided by an explicit test-only driver hook; it does not claim PBS sync/closure delivery. Default runtime quotas and GC thresholds were not relaxed. Two pre-existing upstream JSON-schema enum gaps remain explicitly reported by the existing harness. No installed-game qualification or performance claim is inferred from these results.
The installed knowledge package includes the specification and an executable [array example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/arrays.pbs). SDK collections continue in AGD89, closures in AGD82, and installed reference-game qualification in AGD88.
## Implementation references
- [Source conformance tests](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java)
- [Runtime harness and reproduction instructions](../../../tools/pbx-conformance/README.md)
- [Static semantics](../../../docs/specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md)
- [Dynamic semantics](../../../docs/specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md)
- [Earlier typed common IR/PBX lesson](../DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md)