--- id: LSN-0088 ticket: pbs-generic-contracts title: Concrete Generic Contracts from PBS Source to the VM created: 2026-10-20 tags: [compiler-pbs, generic-contracts, nominal-identity, runtime-conformance] --- ## Original problem and final result Owner: `compiler/pbs`; cross-domain propagation: `compiler/general` and Studio/LSP. DSC-0089 implemented accepted DEC-0072 through PLN-0151. Those control artifacts are removed by housekeeping; the linked specifications are the operational reference. All twelve decision requirements were implemented together. PBS already supported nominal contracts and concrete implementation tables. The missing feature was a frontend path from `Identity` to exact concrete types. Simple contract names appeared in the AST, imports, validation, lowering and editor projections. Extending only the parser would have left those consumers disagreeing about the same program. The completed path is: ```text parameterized declaration + explicit application -> resolve defining declarations and logical arguments -> memoize nominal application and substitute signatures -> emit concrete Trait, implementation and function metadata -> existing PBX loader/verifier and CALL_TRAIT execution ``` There is no runtime generic-instantiation engine or new PBX/ISA category. One distinct application has one nominal Trait identity per image. Equivalent applications share it. This delivers user-defined generic contracts; collection storage and algorithms remain separate work. ## Using a strategy ```pbs declare contract Identity { fn hash(e: T) -> int; fn equals(a: T, b: T) -> bool; } declare service IntIdentity {} implements Identity 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 = IntIdentity; return identity.equals(7, 7); } ``` `IntIdentity` is the receiver; `int` describes the elements. The service keeps its singleton identity. Structs can instead provide constructed strategy instances. Contextual assignments, arguments and returns, or explicit `as`, form a view without allocating an adapter wrapper. A contract can have several ordered parameters, such as `Converter`. Applications are explicit, exact-arity and invariant. A barrel exports the declaration (`pub contract Identity;`), not one closed application. There are no raw types, contract diamond inference, default arguments, blanket generic implementations or injected direct owner methods. ## Identity is resolved before representation `PbsContractTypes` is the PBS-owned resolution and substitution boundary. Its application key contains the defining declaration and ordered canonical logical argument keys. File/source declaration identity distinguishes unrelated nominal types; length-framed child keys avoid ambiguous nested encodings. Display names and image-local numeric TypeIds are not identity keys. Imports carry a semantic `TypeBindingDecl`: the local spelling, original declaration and importing scope. The original signature keeps its lexical scope. Reexports propagate that binding rather than synthesizing a new declaration. Thus importing `Enemy as Opponent` makes `Identity` the same type as `Identity`. Two unrelated declarations both named `Enemy` remain distinct. The production multi-module fixture exercises both properties. Physical storage must follow logical resolution. `array` and `array` can share the internal Array storage carrier while still identifying different `Marker>` applications. A parameter that never occurs in a method signature still participates in identity. One owner can implement both applications; implementation function names carry the full application key. Substitution traverses arguments, arrays, Fn inputs/results, optional payloads, named tuples and nested contracts. Existing return normalization applies before signature comparison: for example, a one-field named return payload does not create a second Fn result identity. Labels and parameter names remain available for tooling. Existing restrictions still reject invalid substituted positions, including optional void, void Fn inputs and invalid Array elements. `Self` keeps its existing scope rules. ## Recursive graphs and bounded processing Register an application anchor before scanning its substituted signatures. A reference to an existing key closes a finite nominal graph; self and mutual recursion therefore terminate. A work queue discovers further instances. `Growing` returning `Growing>` continually creates new applications. It is diagnosed as `E_SEM_CONTRACT_EXPANSION`, rather than hanging or becoming an ordinary type mismatch. Analysis has explicit depth, work, instance and key storage ceilings (256, 1,048,576, 65,536 and 64 Mi characters respectively). These producer bounds do not increase runtime admission limits or replace loader accounting. ## Integration pitfalls exposed by real execution **Trait call stack order differs from implementation parameter order.** The implementation function receives its concrete owner first. At the CALL_TRAIT instruction, explicit argument groups precede the two-slot view on the operand stack. Lowering evaluates and roots the receiver, evaluates arguments left to right, then reloads the complete view immediately before the call. No-argument contract tests alone did not expose the old ordering error. **Globals have one image namespace.** Independently compiled files can each start allocating globals at slot zero. Common IR aggregation now relocates declarations and GET_GLOBAL/SET_GLOBAL operands together. Lifecycle assembly preserves those linked slots and places its initialization guard after all globals. Without this, an imported strategy singleton could collide with the guard. The fix belongs to the neutral compiler, with no PBS rule in the backend. **Aliases must cover all consumers.** Imported function emission uses the true target callable while local resolution uses its alias. Aliased services also retain their constants. Generic hover uses original declaration names in both the application heading and substituted signatures; navigation still reaches the original declaration. A final alias-specific editorial test caught a heading/signature disagreement that plain `Echo` tests did not reveal. **Verifier Unknown is not proof of a type error.** A mutated wrong-Trait call can be rejected statically or admitted with unknown local facts. In the latter case, execution must trap with the runtime type check. The conformance harness accepts exactly these valid outcomes rather than weakening runtime checks or requiring the verifier to infer more than its contract promises. ## Verification evidence Verified on 2026-10-20 against runtime revision `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, macOS/arm64, Rust 1.98.1, development profile with `resource-diagnostics`. Defaults remain unchanged except in explicit refusal tests. The harness builds in a temporary directory and does not modify the provider checkout. The fourteen mandatory generic fixtures compile actual PBS through the production frontend, typed IR, PBX emitter, loader, verifier and VM: | Fixture | Evidence | Types / implementations | PBX bytes | | --- | --- | --- | --- | | identity | Contextual/explicit adaptation and dispatch | 5 / 1 | 1,921 | | manual | Handwritten concrete behavioral reference | 5 / 1 | 1,859 | | multiple | Same owner, several applications | 6 / 2 | 1,991 | | tuple | Two parameters, Array input, complete tuple result | 9 / 1 | 2,762 | | optional | Absence/presence and optional groups | 6 / 1 | 2,267 | | function | Fn argument and call | 5 / 1 | 1,705 | | contract | Nested contract argument | 5 / 2 | 2,014 | | native | Native vec2 payload groups | 5 / 1 | 1,607 | | recursive | Finite recursive application and chained calls | 4 / 1 | 1,791 | | phantom | Distinct logical Array arguments, identical signatures | 5 / 2 | 2,036 | | receiver | Constructed struct receiver state | 4 / 1 | 1,534 | | gc | Closure retains view/receiver through collection | 7 / 1 | 2,153 | | installed | Packaged runnable contracts example | 5 / 1 | 2,105 | | imports | Aliases/reexports, distinct origins, lifecycle globals | 5 / 3 | 2,540 | The generic and handwritten references both succeed with one heap handle and equal guest allocation footprint. Typed absence and ImplementationId zero are checked separately. The GC fixture reclaims at least 1,100 discarded objects while the captured receiver remains callable. Reduced GuestBytes/HandleSlots and zero implementation admission test resource refusal, bounded publication and complete ownership release. These observations do not imply identical PBX bytes or a performance improvement. The complete provider harness also passed the existing source/input, structured value, closure, math, Random, lifecycle, malformed-image and resource corpora. Its two previously documented upstream schema enum gaps remain explicitly reported; they are not hidden or counted as schema conformance. Compiler API (29 tests), PBS frontend (274 tests) and build-pipeline suites passed, together with 68 affected architecture tests, 22 LSP bridge/protocol tests and both installed knowledge tests. The build-pipeline suite retains twelve pre-existing disabled legacy integration cases; production fixtures exercise the required paths. Additional focused cases cover mutual recursion and imported alias navigation. Workflow validation and whitespace checks passed before completion. Reproduce with the gates in the [conformance harness documentation](../../../../tooling/scripts/pbx-conformance/README.md). The new specification and `contracts.pbs` example are discoverable in installed knowledge, not only in the source checkout. ## Handoffs and references AGD92/List is next in the umbrella sequence. SDK data/algorithm specialization and stable object-identity hashing still require their consumer decisions. Generic functions/structs, constraints, variance, inheritance/default methods, associated strategy members and runtime specialization were not introduced. - [PBS generic contracts specification](../../../docs/specs/compiler-languages/pbs/16.%20Generic%20Contracts%20Specification.md). - [Typed Registry/PBX and global relocation](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md). - [Arrays, optional and contract execution](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md). - [Functions and captures](../../../docs/specs/compiler-languages/pbs/15.%20First-Class%20Functions%20and%20Captures%20Specification.md). - [Installed source example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/contracts.pbs). - Historical workflow: AGD-0091, accepted DEC-0072, completed PLN-0151; DSC-0089.