Skip to content

Specialization in trait implementations #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
osa1 opened this issue Aug 12, 2024 · 1 comment
Open

Specialization in trait implementations #20

osa1 opened this issue Aug 12, 2024 · 1 comment
Labels
traits type system Design of the Fir type system

Comments

@osa1
Copy link
Member

osa1 commented Aug 12, 2024

trait T[A]:
    fn f(self)

impl T[I32]: ...

impl[A: T] T[Vec[A]]: ...

# Overlaps with the more general definition above.
impl T[Vec[I32]]: ...

I think this is actually safe when all of the following holds:

  1. We do monomorphisation, instead of runtime polymorphism.

    This allows compiling call sites:

    fn g[A: T](a: A) = [a].f()
    

    Here each call site of g will create a monomorphic g based on the type argument, so I know which f to call in [a].f(), without having to do runtime type tests.

  2. To make sure (1) covers all invocations of the f, the trait is not allowed in trait objects. E.g. you can't have an existential with this trait as the type.

  3. Specialization is only allowed within the compilation/type checking unit of the trait. Users cannot add implementations that specialize an existing implementation.

    This makes sure when two packages/libararies build and run fine on their own, they will build and run the same way when they are linked together in a third package/library.

I actually don't know if this pattern is useful. I'm thinking maybe in the standard library we can provide faster Hash on Vec[I32] (and other Vec types with 4-byte unboxed elements) using this.

@osa1 osa1 added the type system Design of the Fir type system label Jan 8, 2025
@osa1
Copy link
Member Author

osa1 commented Jan 11, 2025

It may worth reading the discussions on Rust's specialization feature: rust-lang/rust#31844

RFC: https://rust-lang.github.io/rfcs/1210-impl-specialization.html

One immediate use case is #30: we can have a ToStr and ToStrBuf, provide a default ToStr implementation for types that are ToStrBuf, and allow types like Bool to override it with a more efficient version that return static strings.

@osa1 osa1 added the traits label Jan 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
traits type system Design of the Fir type system
Projects
None yet
Development

No branches or pull requests

1 participant