blob: bf905d95bac7b508ef386c7bc01be3a1f27d7210 [file] [log] [blame]
Brian Silverman4e662aa2022-05-11 23:10:19 -07001//! Module to make Rust subclasses of C++ classes. See [`CppSubclass`]
2//! for details.
3
4// Copyright 2021 Google LLC
5//
6// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
9// option. This file may not be copied, modified, or distributed
10// except according to those terms.
11
12use std::{
13 cell::RefCell,
14 pin::Pin,
15 rc::{Rc, Weak},
16};
17
18use cxx::{memory::UniquePtrTarget, UniquePtr};
19
20/// Deprecated - use [`subclass`] instead.
21#[deprecated]
22pub use autocxx_macro::subclass as is_subclass;
23
24/// Declare a Rust subclass of a C++ class.
25/// You can use this in two ways:
26/// * As an attribute macro on a struct which is to be a subclass.
27/// In this case, you must specify the superclass as described below.
28/// For instance,
29/// ```nocompile
30/// # use autocxx_macro::subclass as subclass;
31/// #[subclass(superclass("MyCppSuperclass"))]
32/// struct Bar {};
33/// ```
Austin Schuh6ea9bfa2023-08-06 19:05:10 -070034/// * as a directive within the [crate::include_cpp] macro, in which case you
Brian Silverman4e662aa2022-05-11 23:10:19 -070035/// must provide two arguments of the superclass and then the
36/// subclass:
37/// ```
38/// # use autocxx_macro::include_cpp_impl as include_cpp;
39/// include_cpp!(
40/// # parse_only!()
41/// #include "input.h"
42/// subclass!("MyCppSuperclass",Bar)
43/// safety!(unsafe)
44/// );
45/// struct Bar {
46/// // ...
47/// }
48/// ```
49/// In this latter case, you'll need to implement the trait
50/// [`CppSubclass`] for the struct, so it's
51/// generally easier to use the former option.
52///
53/// See [`CppSubclass`] for information about the
54/// multiple steps you need to take to be able to make Rust
55/// subclasses of a C++ class.
56pub use autocxx_macro::subclass;
57
58/// A prelude containing all the traits and macros required to create
59/// Rust subclasses of C++ classes. It's recommended that you:
60///
61/// ```rust
62/// use autocxx::subclass::prelude::*;
63/// ```
64pub mod prelude {
65 pub use super::{
66 is_subclass, subclass, CppPeerConstructor, CppSubclass, CppSubclassDefault,
67 CppSubclassRustPeerHolder, CppSubclassSelfOwned, CppSubclassSelfOwnedDefault,
68 };
69}
70
71/// A trait representing the C++ side of a Rust/C++ subclass pair.
72#[doc(hidden)]
73pub trait CppSubclassCppPeer: UniquePtrTarget {
74 fn relinquish_ownership(&self);
75}
76
77/// A type used for how the C++ side of a Rust/C++ subclass pair refers to
78/// the Rust side.
79#[doc(hidden)]
80pub enum CppSubclassRustPeerHolder<T> {
81 Owned(Rc<RefCell<T>>),
82 Unowned(Weak<RefCell<T>>),
83}
84
85impl<T> CppSubclassRustPeerHolder<T> {
86 pub fn get(&self) -> Option<Rc<RefCell<T>>> {
87 match self {
88 CppSubclassRustPeerHolder::Owned(strong) => Some(strong.clone()),
89 CppSubclassRustPeerHolder::Unowned(weak) => weak.upgrade(),
90 }
91 }
92 pub fn relinquish_ownership(self) -> Self {
93 match self {
94 CppSubclassRustPeerHolder::Owned(strong) => {
95 CppSubclassRustPeerHolder::Unowned(Rc::downgrade(&strong))
96 }
97 _ => self,
98 }
99 }
100}
101
102/// A type showing how the Rust side of a Rust/C++ subclass pair refers to
103/// the C++ side.
104#[doc(hidden)]
Austin Schuh6ea9bfa2023-08-06 19:05:10 -0700105#[derive(Default)]
Brian Silverman4e662aa2022-05-11 23:10:19 -0700106pub enum CppSubclassCppPeerHolder<CppPeer: CppSubclassCppPeer> {
Austin Schuh6ea9bfa2023-08-06 19:05:10 -0700107 #[default]
Brian Silverman4e662aa2022-05-11 23:10:19 -0700108 Empty,
109 Owned(Box<UniquePtr<CppPeer>>),
110 Unowned(*mut CppPeer),
111}
112
Brian Silverman4e662aa2022-05-11 23:10:19 -0700113impl<CppPeer: CppSubclassCppPeer> CppSubclassCppPeerHolder<CppPeer> {
114 fn pin_mut(&mut self) -> Pin<&mut CppPeer> {
115 match self {
116 CppSubclassCppPeerHolder::Empty => panic!("Peer not set up"),
117 CppSubclassCppPeerHolder::Owned(peer) => peer.pin_mut(),
118 CppSubclassCppPeerHolder::Unowned(peer) => unsafe {
119 // Safety: guaranteed safe because this is a pointer to a C++ object,
120 // and C++ never moves things in memory.
121 Pin::new_unchecked(peer.as_mut().unwrap())
122 },
123 }
124 }
125 fn get(&self) -> &CppPeer {
126 match self {
127 CppSubclassCppPeerHolder::Empty => panic!("Peer not set up"),
128 CppSubclassCppPeerHolder::Owned(peer) => peer.as_ref(),
129 // Safety: guaranteed safe because this is a pointer to a C++ object,
130 // and C++ never moves things in memory.
131 CppSubclassCppPeerHolder::Unowned(peer) => unsafe { peer.as_ref().unwrap() },
132 }
133 }
134 fn set_owned(&mut self, peer: UniquePtr<CppPeer>) {
135 *self = Self::Owned(Box::new(peer));
136 }
137 fn set_unowned(&mut self, peer: &mut UniquePtr<CppPeer>) {
138 // Safety: guaranteed safe because this is a pointer to a C++ object,
139 // and C++ never moves things in memory.
140 *self = Self::Unowned(unsafe {
141 std::pin::Pin::<&mut CppPeer>::into_inner_unchecked(peer.pin_mut())
142 });
143 }
144}
145
146fn make_owning_peer<CppPeer, PeerConstructor, Subclass, PeerBoxer>(
147 me: Subclass,
148 peer_constructor: PeerConstructor,
149 peer_boxer: PeerBoxer,
150) -> Rc<RefCell<Subclass>>
151where
152 CppPeer: CppSubclassCppPeer,
153 Subclass: CppSubclass<CppPeer>,
154 PeerConstructor:
155 FnOnce(&mut Subclass, CppSubclassRustPeerHolder<Subclass>) -> UniquePtr<CppPeer>,
156 PeerBoxer: FnOnce(Rc<RefCell<Subclass>>) -> CppSubclassRustPeerHolder<Subclass>,
157{
158 let me = Rc::new(RefCell::new(me));
159 let holder = peer_boxer(me.clone());
160 let cpp_side = peer_constructor(&mut me.as_ref().borrow_mut(), holder);
161 me.as_ref()
162 .borrow_mut()
163 .peer_holder_mut()
164 .set_owned(cpp_side);
165 me
166}
167
168/// A trait to be implemented by a subclass which knows how to construct
169/// its C++ peer object. Specifically, the implementation here will
170/// arrange to call one or other of the `make_unique` methods to be
171/// found on the superclass of the C++ object. If the superclass
172/// has a single trivial constructor, then this is implemented
173/// automatically for you. If there are multiple constructors, or
174/// a single constructor which takes parameters, you'll need to implement
175/// this trait for your subclass in order to call the correct
176/// constructor.
177pub trait CppPeerConstructor<CppPeer: CppSubclassCppPeer>: Sized {
178 /// Create the C++ peer. This method will be automatically generated
179 /// for you *except* in cases where the superclass has multiple constructors,
180 /// or its only constructor takes parameters. In such a case you'll need
181 /// to implement this by calling a `make_unique` method on the
182 /// `<my subclass name>Cpp` type, passing `peer_holder` as the first
183 /// argument.
184 fn make_peer(&mut self, peer_holder: CppSubclassRustPeerHolder<Self>) -> UniquePtr<CppPeer>;
185}
186
187/// A subclass of a C++ type.
188///
189/// To create a Rust subclass of a C++ class, you must do these things:
190/// * Create a `struct` to act as your subclass, and add the #[`macro@crate::subclass`] attribute.
191/// This adds a field to your struct for autocxx record-keeping. You can
192/// instead choose to implement [`CppSubclass`] a different way, in which case
193/// you must provide the [`macro@crate::subclass`] inside your [`crate::include_cpp`]
194/// macro. (`autocxx` will do the required codegen for your subclass
195/// whether it discovers a [`macro@crate::subclass`] directive inside your
196/// [`crate::include_cpp`], or elsewhere used as an attribute macro,
197/// or both.)
198/// * Use the [`CppSubclass`] trait, and instantiate the subclass using
199/// [`CppSubclass::new_rust_owned`] or [`CppSubclass::new_cpp_owned`]
200/// constructors. (You can use [`CppSubclassSelfOwned`] if you need that
201/// instead; also, see [`CppSubclassSelfOwnedDefault`] and [`CppSubclassDefault`]
202/// to arrange for easier constructors to exist.
203/// * You _may_ need to implement [`CppPeerConstructor`] for your subclass,
204/// but only if autocxx determines that there are multiple possible superclass
205/// constructors so you need to call one explicitly (or if there's a single
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700206/// non-trivial superclass constructor.) autocxx will implement this trait
207/// for you if there's no ambiguity and FFI functions are safe to call due to
208/// `autocxx::safety!` being used.
Brian Silverman4e662aa2022-05-11 23:10:19 -0700209///
210/// # How to access your Rust structure from outside
211///
212/// Use [`CppSubclass::new_rust_owned`] then use [`std::cell::RefCell::borrow`]
213/// or [`std::cell::RefCell::borrow_mut`] to obtain the underlying Rust struct.
214///
215/// # How to call C++ methods on the subclass
216///
217/// Do the same. You should find that your subclass struct `impl`s all the
218/// C++ methods belonging to the superclass.
219///
220/// # How to implement virtual methods
221///
222/// Simply add an `impl` for the `struct`, implementing the relevant method.
223/// The C++ virtual function call will be redirected to your Rust implementation.
224///
225/// # How _not_ to implement virtual methods
226///
227/// If you don't want to implement a virtual method, don't: the superclass
228/// method will be called instead. Naturally, you must implement any pure virtual
229/// methods.
230///
231/// # How it works
232///
233/// This actually consists of two objects: this object itself and a C++-side
234/// peer. The ownership relationship between those two things can work in three
235/// different ways:
236/// 1. Neither object is owned by Rust. The C++ peer is owned by a C++
237/// [`UniquePtr`] held elsewhere in C++. That C++ peer then owns
238/// this Rust-side object via a strong [`Rc`] reference. This is the
239/// ownership relationship set up by [`CppSubclass::new_cpp_owned`].
240/// 2. The object pair is owned by Rust. Specifically, by a strong
241/// [`Rc`] reference to this Rust-side object. In turn, the Rust-side object
242/// owns the C++-side peer via a [`UniquePtr`]. This is what's set up by
243/// [`CppSubclass::new_rust_owned`]. The C++-side peer _does not_ own the Rust
244/// object; it just has a weak pointer. (Otherwise we'd get a reference
245/// loop and nothing would ever be freed.)
246/// 3. The object pair is self-owned and will stay around forever until
247/// [`CppSubclassSelfOwned::delete_self`] is called. In this case there's a strong reference
248/// from the C++ to the Rust and from the Rust to the C++. This is useful
249/// for cases where the subclass is listening for events, and needs to
250/// stick around until a particular event occurs then delete itself.
251///
252/// # Limitations
253///
254/// * *Re-entrancy*. The main thing to look out for is re-entrancy. If a
255/// (non-const) virtual method is called on your type, which then causes you
256/// to call back into C++, which results in a _second_ call into a (non-const)
257/// virtual method, we will try to create two mutable references to your
258/// subclass which isn't allowed in Rust and will therefore panic.
259///
260/// A future version of autocxx may provide the option of treating all
261/// non-const methods (in C++) as const methods on the Rust side, which will
262/// give the option of using interior mutability ([`std::cell::RefCell`])
263/// for you to safely handle this situation, whilst remaining compatible
264/// with existing C++ interfaces. If you need this, indicate support on
265/// [this issue](https://github.com/google/autocxx/issues/622).
266///
267/// * *Thread safety*. The subclass object is not thread-safe and shouldn't
268/// be passed to different threads in C++. A future version of this code
269/// will give the option to use `Arc` and `Mutex` internally rather than
270/// `Rc` and `RefCell`, solving this problem.
271///
272/// * *Protected methods.* We don't do anything clever here - they're public.
273///
274/// * *Non-trivial class hierarchies*. We don't yet consider virtual methods
275/// on base classes of base classes. This is a temporary limitation,
276/// [see this issue](https://github.com/google/autocxx/issues/610).
277pub trait CppSubclass<CppPeer: CppSubclassCppPeer>: CppPeerConstructor<CppPeer> {
278 /// Return the field which holds the C++ peer object. This is normally
279 /// implemented by the #[`is_subclass`] macro, but you're welcome to
280 /// implement it yourself if you prefer.
281 fn peer_holder(&self) -> &CppSubclassCppPeerHolder<CppPeer>;
282
283 /// Return the field which holds the C++ peer object. This is normally
284 /// implemented by the #[`is_subclass`] macro, but you're welcome to
285 /// implement it yourself if you prefer.
286 fn peer_holder_mut(&mut self) -> &mut CppSubclassCppPeerHolder<CppPeer>;
287
288 /// Return a reference to the C++ part of this object pair.
289 /// This can be used to register listeners, etc.
290 fn peer(&self) -> &CppPeer {
291 self.peer_holder().get()
292 }
293
294 /// Return a mutable reference to the C++ part of this object pair.
295 /// This can be used to register listeners, etc.
296 fn peer_mut(&mut self) -> Pin<&mut CppPeer> {
297 self.peer_holder_mut().pin_mut()
298 }
299
300 /// Creates a new instance of this subclass. This instance is owned by the
301 /// returned [`cxx::UniquePtr`] and thus would typically be returned immediately
302 /// to C++ such that it can be owned on the C++ side.
303 fn new_cpp_owned(me: Self) -> UniquePtr<CppPeer> {
304 let me = Rc::new(RefCell::new(me));
305 let holder = CppSubclassRustPeerHolder::Owned(me.clone());
306 let mut borrowed = me.as_ref().borrow_mut();
307 let mut cpp_side = borrowed.make_peer(holder);
308 borrowed.peer_holder_mut().set_unowned(&mut cpp_side);
309 cpp_side
310 }
311
312 /// Creates a new instance of this subclass. This instance is not owned
313 /// by C++, and therefore will be deleted when it goes out of scope in
314 /// Rust.
315 fn new_rust_owned(me: Self) -> Rc<RefCell<Self>> {
316 make_owning_peer(
317 me,
318 |obj, holder| obj.make_peer(holder),
319 |me| CppSubclassRustPeerHolder::Unowned(Rc::downgrade(&me)),
320 )
321 }
322}
323
324/// Trait to be implemented by subclasses which are self-owned, i.e. not owned
325/// externally by either Rust or C++ code, and thus need the ability to delete
326/// themselves when some virtual function is called.
327pub trait CppSubclassSelfOwned<CppPeer: CppSubclassCppPeer>: CppSubclass<CppPeer> {
328 /// Creates a new instance of this subclass which owns itself.
329 /// This is useful
330 /// for observers (etc.) which self-register to listen to events.
331 /// If an event occurs which would cause this to want to unregister,
332 /// use [`CppSubclassSelfOwned::delete_self`].
333 /// The return value may be useful to register this, etc. but can ultimately
334 /// be discarded without destroying this object.
335 fn new_self_owned(me: Self) -> Rc<RefCell<Self>> {
336 make_owning_peer(
337 me,
338 |obj, holder| obj.make_peer(holder),
339 CppSubclassRustPeerHolder::Owned,
340 )
341 }
342
343 /// Relinquishes ownership from the C++ side. If there are no outstanding
344 /// references from the Rust side, this will result in the destruction
345 /// of this subclass instance.
346 fn delete_self(&self) {
347 self.peer().relinquish_ownership()
348 }
349}
350
351/// Provides default constructors for subclasses which implement `Default`.
352pub trait CppSubclassDefault<CppPeer: CppSubclassCppPeer>: CppSubclass<CppPeer> + Default {
353 /// Create a Rust-owned instance of this subclass, initializing with default values. See
354 /// [`CppSubclass`] for more details of the ownership models available.
355 fn default_rust_owned() -> Rc<RefCell<Self>>;
356
357 /// Create a C++-owned instance of this subclass, initializing with default values. See
358 /// [`CppSubclass`] for more details of the ownership models available.
359 fn default_cpp_owned() -> UniquePtr<CppPeer>;
360}
361
362impl<T, CppPeer> CppSubclassDefault<CppPeer> for T
363where
364 T: CppSubclass<CppPeer> + Default,
365 CppPeer: CppSubclassCppPeer,
366{
367 fn default_rust_owned() -> Rc<RefCell<Self>> {
368 Self::new_rust_owned(Self::default())
369 }
370
371 fn default_cpp_owned() -> UniquePtr<CppPeer> {
372 Self::new_cpp_owned(Self::default())
373 }
374}
375
376/// Provides default constructors for subclasses which implement `Default`
377/// and are self-owning.
378pub trait CppSubclassSelfOwnedDefault<CppPeer: CppSubclassCppPeer>:
379 CppSubclassSelfOwned<CppPeer> + Default
380{
381 /// Create a self-owned instance of this subclass, initializing with default values. See
382 /// [`CppSubclass`] for more details of the ownership models available.
383 fn default_self_owned() -> Rc<RefCell<Self>>;
384}
385
386impl<T, CppPeer> CppSubclassSelfOwnedDefault<CppPeer> for T
387where
388 T: CppSubclassSelfOwned<CppPeer> + Default,
389 CppPeer: CppSubclassCppPeer,
390{
391 fn default_self_owned() -> Rc<RefCell<Self>> {
392 Self::new_self_owned(Self::default())
393 }
394}