feat(pbs): add concrete generic structs and free functions

This commit is contained in:
2026-10-22 14:42:38 +01:00
parent 240216170c
commit 76a8b074e8
52 changed files with 3285 additions and 103 deletions
@@ -81,3 +81,9 @@ See [Runtime Random integration](runtime-random-integration.md) for opaque gener
## Parameterized contract integration
[Generic contracts](generic-contracts.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](generic-structs-and-free-functions.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.
+2 -2
View File
@@ -17,7 +17,7 @@ declare contract Converter<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.
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](generic-structs-and-free-functions.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.
@@ -71,4 +71,4 @@ Navigation reaches generic declarations, parameters and argument declarations. H
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, bounds, variance, inheritance/default methods, generic reflection, runtime instantiation and collection algorithms are outside this extension.
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](generic-structs-and-free-functions.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,271 @@
# Concrete Generic Structs and Free Functions
Owner: `compiler/pbs`. 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.
## 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](runtime-random-integration.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](generic-contracts.md).
- [Typed arrays and optional execution](typed-arrays-and-optional-execution.md).
- [First-class functions and captures](first-class-functions-and-captures.md).
- [Concrete Registry and PBX handoff](../../general/specs/typed-registry-and-pbx-v0.md).
@@ -35,7 +35,7 @@ Assignment, parameter passing, returns and capture copy a reference to the same
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, including an uninitialized Random field in an explicitly invoked ordinary struct constructor. Existing global-initializer restrictions remain unchanged; an unsupported arbitrary call in a global initializer does not become legal because it returns Random.
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.
@@ -56,11 +56,11 @@ The source corpus MUST run the production PBS → common IR → PBX → runtime
- 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, typed null and retained roots across collection;
- unit/extreme intervals, excluded upper bound, invalid bounds, null receiver and real rejection followed by acceptance;
- 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.
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.
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
@@ -89,3 +89,8 @@ See [Runtime Random integration](runtime-random-integration.md) for opaque gener
## Parameterized contract integration
[Generic contracts](generic-contracts.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](generic-structs-and-free-functions.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.