203 lines
12 KiB
Markdown
203 lines
12 KiB
Markdown
---
|
||
id: LSN-0089
|
||
ticket: pbs-generic-structs
|
||
title: Concrete Generic State and Bodies in PBS
|
||
created: 2026-10-22
|
||
tags: [compiler-pbs, generic-structs, generic-functions, nominal-identity, runtime-conformance]
|
||
---
|
||
|
||
## Original problem and final result
|
||
|
||
Owner: `compiler/pbs`. Studio/LSP receives source projections; the common backend
|
||
and runtime continue to execute concrete types and functions. DSC-0094 implemented
|
||
accepted DEC-0073 through PLN-0152, covering requirements R1–R14. The disposable
|
||
workflow artifacts are removed by housekeeping; specifications remain normative.
|
||
|
||
Generic contracts could describe a strategy but could not provide parameterized
|
||
state or algorithms. PBS now supports generic structs, owner-dependent methods
|
||
and constructors, restricted owner-bound implementations, and named generic free
|
||
functions with explicit arguments. SDK and project code use the same frontend
|
||
mechanism. No runtime source, opcode, descriptor category or PBX format changed.
|
||
|
||
```pbs
|
||
declare struct Box<T>(value: T) {
|
||
ctor make(value: T) { this.value = value; }
|
||
fn get() -> T { return this.value; }
|
||
}
|
||
declare contract Reader<T> { fn read() -> T; }
|
||
implements<T> Reader<T> for Box<T> using box {
|
||
fn read() -> T { return box.get(); }
|
||
}
|
||
fn read<T>(reader: Reader<T>) -> T { return reader.read(); }
|
||
fn example() -> int {
|
||
let box = new Box<int>.make(42);
|
||
let reader: Reader<int> = box;
|
||
let invoke: Fn(Reader<int>) -> int = read<int>;
|
||
return invoke(reader);
|
||
}
|
||
```
|
||
|
||
The combined program executes through production PBX and the provider VM. A
|
||
separate multi-module variant uses aliases, reexports and private definition-side
|
||
helpers while preserving the result 42.
|
||
|
||
## Decisions that shape the implementation
|
||
|
||
Application identity is source nominal origin plus ordered canonical logical
|
||
arguments. It is independent of layout width and presentation. Two homonymous
|
||
Enemy declarations must yield distinct Box<Enemy> types; two aliases of the same
|
||
declaration share one application. Phantom arguments also remain significant.
|
||
Function applications preserve their declaration and argument identity even when
|
||
several targets share a compatible structural Fn descriptor.
|
||
|
||
Definition scope and argument scope are separate. A parameter is bound by its
|
||
declaration/binder and position. Resolve the caller's arguments before constructing
|
||
the callee's substitution environment. Private helpers remain in their definition
|
||
module. Generated imports connect concrete instances without publishing helpers
|
||
as source exports. Explicit barrels retain the template and its ordered parameters.
|
||
|
||
Explicit struct construction provides its own arguments. Diamond and omission
|
||
require an existing expected application; values do not infer T. Generic functions
|
||
always require explicit arguments, including when converted to Fn. Explicit
|
||
applications filter generic overloads by type arity; ordinary calls use ordinary
|
||
overloads. Renaming binders alone does not create a new overload.
|
||
|
||
Concrete specialization increases frontend work and potentially image size, but
|
||
reuses the established runtime value model. It avoids requiring a Dynamic generic
|
||
argument ABI or adapter objects. Existing Array packing still follows Array rules.
|
||
No performance or byte-for-byte image equivalence is promised.
|
||
|
||
## Checking and materializing the graph
|
||
|
||
`PbsGenericInstantiation` owns the interacting concrete graph. Shared
|
||
`PbsContractTypes`, `PbsInstantiationBudget` and application provenance support
|
||
contracts, structs and functions. Register anchors before traversing dependencies:
|
||
revisiting the same application closes a finite graph, whereas requesting new
|
||
applications indefinitely produces a bounded expansion diagnostic.
|
||
|
||
The current frontend budget bounds depth at 256, instances at 65,536, work at
|
||
1,048,576 visits and accounted specialization storage at 64 MiB. These analysis
|
||
ceilings do not enlarge provider admission or execution limits.
|
||
|
||
Validation has two distinct purposes. Symbolic capability checking prevents T
|
||
from gaining arithmetic, comparison, members or construction from a chosen concrete
|
||
argument. Opaque nominal witnesses also run unused template bodies through the
|
||
ordinary declaration and flow validators, catching ordinary errors such as wrong
|
||
returns and incomplete constructors. Dependency shapes provide their declared
|
||
capabilities without recursively executing every unused template family.
|
||
|
||
Each required concrete owner then validates fields, constructors and every method,
|
||
including uncalled methods. Substitute entire bodies, annotations, nested calls,
|
||
constructions, lambdas and captures. Revalidate positions after substitution:
|
||
Box<optional int> can have a T field, but array<T> cannot accept that substitution.
|
||
Reject overloads that collapse after substitution; never prefer an int overload
|
||
over set(T) merely because T became int.
|
||
|
||
Owner-bound implementation rules bind every parameter through distinct direct
|
||
owner arguments. Symbolic unification detects generic/generic, generic/closed and
|
||
closed/closed overlap before any conflicting application is requested. A closed
|
||
rule has no priority over a family. Implementations remain exact and module-owned;
|
||
their methods do not enter the struct's direct method namespace.
|
||
|
||
Specialized free-function references use ordinary Closure values with empty
|
||
environments. Lambdas inside specialized bodies keep explicit snapshot captures
|
||
and complete logical groups. Struct values retain reference identity; assignment
|
||
does not copy their state.
|
||
|
||
## Constructor initialization and Random
|
||
|
||
Implementation exposed a conflict: the static semantics required every field
|
||
initialized on each completing constructor path, while Random fixtures used an
|
||
empty constructor to obtain the provider's null reference default. The user
|
||
explicitly chose complete initialization and authorized revising Random's spec
|
||
and fixtures. This clarification applies to ordinary and generic structs.
|
||
|
||
The flow check intersects assignments across branches and accounts for loop exits
|
||
and short-circuit logical operands.
|
||
An assignment in a loop that might run zero times is insufficient. Deferred lambda
|
||
bodies do not initialize the enclosing constructor's fields. A constructor that
|
||
cannot complete has no completing path to check.
|
||
|
||
Valid Random source fixtures now initialize their fields explicitly. Four null
|
||
and typed-null checks remain controlled provider fixtures: compile valid source,
|
||
suppress the unique named-constructor field store in test bytecode, then run the
|
||
production verifier/VM. Runtime field defaults, typed Array presence and null
|
||
faults are still tested without making incomplete PBS constructors legal.
|
||
|
||
## Editor and diagnostic projections
|
||
|
||
Keep original declarations and spans alongside the specialized semantic projection.
|
||
Navigation and references distinguish symbolic parameters, concrete arguments and
|
||
generic origins. Concrete hover/completion/signature help use the applied type;
|
||
template bodies retain symbolic field and method presentation. Source formatting,
|
||
document/workspace symbols, rename references, inline hints and semantic overlays
|
||
continue through the existing frontend/LSP surfaces.
|
||
|
||
Pass the current application into declaration and flow diagnostics. Merely replacing
|
||
generated names at file scope is insufficient: field-position errors also need
|
||
related spans for the original definition and requesting use. Display a short
|
||
source chain and canonical application names rather than internal identities.
|
||
|
||
## Qualification and requirement coverage
|
||
|
||
The final reports contain 1,004 general tests, zero failures/errors and 13 existing
|
||
skips, plus two passing installed-knowledge tests. The complete Gradle regression
|
||
passed; final affected gates were repeated after improving diagnostic provenance
|
||
and finalizing installed spec references. One earlier external-source LSP failure
|
||
passed in isolation and in the complete repetition; no unrelated LSP code changed.
|
||
|
||
Production qualification used runtime revision
|
||
`f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, Rust 1.98.1, macOS arm64, dev profile,
|
||
`resource-diagnostics`, default limits and `NONE` capabilities, with explicitly
|
||
lowered quota cases. All 16 mandatory generic fixtures passed. The full existing
|
||
PBX harness also passed, including 227 Random cases. This evidence does not qualify
|
||
another platform, a release runtime profile or the reference game.
|
||
|
||
| Requirements | Final evidence |
|
||
| --- | --- |
|
||
| R1–R2 | Exact arguments, origin/phantom/reference identity, contextual and named construction, complete initialization |
|
||
| R3–R5 | Composed multi-slot storage, symbolic capability errors, complete bodies, unused-method and overload failures |
|
||
| R6–R7 | Restricted coherent owner rules, overlap before use, anchored recursion and bounded expanding bodies |
|
||
| R8 | Production concrete Registry/PBX/VM, implementation zero, retained captures through GC and quota refusals |
|
||
| R9–R10 | Explicit free functions, concrete Fn/empty closures, nested captures and ordinary apply |
|
||
| R11–R12 | Homonymous binders/origins, definition-side helpers, aliases/reexports, barrels, duplicates and comparisons |
|
||
| R13 | Symbolic/concrete navigation and editor tests; diagnostic definition/use spans and readable applications |
|
||
| R14 | Shared infrastructure, isolated/combined modules, installed example/specs and complete regressions |
|
||
|
||
The 16 fixtures cover basic/manual objects, constructors/Self, phantom applications,
|
||
tuple, optional, Array, nominal recursion, combined dispatch, generic/manual Fn,
|
||
GC, imports/reexports, installed example, multiple parameters and homonymous origins.
|
||
Specialized and handwritten object/Fn fixtures execute under a one-handle limit
|
||
and use equal guest heap resources. All observed resources return to zero after
|
||
VM disposal. Refused allocation publishes no partial object. Full fixture sizes,
|
||
type/implementation counts, hashes, commands and log fingerprints are retained in
|
||
[evidence.json](evidence.json).
|
||
|
||
## Pitfalls and subsequent work
|
||
|
||
- Checking only requested templates or called methods changes source acceptance.
|
||
- Rewriting only signatures loses local annotations, construction contexts and captures.
|
||
- Using simple names or physical slots as identity merges distinct applications.
|
||
- Resolving private helpers at the caller makes imports change template meaning.
|
||
- Choosing a closed implementation over a family hides an incoherent program.
|
||
- Treating a provider's reference default as a PBS constructor exemption creates
|
||
incompatible source rules.
|
||
- Maintaining normative chapters in both `docs/specs/compiler-languages/pbs` and
|
||
`docs/compiler/pbs/specs` permits contradictions. The canonical owner is the
|
||
latter; existing distribution still merges both roots. Consolidating the legacy
|
||
chapters and their links/build inputs remains a separate repository migration.
|
||
|
||
The next collection discussion is List (DSC-0090 / AGD-0092). Its API, iteration,
|
||
logical bounds and private slot-transfer decisions remain open. Completing this
|
||
language prerequisite does not approve those collection proposals.
|
||
|
||
## References
|
||
|
||
- [Generic structs and free functions](../../../docs/specs/compiler-languages/pbs/17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
|
||
- [Generic contracts](../../../docs/specs/compiler-languages/pbs/16.%20Generic%20Contracts%20Specification.md).
|
||
- [Arrays and optional](../../../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).
|
||
- [Random integration](../../../docs/specs/compiler-languages/pbs/20.%20Runtime%20Random%20Integration%20Specification.md).
|
||
- [Concrete common Registry/PBX](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md).
|
||
- Historical execution plan: PLN-0152, completed and removed by discussion housekeeping.
|