gccrs: backend: Fix incorrect impl block selection
gccrs backend now correctly identifies the `impl` block for trait dispatch, fixing dynamic dispatch errors for types implementing the same trait.
A bug in gccrs’s vtable generation has been fixed, which previously caused incorrect method calls during dynamic dispatch. The compiler would select the first impl block that matched a trait predicate, without verifying if it belonged to the correct receiver type. This change ensures that the impl block’s resolved type is compared against the receiver type, guaranteeing that the correct associated function is called.
In Details
In HIRCompileBase::compute_address_for_trait_item, the logic for selecting an impl block for trait dispatch was flawed. It picked the first matching impl without checking if it was associated with the actual receiver type. This commit adds a check to compare the impl block's type with the receiver type, ensuring correct associated function address computation, thus fixing dynamic dispatch when multiple types implement the same trait.
- gccrs
- The Rust front-end for GCC, enabling GCC to compile Rust code.
- vtable
- Virtual Method Table. A table used in C++ and other object-oriented languages to implement dynamic dispatch. It contains pointers to virtual functions.
- trait
- In Rust, a trait defines a set of methods that a type must implement. It's similar to an interface in other languages.
- dynamic dispatch
- A mechanism where the specific function to be called is determined at runtime, typically based on the type of an object. This allows for polymorphism.
- impl block
- In Rust, an
implblock is used to define methods associated with a specific type or to implement a trait for a type. - receiver type
- The type of the object on which a method is called. In Rust, this is often the type of
selfwithin a method.