Make sure to use Receiver trait when extracting object method candidate by compiler-errors · Pull Request #135179 · rust-lang/rust (original) (raw)

Background:

Rust references have certain rules, most notably that the underlying data cannot be changed while an immutable reference exists. That's essentially impossible to promise for any C++ data; C++ may retain references or pointers to data any modify it at any time. This presents a problem for Rust/C++ interop tooling. Various solutions or workarounds are possible:

  1. All C++ data is represented as zero-sized types. This is the approach taken by cxx for opaque types. This sidesteps all of the Rust reference rules, since those rules only apply to areas of memory that are referred to. This doesn't really work well enough for autocxx since we want to be able to keep C++ data on the Rust stack, using all the fancy moveit shenanigans, and that means that Rust must know the true size and alignment of the type.

  2. All C++ data is represented as UnsafeCell<MaybeUninit>. This also sidesteps the reference rules. This would be a valid option for autocxx.

  3. Have a sufficiently simple language boundary that humans can reasonably guarantee there are no outstanding references on the C++ side which could be used to modify the underlying data. This is the approach taken by cxx for cxx::kind::Trivial types. It's just about possible to cause UB using one of these types, but you really have to work at it. In practice such UB is unlikely.

  4. Never allow Rust references to C++ types. Instead use a special smart pointer type in Rust, representing a C++ reference. This is the direction in this PR.

More detail on this last approach here: https://medium.com/@adetaylor/are-we-reference-yet-c-references-in-rust-72c1c6c7015a

This facility is already in autocxx, by adopting the safety policy "unsafe_references_wrapped". However, it hasn't really been battle tested and has a bunch of deficiencies.

It's been awaiting formal Rust support for "arbitrary self types" so that methods can be called on such smart pointers. This is now [fairly close to stabilization](rust-lang/rust#44874 (comment)); this PR is part of the experimentation required to investigate whether that rustc feature should go ahead and get stabilized.

This PR essentially converts autocxx to only operate in this mode - there should no longer ever be Rust references to C++ data.

This PR is incomplete:

This also shows up a Rustc problem which is fixed here.

Ergonomic findings:

Next steps here: