Skip to content

Fix sema generic type instantiation (TY_GENERIC_INST erasure) — prerequisite for stdlib-as-generics #391

Closed

Description

@ehartford

Summary

Fix generic type instantiation as a compiler-wide foundation before expanding stdlib generics. The target outcome is that Vec[i32], Vec[str], HashMap[str, i32], and user generic instantiations remain semantically distinct through sema, MIR, codegen, trait selection, and diagnostics.

Spec

§11.2 says unbounded generics are checked when instantiated with concrete types: unsupported operations should name the concrete type and instantiation. §13.2/§13.3 rely on ordinary generic iterator adapters and consumers rather than compiler-built intrinsics for every collection operation.

Current state

There is now real TY_GENERIC_INST infrastructure: Sema.ensure_generic_inst_type interns base+arg instantiations at src/Sema.w:1962-1974, resolve_generic_type builds them from type syntax at src/Sema.w:2082-2119, and compatibility compares generic args at src/Sema.w:3153-3166 and src/Sema.w:3223-3235.

The remaining root debt is the erasure compatibility escape hatch and downstream reliance on builtin container knowledge. types_compatible_fast still treats a generic instantiation as compatible with its base struct/enum by base symbol alone at src/Sema.w:3167-3175, and the slower compatibility path does the same at src/Sema.w:3236-3242. Large parts of method checking still special-case builtin generic containers by name and pull element/key/value types manually (src/SemaCheck.w:10736-10835). This is the pattern that makes stdlib issues depend on this keystone: without end-to-end per-instantiation identity, implementing #392/#388/#394/#470/#471/#475 as normal With generics risks either false compatibility or more hardcoded intrinsics.

Implementation plan

  1. Audit all TY_GENERIC_INST compatibility paths. Remove or sharply constrain generic-inst-to-base compatibility so it is only allowed at a deliberate ABI/storage boundary, never as semantic type equality.
  2. Define a canonical generic instantiation key and ensure every path uses it: type syntax, method receiver substitution, trait impl selection, MIR local types, codegen storage, and diagnostics.
  3. Make instantiation-time checking explicit per §11.2: a generic body is checked when instantiated with concrete args, and diagnostics include concrete operation/type/function instantiation context.
  4. Replace builtin container method special cases gradually with normal generic method signatures in lib/std/collections.w. Keep temporary shims only where bootstrap requires them and file/remove them explicitly.
  5. Update trait selection so impl Trait for Vec[i32] and impl Trait for Vec[str] are distinct, and blanket impls over Vec[T] substitute T correctly.
  6. Add monomorphization/codegen guarantees: generated function names, LLVM struct wrappers, and MIR bodies must include concrete type args deterministically, without pointer-address or map-iteration ordering.
  7. Use stdlib migration as proof: implement a small generic iterator adapter in With and run it over Vec[i32] and Vec[str] in the same program.

Test plan

Add test/spec/spec_ss11_2_generic_inst_identity.w:

  • Vec[i32] is not assignable to Vec[str]
  • methods on Boxed[i32] and Boxed[str] return distinct types
  • impl Trait for Wrapper[i32] does not satisfy Wrapper[str]
  • a blanket impl over Wrapper[T] works for multiple T

Add test/behavior/behav_generic_iterator_adapter_distinct.w with a user-written generic adapter such as enumerate or map_id used over Vec[i32] and Vec[str].

Add compile-error cases for wrong generic arg assignment and unsupported generic operation at instantiation, checking the diagnostic names the concrete instantiation.

Acceptance criteria

  • Generic instantiations have semantic identity including all type args.
  • Generic-inst-to-base compatibility is not used to accept semantically different types.
  • Instantiation-time diagnostics identify the concrete type and generic function.
  • Trait impl selection distinguishes concrete generic args and handles blanket substitution.
  • A user-written generic iterator adapter works over at least two distinct Vec[T] instantiations.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Blocks or strongly sequences #388, #392, #394, #405, #414, #470, #471, and #475. Overlaps generic derive work in #409 and default trait methods in #538.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Additional concrete repros found while implementing #437:

    1. Generic pointer parameters were not binding nested type arguments during backend monomorphization:
    type GenericBox[T] { value: T }
    unsafe fn read[T](box: *const GenericBox[T]) -> T:
        unsafe (*box).value
    

    Calling read(&raw const box as *const GenericBox[i32]) used to fail in codegen with error: unknown type. #437 fixes this narrow backend binder case and adds behav_generic_pointer_binding.w.

    1. Return-only generic inference is still missing:
    var xs: ArenaVec[i32] = arena_vec_new_in(&raw mut arena as *mut Arena)
    

    T appears only in the return type, and the checker currently does not infer it from the annotated destination. This blocks an ergonomic generic constructor for ArenaVec[T].

    1. User generic mut self methods still do not reliably mutate the receiver. Minimal repro:
    type Counter[T] { value: i32, tag: T }
    fn Counter.bump(mut self: Counter[T]):
        self.value = self.value + 1
    fn main:
        var c: Counter[i32] = Counter { value: 0, tag: 1 }
        c.bump()
        print(int_to_string(c.value as i64))
    

    Expected 1; current native behavior observed during #437 was 0, and emitted C left an unresolved generic_call abort at the call site. This is why #437's ArenaVec[T] uses explicit unsafe helper functions at the raw-pointer boundary instead of normal generic methods for now.

  2. ehartford commented on Jun 13, 2026

    @ehartford
    ContributorAuthor

    Implemented in a348128. Generic instantiations now retain TY_GENERIC_INST identity at Sema boundaries; exact generic impls no longer leak to other instantiations, generic blanket impls match concrete type arguments and substituted bounds, and diagnostics name concrete instantiations. Added positive/negative coverage for exact generic impl dispatch, direct impl leakage, Box[i32]/Box[str] mismatch, blanket impl selection, and blanket bound rejection. Verification passed: with build, with build :fixpoint, with build :test, and with build :test-green. Follow-up receiver ABI bug filed as #584.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions