Files
prometeu-studio/docs/compiler/pbs/specs/generic-structs-and-free-functions.md
T
bquarkz 01a1968689
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
feat(pbs): add Map and read-only Keyval associations
2026-10-26 20:37:06 +00:00

14 KiB

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.

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

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.

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, for example, produces optional T. Additional capabilities require explicit composition:

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 inside that application and Box 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

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>, 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(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(value:T) and f(value:U) are duplicates when otherwise signature-equivalent. Substituted collisions in the filtered generic candidate set are errors.

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.

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, Reader, owner-bound implements, read, read 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.