blob: 0d8941cb2ac3dfc4158b75f778c7bb51ddc48683 [file] [view]
# Rust bindings for C++ classes and structs
A C++ `class` or `struct` is mapped to a Rust `struct` with the same fields. If
any subobject of the class cannot be represented in Rust, the class itself will
still have bindings, but [the relevant subobject will be
private](#opaque_fields).
## Example
Given the following C++ header:
```live-snippet
cs/file:examples/cpp/trivial_struct/example.h class:Position
```
Crubit will generate a struct with the same layout:
```live-snippet
cs/file:examples/cpp/trivial_struct/example_generated.rs class:Position
```
Which can be used like this:
```live-snippet
cs/file:examples/cpp/trivial_struct/main.rs function:main
```
For an example of a Rust-movable class with a destructor, see
[examples/cpp/trivial_abi_struct/](https://github.com/google/crubit/tree/main/examples/cpp/trivial_abi_struct/).
## Fields {#fields}
The fields on the Rust struct type are the corresponding Rust types:
* If the C++ field has [primitive type](../types/primitive.md), then the Rust
field uses the corresponding Rust type.
* Similarly, if the C++ field has [pointer type](../types/pointer.md), then
the Rust field has the corresponding Rust pointer type.
* If the field has a user-defined type, such as a [class
type](classes_and_structs.md) or [enum](enums.md), then the Rust field uses
the bindings for that type.
* If the field has a non-zero fixed-length C-style array type (`T[N]`) of a
[primitive type](../types/primitive.md) or [enum](enums.md) (including
multidimensional arrays such as `T[M][N]`), then the Rust field has type
`[T; N]`.
### Unsupported fields {#opaque_fields}
Subobjects that do not receive bindings are made private, and replaced with an
opaque blob of `[MaybeUninit<u8>; N]`, as well as a comment in the generated
source code explaining why the subobject could not receive bindings. For
example, base class subobjects are not exposed as fields, so the space of the
object occupied by a base class will instead be this opaque blob of bytes, with
no comment. (See [Base classes](#inheritance) for what you can do with base
classes instead.)
Specifically, the following subobjects are hidden and replaced with opaque
blobs:
* Base class subobjects
* Non-`public` fields (`private` or `protected` fields)
* Fields that have nontrivial destructors
* Fields whose type does not have bindings
* Fields that have any unrecognized attribute, including `no_unique_address`
* Fields of a [packed struct](#packed) whose Rust type has `#[repr(align(N))]`
A Rust struct with opaque blobs is ABI-incompatible with the C++ struct or class
that it corresponds to. As a consequence, if the struct is used for FFI outside
of Crubit, it should not be passed by value. Within Crubit, it can't be passed
by value in [function pointers](../types/pointer.md#function), but can otherwise
be used as normal.
## Static data members {#static_members}
Public static data members get bindings: compile-time integer, `bool`, integer
array, and string_view constants become associated `const`s of the Rust struct,
and other static data members become Rust `static`s. See [Static data
members](static_data_members.md) for details.
<span id="trivially_relocatable"></span>
## Rust-movable classes {#rust_movable}
The easiest C++ classes to work with are "Rust-movable", meaning they support
being relocated in memory using `memcpy` without running the move constructor.
When passed and returned by value, Rust-movable classes will use the direct
type. For example, `T Identity(T)` becomes `pub fn Identity(_: T) -> T`.
If it is non-Rust-movable, then Crubit will instead use in-place initialization
types, `Ctor`, and requires a bit of syntactic overhead when moving objects
around. The same function might instead become
`pub fn Foo(_: Ctor![T]) -> Ctor![T]`.
(For an introduction to `Ctor![T]`, see
crubit.rs/types/non_rust_movable/intro_short.)
Types are considered Rust-movable (bitwise relocatable) by default. If the type
defines a user-provided move constructor or destructor, then it requires a
special annotation to be considered Rust-movable:
`CRUBIT_UNSAFE_BITWISE_RELOCATABLE` (defined in `support/annotations.h`, along
with `CRUBIT_UNSAFE_BITWISE_RELOCATABLE_IF_ELIGIBLE` for templates,
`CRUBIT_UNSAFE_BITWISE_RELOCATABLE_FIELD`,
`CRUBIT_BITWISE_RELOCATABLE_STD_STRING_ONLY_ON_LIBCXX`, and
`CRUBIT_NEVER_BITWISE_RELOCATABLE`).
If a type has a non-Rust-movable field or base class, it is not Rust-movable. A
`CRUBIT_UNSAFE_BITWISE_RELOCATABLE` annotation on a type with
non-bitwise-relocatable fields or bases fails bindings generation with a hard
error.
**Note on `trivial_abi`**: While `[[clang::trivial_abi]]` /
[`ABSL_ATTRIBUTE_TRIVIAL_ABI`](https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h#:~:text=ABSL_ATTRIBUTE_TRIVIAL_ABI)
previously made types Rust-movable, it *may not* make a type Rust-movable
anymore. Crubit checks the members of a `trivial_abi` type, and if any member is
not bitwise-relocatable, Crubit leaves the type pinned and records the reason in
the generated doc comment. New code should use
`CRUBIT_UNSAFE_BITWISE_RELOCATABLE`.
It can be worth putting some effort into designing the type to be Rust-movable.
The [C++ Bindings Cookbook](./cookbook.md#rust_movable) describes, in more
detail, how to go about this.
Some examples of Rust-movable types:
* any primitive type (integers, character types, floats, etc.)
* raw pointers
* `string_view`
* [`struct tm`](https://en.cppreference.com/w/cpp/chrono/c/tm), or any other
type in the C standard library
* `std::unique_ptr` (with the default deleter), `std::shared_ptr`,
`std::weak_ptr`, and `std::vector` (with the default allocator)
* `std::optional<T>`, `std::variant<Ts...>`, and `std::expected<T, E>` when
their element types are Rust-movable
* any class whose bases and non-static data members are Rust-movable, and
which has no user-provided (or explicitly `= delete`d) special member
functions, even if its copy and move constructors are implicitly deleted
(such as structs containing `rs::Box` or other non-C++-movable types
annotated with `CRUBIT_UNSAFE_BITWISE_RELOCATABLE`).
* `absl::Status`
Some examples of types that are **not** Rust-movable:
* `std::string` (unless opted in on libc++-only builds via
`CRUBIT_BITWISE_RELOCATABLE_STD_STRING_ONLY_ON_LIBCXX`), `std::function`,
`std::any`, and node-based containers such as `std::map` and `std::list`.
* (For now) `absl::flat_hash_map`, `absl::AnyInvocable`, and other nontrivial
types used throughout the C++ ecosystem, even outside the standard library.
* `absl::Mutex`, `absl::Notification`, and other non-movable types.
## Base classes {#inheritance}
Rust has no inheritance, so a derived class and its base classes become
unrelated Rust structs. The base class subobject is an [opaque
blob](#opaque_fields), so base class fields aren't accessible through the
derived struct. With `oo_casting`, Rust code can [upcast](#inherited_methods) to
the base class and read the fields there.
### Inherited methods {#inherited_methods}
By default, methods that a class inherits from its base classes are **not** part
of the derived class's bindings, and no comment is emitted about them. They
still exist on the base class's bindings.
```c++
struct Base {
bool IsValid() const;
};
struct Derived : Base {};
```
Here, `Base::IsValid()` has bindings, but `Derived` has no `IsValid()` method in
Rust.
To get inherited methods, add `//features:oo_casting` to the
`aspect_hints` of the `cc_library` that defines the derived class. This is an
[experimental](../overview/status.md) feature. With it:
* The derived struct gets the public methods, including static methods, of its
public base classes, so `derived.IsValid()` works in Rust. This only covers
base classes defined in the same `cc_library` as the derived class, and
leaves out methods whose name comes from more than one base class.
* The derived struct implements `oops::Inherits<Base>` for each public base
class, including base classes from other `cc_library` targets. Rust code can
then use the `oops::Upcast` trait to convert a `&Derived` to the base class
type. If the base class is not Rust-movable, it can also convert a
`Pin<&mut Derived>`. To convert a `*const Derived` or `*mut Derived`, use
`oops::RawUpcast`. For example, to call a method of a base class in another
`cc_library`, upcast first:
```rust
use oops::Upcast as _;
// The type annotation is required.
let base: &Base = unsafe { derived.upcast() };
// For non-const methods on a non-Rust-movable base class:
let base: core::pin::Pin<&mut Base> = unsafe { derived_pin.upcast() };
// For raw pointers:
use oops::RawUpcast as _;
let base_ptr: *const Base = unsafe { derived_ptr.raw_upcast() };
```
There is no `Pin<&mut Derived>` conversion to a Rust-movable base class,
because safe code could turn the result into a `&mut Base` and overwrite
data that belongs to the derived class.
For a `virtual` base class, use `oops::VirtualUpcast` on a raw pointer
instead. Rust code that uses these traits depends on
`//support:oops`.
The tests in
`rs_bindings_from_cc/test/struct/inheritance/` show
both.
Without `oo_casting`, add a method to the derived class in C++ that forwards to
the base class method, or a function that returns the object as a pointer to its
base class.
`using Base::Method;` declarations in the derived class don't get bindings, and
produce a "Function aliases are not yet supported" error comment. With
`oo_casting`, the method is usually inherited anyway. It's missing only if the
`using` declaration makes a method of a non-public base class accessible, or
brings back a base class method that a derived class method of the same name
hides.
### Virtual methods {#virtual}
Calling a C++ virtual method from Rust works like calling any other method, and
dispatches virtually. This includes pure virtual methods. Because a class with
virtual methods is not [Rust-movable](#rust_movable), non-`const` methods take
`self: Pin<&mut Self>`.
An abstract class (one with pure virtual methods that aren't overridden) gets
bindings for its methods but no constructor, so Rust code works with it through
references and pointers to objects created elsewhere. A subclass that overrides
the methods gets bindings for its overrides and can be constructed. The methods
it doesn't override are [inherited methods](#inherited_methods).
Overriding a C++ virtual method in Rust, or otherwise implementing a C++
interface in Rust, is not supported. The workaround is a C++ subclass that
forwards to a Rust type; see
[`examples/cpp/virtual/`](https://github.com/google/crubit/tree/main/examples/cpp/virtual/).
## Debug formatting {#debug}
With the experimental `//features:record_impl_debug` feature,
Crubit automatically generates an `impl Debug` for C++ structs and classes,
unless:
* The type is abstract i.e., has pure virtual functions, in which case it
defaults to *not* implementing `Debug`.
* The type explicitly opts out using `CRUBIT_OVERRIDE_DEBUG(false)`.
The generated `impl Debug` formats all [supported fields](#fields) that
implement `Debug`. If all fields are supported and debug-formattable, and the
type has no bases, it calls `.finish()` (exhaustive). Otherwise, it calls
`.finish_non_exhaustive()` to indicate that some C++ details may be omitted
e.g., unsupported fields, other bases.
### Opting out or in {#override_debug}
To manually control whether to generate the `impl Debug`, use the
`CRUBIT_OVERRIDE_DEBUG` macro:
```live-snippet
cs/file:support/annotations.h symbol:CRUBIT_OVERRIDE_DEBUG
```
* `CRUBIT_OVERRIDE_DEBUG(false)`: Use if the C++ type already has a
hand-written Rust `Debug` implementation to avoid a trait implementation
conflict.
* `CRUBIT_OVERRIDE_DEBUG(true)`: Use to force generation for an abstract type.
IMPORTANT: Deriving `Debug` using `CRUBIT_TRAIT_DERIVE("Debug")` will be
deprecated and cause a compilation error. Use the default behavior or
`CRUBIT_OVERRIDE_DEBUG` instead.
## Packed structs {#packed}
A packed C++ struct becomes a packed Rust struct with the same layout:
* `__attribute__((packed))` (or `ABSL_ATTRIBUTE_PACKED`) on the struct becomes
`#[repr(C, packed)]`.
* A struct defined under `#pragma pack(N)` becomes `#[repr(C, packed(N))]`. If
the pragma doesn't lower the alignment of any field or base class, it
doesn't change the layout, and the struct is treated like any other struct.
For example:
```c++
struct __attribute__((packed)) PackedStruct {
uint8_t a;
uint32_t b; // At offset 1.
uint16_t c; // At offset 5.
};
```
becomes a 7-byte Rust struct with alignment 1:
```rust
#[repr(C, packed)]
pub struct PackedStruct {
pub a: u8,
pub b: u32,
pub c: u16,
}
```
Some packed structs don't get bindings:
* Structs with `__attribute__((packed))` on individual fields.
* Packed structs with an explicit alignment (such as `alignas` or
`__attribute__((aligned(N)))`) greater than the packing alignment.
A field of a packed struct whose Rust type has `#[repr(align(N))]`, directly or
in one of its own fields, becomes a private [opaque blob](#opaque_fields),
because Rust doesn't allow such types in packed structs. A struct type gets
`#[repr(align(N))]` if, for example, it has an explicit alignment, or it has an
alignment greater than 1 and has bitfields or fields whose type doesn't have
bindings.
Note: Clang doesn't pack fields whose type isn't POD for the purpose of layout
(for example, a type with a user-defined copy constructor) and warns about this
with `-Wpacked-non-pod`. If such a field has an alignment greater than 1, the
Rust bindings won't compile, because the Rust struct packs every field.
### Using fields of packed structs {#packed_fields}
Fields of a packed struct may be unaligned, so Rust doesn't allow references to
them ([E0793](https://doc.rust-lang.org/error_codes/E0793.html)). Reading a
field by value (`let b = s.b;`) works, but anything that implicitly takes a
reference, such as `println!("{}", s.b)` or `s.b.to_string()`, doesn't compile.
Copy the field out first, for example with braces:
```rust
println!("{}", { s.b });
let text = { s.b }.to_string();
```
Assigning to a field (`s.b = 5;`) works as usual. For fields that aren't `Copy`,
use raw pointers (`&raw const s.field` or `&raw mut s.field`) with
`ptr::read_unaligned` and `ptr::write_unaligned`.
### `Debug` for packed structs {#packed_debug}
Crubit ignores `CRUBIT_TRAIT_DERIVE(Debug)` on packed structs, because
`#[derive(Debug)]` takes references to the fields.
Instead, with the experimental `//features:record_impl_debug`
feature, packed structs implement `Debug` like other structs, with these
differences:
* Each field is copied out before it's printed. If a field that would be
printed isn't `Copy` (or is `mutable`, and thus wrapped in a `Cell`), no
fields are printed, and the output is `PackedStruct { .. }`, like for a
union.
* Base classes aren't printed, since they may be unaligned too.
For example, with the struct above, `format!("{s:?}")` is
`PackedStruct { a: 10, b: 200, c: 3000 }`. The tests in
[`rs_bindings_from_cc/test/struct/packed/`](/rs_bindings_from_cc/test/struct/packed/test.rs)
show more examples.
## Attributes {#attributes}
Crubit does not support most attributes on structs and their fields. If a struct
is marked using any attribute other than alignment, [packing](#packed),
`CRUBIT_*` annotations from `"support/annotations.h"` (such
as `CRUBIT_UNSAFE_BITWISE_RELOCATABLE`, which should be preferred over
`ABSL_ATTRIBUTE_TRIVIAL_ABI` in new code), or `ABSL_ATTRIBUTE_TRIVIAL_ABI`, it
will not receive bindings. If a field is marked using any other attribute (aside
from supported annotations such as `CRUBIT_*` field annotations), it will be
replaced with a private opaque blob.