Skip to content

Deref to type that is also a Receiver to the original type creates an infinite cycle #139394

Closed as not planned
@tmandry

Description

@tmandry

Let's say I define a transparent receiver type like this:

#[repr(transparent)]
struct CRef<T> {
    inner: T,
}

impl<T> Receiver for CRef<T> {
    type Target = T;
}

And then a type which allows "viewing" itself as a &CRef<T> when what you have is a &T:

#[repr(C)]
struct Flag(i32);

impl Deref for Flag {
    type Target = CRef<Flag>;
    fn deref(&self) -> &Self::Target {
        unsafe { &*(self as *const _ as *const CRef<Self>) }
    }
}

Then given this:

impl Flag {
    fn get(self: &CRef<Self>) -> i32 { 42 }
}

fn main() {
    let flag = Flag(0);
    assert_eq!(flag.get(), 42);
}

I expect flag.get() to mean something like

let flagcr: &CRef<Flag> = <Flag as Deref>::deref(&flag);
Flag::get(flagcr)

but instead I got

error[E0055]: reached the recursion limit while auto-dereferencing `CRef<Flag>`
  --> src/main.rs:32:21
   |
32 |     assert_eq!(flag.get(), 42);
   |                     ^^^ deref recursion limit reached
   |
   = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`playground`)

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e3e560589bf664d37a489d798f41cca5

It's possible this is somehow correct and there's no way to do what I'm trying to do, but if it is I don't see why.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-discussionCategory: Discussion or questions that doesn't represent real issues.F-arbitrary_self_types`#![feature(arbitrary_self_types)]`

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions