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.
@@ -189,3 +189,10 @@ Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(
Contract declarations and barrel items preserve ordered type-parameter names and individual spans. Applied type references preserve ordered child arguments and spans. Implements and as carry a complete target type reference. Semantic imported bindings retain the original declaration and importing lexical scope rather than inventing nominal origins. Existing visitors must traverse type arguments as well as inner/group/Fn/tuple children.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
## Concrete generic structs and free functions
Structs and free functions preserve ordered parameter declarations and spans. Explicit applied function references preserve type arguments and their source span. Implements preserves its binder, full applied owner and target. Substitution rewrites every field, signature, annotation and executable body/capture position with a declaration-local environment. Concrete application provenance retains original declaration, canonical logical arguments and requesting use; it is not an executable runtime template.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
@@ -313,3 +313,10 @@ Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(
Parameterized contract diagnostics distinguish exact arity (E_SEM_CONTRACT_ARITY), undeclared/duplicate parameters (E_SEM_CONTRACT_PARAMETER), invalid applications (E_SEM_CONTRACT_ARGUMENT), incompatible or incomplete implementations (E_SEM_CONTRACT_SIGNATURE), duplicate pairs (E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION), invalid owners/modules (E_SEM_CONTRACT_OWNER / E_SEM_CONTRACT_OWNER_MODULE), invalid coercions (E_SEM_CONTRACT_COERCION), and bounded expansion/resource exhaustion (E_SEM_CONTRACT_EXPANSION). Barrel parameter disagreement uses E_LINK_CONTRACT_PARAMETERS. Existing invalid Array/Fn/optional/Self diagnostics also apply after substitution.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
## Concrete generic structs and free functions
Generic diagnostics distinguish duplicate/unbound parameters, exact arity, raw or improperly inferred application, unjustified symbolic capabilities, invalid substituted positions, constructor errors, collapsed overloads, invalid bound owners, overlap and bounded expansion. Preserve declaration and requesting-use locations with a short instantiation chain. Editor projections retain symbolic parameter, concrete argument and generic origin identities. Generated instance names and host stacks do not replace source explanations.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
@@ -255,3 +255,10 @@ Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(
The frontend substitutes each closed application and emits a concrete nominal Trait descriptor shared by equivalent uses. Distinct logical applications remain distinct despite shared physical carriers. Concrete implementation functions take the receiver first. CALL_TRAIT evaluates and roots the receiver before arguments, evaluates arguments left to right, then places the complete receiver/ImplementationId view after the argument groups as required by the runtime ABI. Preserve exact signatures, absence, ImplementationId zero, ownership, GC and quotas; generic calls do not add a Dynamic ABI or adaptation wrapper.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
## Concrete generic structs and free functions
Instantiate structs, free functions and owner-bound implementations within PBS before publishing executable descriptors. Registry receives concrete fields, signatures, bodies, capture groups and targets. Specialized free-function references use existing empty-environment Closure values; Fn remains structural. Preserve receiver identity, implementation zero, singletons, rooting, GC, ownership, evaluation/fault order and quotas. No generic Dynamic/boxing ABI, opcode, descriptor category or runtime instantiation engine is introduced.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
@@ -165,8 +165,8 @@ BarrelItem ::= BarrelFnItem
| BarrelConstItem
BarrelVisibility ::= 'mod' | 'pub'
BarrelFnItem ::= BarrelVisibility 'fn' Identifier ParamList ReturnAnn? ';'
BarrelStructItem ::= BarrelVisibility 'struct' Identifier ';'
BarrelFnItem ::= BarrelVisibility 'fn' Identifier TypeParameters? ParamList ReturnAnn? ';'
BarrelStructItem ::= BarrelVisibility 'struct' Identifier TypeParameters? ';'
BarrelContractItem ::= BarrelVisibility 'contract' Identifier TypeParameters? ';'
BarrelHostItem ::= BarrelVisibility 'host' Identifier ';'
BarrelErrorItem ::= BarrelVisibility 'error' Identifier ';'
@@ -280,7 +280,7 @@ Top-level `let` forms and top-level executable statements are forbidden.
```ebnf
TypeDecl ::= StructDecl | ServiceDecl | ContractDecl | HostDecl | BuiltinTypeDecl | ErrorDecl | EnumDecl
StructDecl ::= 'declare' 'struct' Identifier '(' StructFieldList? ')' (StructMethodBody | ';')
StructDecl ::= 'declare' 'struct' Identifier TypeParameters? '(' StructFieldList? ')' (StructMethodBody | ';')
ServiceDecl ::= 'declare' 'service' Identifier ServiceBody
ContractDecl ::= 'declare' 'contract' Identifier TypeParameters? ContractBody
TypeParameters ::= '<' Identifier (',' Identifier)* '>'
@@ -390,7 +390,7 @@ Rules:
### 7.4 Functions
```ebnf
FunctionDecl ::= 'fn' Identifier ParamList ReturnAnn? Block
FunctionDecl ::= 'fn' Identifier TypeParameters? ParamList ReturnAnn? Block
ParamList ::= '(' (Param (',' Param)*)? ')'
Param ::= Identifier ':' TypeRef
ReturnAnn ::= '->' ReturnSpec
@@ -467,7 +467,7 @@ Rules:
- Named tuple arity is 1..6 in v1 core syntax.
- Tuple types in PBS core are always named.
- Single-slot tuple types are allowed only in type/signature surface, not as tuple literals.
- User-defined parameterized declarations are supported for contracts. General generic structs and functions remain outside PBS core v1.
- User-defined parameterized declarations are supported for contracts. Generic structs and explicit generic free functions follow the concrete generic application extension linked below.
- `SimpleType` may denote either a visible nominal type identifier or one of the predeclared builtin simple types.
- The predeclared builtin simple types in v1 core are `int`, `float`, `bool`, and `str`.
- Builtin simple types are always available in type position and do not require import.
@@ -574,10 +574,10 @@ ArgList ::= Expr (',' Expr)*
Literal ::= IntLit | FloatLit | StringLit | BoolLit
BoolLit ::= 'true' | 'false'
PrimaryExpr ::= Literal | Identifier | ThisExpr | NewExpr | LambdaExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block
PrimaryExpr ::= Literal | Identifier TypeArguments? | ThisExpr | NewExpr | LambdaExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block
ThisExpr ::= 'this'
NewExpr ::= 'new' NewTarget '(' ArgList? ')'
NewTarget ::= Identifier ('.' Identifier)?
NewTarget ::= Identifier (TypeArguments | '<' '>')? ('.' Identifier)?
LambdaExpr ::= 'fn' '[' CaptureNames? ']' ParamList '->' TypeRef Block
CaptureNames ::= Identifier (',' Identifier)*
FnType ::= 'Fn' '(' (TypeRef (',' TypeRef)*)? ')' '->' TypeRef
@@ -1211,3 +1211,10 @@ Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(
Parameterized contracts use explicit angular arguments in annotations, nested types, implements and as. Barrels export the ordered parameter list. Raw generic uses, empty argument lists and default arguments are invalid; existing contextual closers and Array construction sugars remain unchanged.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
## Concrete generic structs and free functions
Struct and module-level free-function declarations and their barrel items accept ordered type parameters. Explicit function applications are reference expressions; calls use existing parentheses/apply. Generic construction supports explicit arguments and contextual diamond/omission. Owner-bound `implements` accepts its own parameter binder and a full applied owner. Independent method parameters, function diamond/inference and polymorphic Fn remain invalid. The owner specification defines exact arity, comparison disambiguation and recovery.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
@@ -830,3 +830,10 @@ Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(
Application identity combines the defining nominal declaration with ordered canonical logical arguments after alias resolution. Applications are invariant. Substitution preserves existing type-position restrictions, names, labels and complete groups across Array, Fn, optional, tuples and nested contracts. A struct/service may implement several applications, with complete unique implementations in its owner module. Finite instance recursion is accepted within resource limits; unbounded expansion receives a bounded diagnostic.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
## Concrete generic structs and free functions
Templates are checked symbolically in definition scope. Required concrete owners validate all methods and constructors, including unused methods. Substitute complete bodies and applied Self; preserve position restrictions, invariant nominal/phantom identity and logical groups. Explicit function applications filter generic overloads by type arity; ordinary calls never infer them. Bound owner implementations require complete exact signatures and symbolic overlap rejection before use. Finite recursive applications are anchored; expanding type/body families are bounded errors.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
@@ -563,3 +563,10 @@ new coverage; existing behavior MUST NOT regress.
A barrel exports a parameterized contract declaration with the same ordered parameters as its source declaration. Imported bindings retain the original declaration and lexical source scope, including aliases in signatures of dependencies. A local alias never creates another nominal type. Implementations remain in the declaring module of the concrete struct/service owner.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
## Concrete generic structs and free functions
Generic struct/function barrels export declarations and ordered parameters, including complete function signatures, rather than enumerated specializations. Imports and aliases preserve nominal origins and definition-scoped bodies/private helpers. Specializations are shared across equivalent uses and do not export private dependencies. SDK and program sources use the same language machinery.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).