feat(pbs): add parametric arrays and concrete generic contracts
Support explicit contract type parameters, canonical nominal applications, recursive substitution, concrete implementations and instantiated editor views. Complete parametric Array syntax and contextual construction integration. Preserve type origins across imports and reexports, fix trait argument stack order, and relocate global slots before lifecycle assembly. Publish specs, installed examples and consolidated discussion lessons. Validate frontend, common pipeline, architecture, LSP and installed knowledge gates, plus the full production VM conformance corpus with 14 generic fixtures.
This commit is contained in:
@@ -42,6 +42,12 @@ identities, excluding names. Forward references and recursion through nominal
|
||||
anchors are valid. Pure Array/Fn cycles are invalid. Every reference must
|
||||
resolve before emission. Frontends should supply only used imports.
|
||||
|
||||
File-local global slots MUST be relocated to unique image-wide slots when common
|
||||
IR files are merged. Every GET_GLOBAL and SET_GLOBAL operand must use the same
|
||||
relocation as its declaration. Lifecycle assembly preserves those linked slots
|
||||
and allocates its initialization guard after all existing image globals. Module
|
||||
boundaries do not create separate runtime global namespaces.
|
||||
|
||||
| BuiltinId | Type | Slots |
|
||||
| --- | --- | --- |
|
||||
| `0x0001` | color | 1 |
|
||||
|
||||
@@ -19,7 +19,7 @@ fn example() -> int {
|
||||
}
|
||||
```
|
||||
|
||||
Function-returning functions use `-> Fn(int) -> int`. Function array elements use grouping, for example `array (Fn(int) -> int)`. Existing array vacancy and optional-read rules apply; accessing an empty slot does not fabricate a callable.
|
||||
Function-returning functions use `-> Fn(int) -> int`. Function array elements use grouping, for example `array<(Fn(int) -> int)>`. Existing array vacancy and optional-read rules apply; accessing an empty slot does not fabricate a callable.
|
||||
|
||||
## Lambdas
|
||||
|
||||
@@ -76,3 +76,8 @@ Function creation and calls remain subject to existing resource checks and runti
|
||||
Conformance must compile actual PBS through production PBX and execute it in the production VM. Required cases include signature errors, explicit capture enforcement, snapshots, escaped closures, shared and isolated objects, collection transport, nested closures and function captures, receiver/contract integration, and reachable/unreachable closure behavior across the existing frame lifecycle and GC. Installed knowledge must package this specification and a compilable example.
|
||||
|
||||
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# PBS Generic Contracts
|
||||
|
||||
Owner: `compiler/pbs`. This specification extends nominal contracts with explicit type parameters. Registry, PBX, instruction, ownership and resource contracts remain governed by the runtime provider. Collections and object-identity hashing are separate consumers.
|
||||
|
||||
## Declaration and application
|
||||
|
||||
```pbs
|
||||
declare contract Identity<T> {
|
||||
fn hash(e: T) -> int;
|
||||
fn equals(a: T, b: T) -> bool;
|
||||
}
|
||||
|
||||
declare contract Converter<A, B> {
|
||||
fn convert(value: 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.
|
||||
|
||||
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.
|
||||
|
||||
## Identity and compatibility
|
||||
|
||||
An application's identity is the defining nominal contract declaration plus its ordered canonical logical argument identities. Import aliases resolve before this identity is formed. If `Opponent` aliases the same `Enemy` declaration, `Identity<Opponent>` and `Identity<Enemy>` are identical. Equal names, method shapes or physical layouts do not merge different declarations or applications. Phantom arguments still distinguish applications.
|
||||
|
||||
Applications are invariant. A conversion between argument types does not establish a conversion between their contract applications. Existing explicit reference-view conversion can select another implementation actually supplied by the concrete receiver; it does not manufacture variance.
|
||||
|
||||
## Substitution and composition
|
||||
|
||||
Substitution traverses every type position in each signature, preserving parameter names, tuple labels, order and source provenance. It supports valid composition with existing builtins, nominal values, arrays, other applied contracts, Fn, optional and named tuples. Each resulting position remains subject to the existing type, return, optional/result and storage rules; substitution does not legalize an otherwise invalid position.
|
||||
|
||||
Normalize substituted signatures before deriving physical parameter/result groups. One logical parameter can contain several physical values. A shared physical carrier does not erase logical argument identity: distinct `Identity<array<X>>` applications remain nominally distinct even when their arrays share internal storage representation.
|
||||
|
||||
## Implementations and values
|
||||
|
||||
```pbs
|
||||
declare service IntIdentity {}
|
||||
|
||||
implements Identity<int> 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<int> = IntIdentity;
|
||||
return identity.equals(7, 7);
|
||||
}
|
||||
```
|
||||
|
||||
Structs and services are the supported owners. An implementation belongs to the owner's declaring module and follows existing visibility rules. Implementations are complete and unique per `(owner, instantiated contract)`. One owner may implement several applications of the same contract. Implementation/callable identities include the full application, preventing collisions between those methods. Contract methods are not injected into the direct method namespace of their owner.
|
||||
|
||||
Named service singletons and constructed struct values supply strategies. Contextual assignments, arguments and returns, and explicit `value as Identity<int>`, select the concrete implementation. Conversion preserves the receiver and selected implementation without allocating an adapter wrapper or duplicating a singleton. Associated members such as `Enemy.identity` are not introduced.
|
||||
|
||||
## Recursion and bounded analysis
|
||||
|
||||
Register a nominal application anchor before expanding its signatures. A recurrence to an existing key forms a finite graph and is valid within existing resource limits. An application family that continually introduces new arguments, such as `Growing<T>` returning `Growing<array<T>>`, must be rejected with a clear expansion diagnostic.
|
||||
|
||||
Expansion, substitution and identity processing are bounded in work, storage and depth. Resource exhaustion and nonterminating specialization must not become hangs, host stack overflows, missing-method errors or ordinary argument-mismatch diagnostics.
|
||||
|
||||
## Execution and tooling
|
||||
|
||||
The frontend emits a concrete nominal Trait descriptor for each distinct required application, sharing the descriptor for equivalent uses across modules. Open type parameters do not reach executable signatures. Implementation functions receive the concrete owner first, followed by complete substituted argument/result groups.
|
||||
|
||||
Existing Registry/PBX and `REF_TO_TRAIT`/`CALL_TRAIT` mechanisms execute these records. Preserve typed absence, valid ImplementationId zero, receiver identity, rooting, GC, native ownership and quotas. Generic calls do not introduce a Dynamic argument ABI or boxing merely because an argument was a type parameter. Existing storage-specific packing remains governed by that storage's contract.
|
||||
|
||||
Navigation reaches generic declarations, parameters and argument declarations. Hover, completion and signature help show instantiated signatures with canonical source names. Arity, unresolved parameters, invalid applications/coercions, incomplete or duplicate implementations and expansion failures have localized diagnostics. Compilation and editor projections share the same type resolution.
|
||||
|
||||
## Conformance
|
||||
|
||||
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.
|
||||
@@ -4,20 +4,28 @@ Owner: `compiler/pbs`. This specification defines the source contract for typed
|
||||
|
||||
## Types and construction
|
||||
|
||||
`array T` denotes a fixed-length reference to positions holding values of T or no value. `array[N] T` denotes N nested array levels, where N is a positive integer literal. `array[1] T` and `array T` are equivalent. Depth belongs to the type; allocation length belongs to the constructor. The compiler bounds expanded type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST.
|
||||
`array<T>` denotes a fixed-length reference to positions holding values of T or no value. Nesting is compositional: `array<array<Enemy>>` holds array references. The compiler bounds structural type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST. Allocation length belongs to the constructor, not the type.
|
||||
|
||||
```pbs
|
||||
let enemies: array Enemy = new array(10);
|
||||
let groups: array[2] Enemy = new array(3);
|
||||
let scores: array int = [10, 20, 30];
|
||||
let empty: array Enemy = [];
|
||||
let enemies = new array<Enemy>(10);
|
||||
let contextual: array<Enemy> = new array<>(10);
|
||||
let omitted: array<Enemy> = new array(10);
|
||||
let groups: array<array<Enemy>> = new array<>(3);
|
||||
let scores: array<int> = [10, 20, 30];
|
||||
let empty: array<Enemy> = [];
|
||||
```
|
||||
|
||||
`new array(length)` requires an expected array type. It allocates only the outer array: each position is empty, with no implicit subarray, element construction or callback. Every array literal, including a nonempty literal, requires an expected array type. The compiler must not infer an array type from its elements. Expected types propagate through annotated bindings, assignments, parameters, returns and nested value expressions. Incompatible elements are errors; they do not produce a public Dynamic type.
|
||||
`new array<T>(length)` supplies its own type, including when the binding has no annotation. T must resolve to a valid element type. `new array<>(length)` and `new array(length)` are equivalent sugars requiring an expected array type. The length never supplies element-type information. All forms allocate only the outer array: each position is empty, with no implicit subarray, element construction or callback.
|
||||
|
||||
Arrays are invariant in element type and depth. Assignment and argument passing share the array reference. The runtime's shared storage carrier must not make different PBS array types interchangeable. `array (optional T)` is invalid, including through grouped types. `optional (array T)` remains valid and distinguishes an absent array from a present array whose positions are empty.
|
||||
Every array literal, including a nonempty literal, requires an expected array type. The compiler must not infer its type from its elements. Expected types propagate through annotated local/global bindings, assignments, arguments with a resolved single callable signature, returns and nested value expressions. This migration does not expand overload resolution; contextual construction without sufficient expected type is an error. Incompatible explicit constructor types and literal elements are errors; they do not produce a public Dynamic type.
|
||||
|
||||
`T[]`, `[]T`, `array !! T`, `new T[n]` and `new array[n]` are not alternative spellings. PBS exposes neither a null value nor a Dynamic type.
|
||||
Arrays are invariant in element type and nesting. Assignment and argument passing share the array reference. The runtime's shared storage carrier must not make different PBS array types interchangeable. `array<optional T>` is invalid, including through grouped types. `optional (array<T>)` remains valid and distinguishes an absent array from a present array whose positions are empty.
|
||||
|
||||
Type delimiters can be adjacent to assignment: `let a: array<array<int>>=new array<>(3);` is valid. Parsing consumes type closers contextually while preserving expression comparisons such as `x >= y`. This does not introduce shift operators. Optional, `result<Error>` and `Fn(...) -> ...` retain their existing spellings.
|
||||
|
||||
Legacy `array T`, `array[N] T`, and `array<T>[N]` are rejected. `T[]`, `[]T`, `array !! T`, `new T[n]` and `new array[n]` are not alternative spellings. PBS exposes neither a null value nor a Dynamic type.
|
||||
|
||||
The frontend AST retains recursive element types and their spans. Constructor nodes distinguish explicit type arguments, diamond and omission; explicit construction types must reach semantic analysis, source tooling and PBS lowering without relying on a destination annotation. Common backend IR and runtime storage do not acquire PBS syntax rules.
|
||||
|
||||
## Operations and ordering
|
||||
|
||||
@@ -62,7 +70,7 @@ Existing PBS struct and contract rules apply unchanged: structs have reference i
|
||||
|
||||
## Diagnostics, tooling and conformance
|
||||
|
||||
Diagnostics must reject missing expected array types, invalid depth, optional elements, incompatible invariant arrays, non-integral sizes/indices and non-optional if-let operands. Editor types and hints use PBS array notation. Hover, completion, definitions, references and rename must respect success-only binding scope and source element identity.
|
||||
Diagnostics must reject missing expected array types for contextual construction, unresolved explicit element types, excessive nesting, removed syntax, optional elements, incompatible invariant arrays, non-integral sizes/indices and non-optional if-let operands. Editor types and hints use PBS array notation. Hover, completion, definitions, references and rename must respect success-only binding scope and source element identity.
|
||||
|
||||
Conformance must compile real PBS through typed IR and production PBX into the production loader/VM. Required cases include vacancy versus zero, alias mutation, contextual literals, nested arrays, int/long bounds, lazy and single evaluation, multi-slot groups, constructors and contract dispatch, service identity, resource refusal and GC/ownership. Assembly-only probes are insufficient. Installed knowledge must package this specification and executable examples.
|
||||
|
||||
@@ -76,3 +84,8 @@ Conformance must compile real PBS through typed IR and production PBX into the p
|
||||
List/Set/Map, growth, iteration, equality and hashing policies belong to the separate SDK collections discussion. A future list capacity does not create logical elements; fixed array length does.
|
||||
|
||||
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
Reference in New Issue
Block a user