Objects should be upcastable to supertraits
trait T {
fn foo(@mut self);
}
struct S {
unused: int
}
impl T for S {
fn foo(@mut self) {
}
}
fn main() {
let s = @S { unused: 0 };
let s2 = s as @T;
let s3 = s2 as @T;
}
error: failed to find an implementation of trait @T for T
Reproduced with 64963d6cbaea86e0d2a58f507e57a76da7512e3e. Nominating for milestone 5, production-ready
The error as of 6c2dc3c is:
foo.rs:17:13: 17:21 error: can only cast an @-pointer to an @-object, not a trait T
foo.rs:17 let s3 = s2 as @T;
^~~~~~~~
error: aborting due to previous error
which is a bit weird, why shouldn't you be able to cast a trait object to the same trait object?
IINM there's two ways you could interpret this: one is that it's the identity function (casting something to its own type), the other is that you're looking for an impl T for @T, and trying to make a new @T with that as the vtable, and with s2 as the "hidden object". Last I checked trait objects don't automatically implement their trait (because e.g. with Self it can be impossible), rust-lang/rust#5087.
I would have assumed it's the identity function
Updating title to reflect the larger issue (casting from @T to @T is a special case)
accepted for feature-complete milestone
This doesn't seem like the identity function to me, as the vtables can be subsets of each other in weird ways (e.g. with multiple supertraits). Doing this properly will require new codegen.
A simpler testcase:
trait U {}
trait V : U {}
fn foo<'a>(a : &'a V)-> &'a U {
a as &U
}
this need not block 1.0. Assigning P-high as it is important for some use cases.
To be clear: this is not a subtyping rule but a coercion one. As @bblum says, it may require substituting a new vtable.
This is on the 1.0 milestone currently, due to @pnkfelix's comment above, I'm removing the milestone assuming that it was an accident.
I'm curious, how we could call supertrait method on subtrait object [1], without being able to upcast such object to supertrait? Does vtable of subtrait include all methods from supertrait? Or how does it work?
[1] — https://github.com/rust-lang/rust/blob/41a79104a412989b802852f9ee6e589b06391d61/src/test/run-pass/trait-inheritance-cast.rs
Is there any way to work around this issue in current rust? transmute can not help here: it seems that transmute messes up with vtables:
trait Foo {
fn f(&self) -> int;
}
trait Bar : Foo {
fn g(&self) -> int;
}
struct A {
x: int
}
impl Foo for A {
fn f(&self) -> int { 10 }
}
impl Bar for A {
fn g(&self) -> int { 20 }
}
fn to_foo(x:&Bar) -> &Foo {
unsafe { std::mem::transmute(x) }
}
pub fn main() {
let a = &A { x: 3 };
let abar = a as &Bar;
let abarasafoo = to_foo(abar);
assert_eq!(abarasafoo.f(), 20); // g is called
assert_eq!(abarasafoo.f(), 10); // g is called
What is layout of trait objects? I think it should be possible to "upcast" subtrait object to supertrait with unsafe manipulation of vtables.
For future references: https://github.com/rust-lang/rust/blob/master/src/librustc/driver/pretty.rs#L137 — here is workaround for this issue.
Sub.
My workaround: http://stackoverflow.com/a/28664881/403742
Triage: https://github.com/rust-lang/rust/issues/5665#issuecomment-31582946 seems to be a decent test-case, and this is still a non-scalar cast today.
I've started looking at this. I figured I'd try to clear up the design first. Here's my understanding:
Basics
Trait objects (spelled as &Trait) should be upcastable to trait objects of supertraits (&Supertrait) in as expressions, with lifetime and mutability rules behaving similarly to reference casting.
Smart pointers
Similar conversions should probably be possible for Box<Trait> to Box<SuperTrait>, Rc<Trait> to Rc<Supertrait>, and for other smart pointers. If this can (or needs to) be dealt with separately, I'll defer it for now and maybe create a separate issue, but it seems like the issues around upcasting are the same.
Implementation
Trait objects consist of a vptr and a self-pointer. The vptr points to a vtable, which contains a static array of function addresses. Each method is associated with a statically known offset in that table. To call a method on a trait object, add the offset to the vptr and call the function whose address is stored in that slot, passing the self-pointer as the first argument.
(The vtable also stores some metadata, which currently includes size, alignment, and the address of the destructor. The destructor is treated specially, presumably because any concrete type may implement Drop, and Box<Trait> needs to be able to run the destructor without Trait explicitly inheriting Drop.)
Currently, there is one vtable for each impl of an object-safe trait. There is no particular relationship between different vtables for a type that implements multiple traits. Supertrait method addresses are, however, duplicated into the subtrait's vtable.
To support upcasting, we need a way to get from the subtrait's vtable to the supertrait's vtable. I'm planning on storing supertrait vtables next to subtraits vtables, in a recursive pattern. This would let us use statically known offsets for upcasting, because the offsets are the same for every subtrait impl. The drawback is that superclass vtables would need to be duplicated in a 'diamond' inheritance situation.
(Another consequence is that two trait objects of the same trait could have different vptrs even if they were created from the same concrete type, depending on what path they took up the inheritance chain. This shouldn't matter in practice, since we don't make any guarantees about trait object equivalence.)
An alternative solution would be to store offsets next to each method list, one for each supertrait we can upcast to. This representation is more compact, but I expect it would be slower because of the dependent read.
Questions
- Should trait object upcasts be explicit (require an
asexpression) or implicit? - Is it OK to duplicate supertrait vtables like I described above?
- I believe this issue predates the RFC process. Should I file one about any part of this?
Looks like RFC 401 answered my first question: this is supposed to be an implicit coercion. See also: rust-lang/rust#18469, the tracking issue for RFC 401, and rust-lang/rust#18600, which deals with subtrait coercions and therefore may be a duplicate of this issue.
RFC 982 (DST coercions) also looks to be related. Tracking issue is rust-lang/rust#18598.
RFC pull request 250 (postponed) dealt with this, but alongside proposals for associated fields on traits, opt-in internal vtables, and other features. The upcasting section of that proposal is basically what I had in mind.