Skip to content

Commit 389c868

Browse files
committed
Partial conversion to CppRef<T> everywhere
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<T>>. 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: * There are still 60 failing integration tests. Mostly these relate to subclass support, which isn't yet converted. * `ValueParam` and `RValueParam` need to support taking `CppPin<T>`, and possibly `CppRef<T: CopyNew>` etc. * Because we can't implement `Deref` for `cxx::UniquePtr<T>` to emit a `CppRef<T>`, unfortunately `cxx::UniquePtr<T>` can't be used in cases where we want to provide a `const T&`. It's necessary to call `.as_cpp_ref()` on the `UniquePtr`. This is sufficiently annoying that it might be necessary to implement a trait `ReferenceParam` like we have for `ValueParam` and `RValueParam`. (Alternatives include upstreaming `CppRef<T>` into cxx, but per reason 4 listed above, the complexity probably isn't merited for statically-declared cxx interfaces; or separating from cxx entirely.) This also shows up a [Rustc problem which is fixed here](rust-lang/rust#135179). Ergonomic findings: * The problem with `cxx::UniquePtr` as noted above. * It's nice that `Deref` coercion allows methods to be called on `CppPin` as well as `CppRef`. * To get the same benefit for parameters being passed in by reference, you need to pass in `&my_cpp_pin_wrapped_thing` which is weird given that the whole point is we're trying to avoid Rust references. Obviously, calling `.as_cpp_ref()` works too, so this weirdness can be avoided. * When creating some C++ data `T`, in Rust, it's annoying to have to decide a-priori whether it'll be Rust or C++ accessing the data. If the former, you just create a new `T`; if the latter you need to wrap it in `CppPin::new`. This is only really a problem when creating a C++ object on which you'll call methods. It feels like it'll be OK in practice. Possibly this can be resolved by making the method receiver some sort of `impl MethodReceiver<T>` generic; an implementation for `T` could be provided which auto-wraps it into a `CppPin` (consuming it at that point). This sounds messy though. A bit more thought required, but even if this isn't possible it doesn't sound like a really serious ergonomics problem, especially if we can use `#[diagnostic::on_unimplemented]` somehow to guide. Next steps here: * Stabilize arbitrary self types. This PR has gone far enough to show that there are no really serious unexpected issues there. * Implement `ValueParam` and `RValueParam` as necessary for `CppRef` and `CppPin` types. * Work on those ergonomic issues to the extent possible. * Make a bold decision about whether autocxx should shift wholesale away from `&` to `CppRef<T>`. If so, this will be a significant breaking change.
1 parent a4fe59e commit 389c868

File tree

9 files changed

+190
-176
lines changed

9 files changed

+190
-176
lines changed

demo/src/main.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
// option. This file may not be copied, modified, or distributed
77
// except according to those terms.
88

9+
#![feature(arbitrary_self_types)]
10+
911
use autocxx::prelude::*;
1012
include_cpp! {
1113
#include "input.h"
@@ -16,9 +18,9 @@ include_cpp! {
1618

1719
fn main() {
1820
println!("Hello, world! - C++ math should say 12={}", ffi::DoMath(4));
19-
let mut goat = ffi::Goat::new().within_box();
20-
goat.as_mut().add_a_horn();
21-
goat.as_mut().add_a_horn();
21+
let goat = ffi::Goat::new().within_cpp_pin();
22+
goat.add_a_horn();
23+
goat.add_a_horn();
2224
assert_eq!(
2325
goat.describe().as_ref().unwrap().to_string_lossy(),
2426
"This goat has 2 horns."

engine/src/conversion/analysis/fun/mod.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -1541,13 +1541,15 @@ impl<'a> FnAnalyzer<'a> {
15411541
let from_type = self_ty.as_ref().unwrap();
15421542
let from_type_path = from_type.to_type_path();
15431543
let to_type = to_type.to_type_path();
1544-
let (trait_signature, ty, method_name) = match *mutable {
1544+
let (trait_signature, ty, method_name): (_, Type, _) = match *mutable {
15451545
CastMutability::ConstToConst => (
15461546
parse_quote! {
1547-
AsRef < #to_type >
1547+
autocxx::AsCppRef < #to_type >
15481548
},
1549-
Type::Path(from_type_path),
1550-
"as_ref",
1549+
parse_quote! {
1550+
autocxx::CppRef< #from_type_path >
1551+
},
1552+
"as_cpp_ref",
15511553
),
15521554
CastMutability::MutToConst => (
15531555
parse_quote! {

engine/src/conversion/codegen_rs/mod.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ mod utils;
1818
use indexmap::map::IndexMap as HashMap;
1919
use indexmap::set::IndexSet as HashSet;
2020

21-
use autocxx_parser::{ExternCppType, IncludeCppConfig, RustFun, UnsafePolicy};
21+
use autocxx_parser::{ExternCppType, IncludeCppConfig, RustFun};
2222

2323
use itertools::Itertools;
2424
use proc_macro2::{Span, TokenStream};
@@ -121,7 +121,6 @@ fn get_string_items() -> Vec<Item> {
121121
/// In practice, much of the "generation" involves connecting together
122122
/// existing lumps of code within the Api structures.
123123
pub(crate) struct RsCodeGenerator<'a> {
124-
unsafe_policy: &'a UnsafePolicy,
125124
include_list: &'a [String],
126125
bindgen_mod: ItemMod,
127126
original_name_map: CppNameMap,
@@ -133,14 +132,12 @@ impl<'a> RsCodeGenerator<'a> {
133132
/// Generate code for a set of APIs that was discovered during parsing.
134133
pub(crate) fn generate_rs_code(
135134
all_apis: ApiVec<FnPhase>,
136-
unsafe_policy: &'a UnsafePolicy,
137135
include_list: &'a [String],
138136
bindgen_mod: ItemMod,
139137
config: &'a IncludeCppConfig,
140138
header_name: Option<String>,
141139
) -> Vec<Item> {
142140
let c = Self {
143-
unsafe_policy,
144141
include_list,
145142
bindgen_mod,
146143
original_name_map: CppNameMap::new_from_apis(&all_apis),
@@ -515,11 +512,8 @@ impl<'a> RsCodeGenerator<'a> {
515512
name, superclass, ..
516513
} => {
517514
let methods = associated_methods.get(&superclass);
518-
let generate_peer_constructor = subclasses_with_a_single_trivial_constructor.contains(&name.0.name) &&
519-
// TODO: Create an UnsafeCppPeerConstructor trait for calling an unsafe
520-
// constructor instead? Need to create unsafe versions of everything that uses
521-
// it too.
522-
matches!(self.unsafe_policy, UnsafePolicy::AllFunctionsSafe);
515+
let generate_peer_constructor =
516+
subclasses_with_a_single_trivial_constructor.contains(&name.0.name);
523517
self.generate_subclass(name, &superclass, methods, generate_peer_constructor)
524518
}
525519
Api::ExternCppType {

engine/src/conversion/conversion_tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ fn do_test(input: ItemMod) {
3333
bc.convert(
3434
input,
3535
parse_callback_results,
36-
UnsafePolicy::AllFunctionsSafe,
36+
UnsafePolicy::ReferencesWrappedAllFunctionsSafe,
3737
inclusions,
3838
&CodegenOptions::default(),
3939
"",

engine/src/conversion/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,6 @@ impl<'a> BridgeConverter<'a> {
196196
.map_err(ConvertError::Cpp)?;
197197
let rs = RsCodeGenerator::generate_rs_code(
198198
analyzed_apis,
199-
&unsafe_policy,
200199
self.include_list,
201200
bindgen_mod,
202201
self.config,

integration-tests/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@ pub fn do_run_test(
380380
let safety_policy = format_ident!("{}", safety_policy);
381381
let unexpanded_rust = quote! {
382382
#module_attributes
383+
#![feature(arbitrary_self_types)]
383384

384385
use autocxx::prelude::*;
385386

0 commit comments

Comments
 (0)