Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
#### v0.11.0-kixelated.8+v0.32.2

----
- C: Render an object's exported traits (`Display`, `Debug`, `Eq`, `Hash`, `Ord`) as functions
named like the C++ binding's methods, which the backend refused before

#### v0.11.0-kixelated.7+v0.32.2

----
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ the `error_style = "expected"`, `strip_type_prefix`, and `strip_function_prefix`
collide with upstream's:

```bash
cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.7+v0.32.2
cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.8+v0.32.2
```

# How to generate bindings
Expand Down Expand Up @@ -98,11 +98,16 @@ handle is `my_object *`, released with `my_object_free`. The rest follows from a
work or has shut down, which abandons the call. Free every task: freeing a pending
one cancels the Rust future, and once `<namespace>_task_free` returns the callback has finished
or will never run.
* An object's exported traits are functions named like the C++ binding's methods:
`<object>_to_string` (`Display`), `<object>_to_debug_string` (`Debug`), `<object>_eq` and
`<object>_ne` (`Eq`), `<object>_hash` (`Hash`), and `<object>_cmp` (`Ord`). Two handles are
distinct pointers even to equal objects, so compare them with `<object>_eq`.
* Callbacks run on the default dispatcher thread unless `<namespace>_set_dispatcher` installs a
host's own, which receives `<namespace>_work *` items to run with `<namespace>_work_run`.

The C backend refuses what it cannot render faithfully, such as callback interfaces, custom and
external types, timestamps, and exported traits other than `Display` on errors.
external types, timestamps, and exported traits on records and enums (other than `Display` on
errors).

# Configuration options

Expand Down
2 changes: 1 addition & 1 deletion bindgen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uniffi-bindgen-cpp"
version = "0.11.0-kixelated.7+v0.32.2"
version = "0.11.0-kixelated.8+v0.32.2"
edition = "2021"

[dependencies]
Expand Down
46 changes: 39 additions & 7 deletions bindgen/src/bindings/c/gen_c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use askama::Template;
use heck::{ToShoutySnakeCase, ToSnakeCase};
use uniffi_bindgen::{
interface::{
AsType, Callable, DefaultValue, Enum, Field, Literal, Object, Radix, Record, Type,
AsType, Callable, DefaultValue, Enum, Field, Literal, Method, Object, Radix, Record, Type,
UniffiTrait,
},
ComponentInterface,
};
Expand Down Expand Up @@ -310,12 +311,6 @@ impl<'a> Gen<'a> {
obj.name()
);
}
if let Some(t) = obj.uniffi_traits().first() {
bail!(
"the C backend does not support exported traits on objects yet, but `{}` exports {t:?}",
obj.name()
);
}
if self.ci.is_name_used_as_error(obj.name()) {
bail!(
"the C backend does not support objects as errors, but `{}` is one",
Expand Down Expand Up @@ -970,6 +965,43 @@ impl<'a> Gen<'a> {
let call = format!("self->inner->{}", filters::fn_name(method.name()).unwrap());
self.render_callable(h, s, method, &name, Some(&c), &call)?;
}

// Exported traits call the C++ binding's method of the same name.
for t in obj.uniffi_traits() {
let methods: Vec<(&Method, &str, &str)> = match &t {
UniffiTrait::Display { fmt } => vec![(
fmt,
"to_string",
"Formats this object with Rust's `Display`.",
)],
UniffiTrait::Debug { fmt } => vec![(
fmt,
"to_debug_string",
"Formats this object with Rust's `Debug`.",
)],
UniffiTrait::Eq { eq, ne } => vec![
(
eq,
"eq",
"Whether the two objects are equal, by Rust's `Eq`.",
),
(ne, "ne", "Whether the two objects differ, by Rust's `Eq`."),
],
UniffiTrait::Hash { hash } => {
vec![(hash, "hash", "Hashes this object with Rust's `Hash`.")]
}
UniffiTrait::Ord { cmp } => vec![(
cmp,
"cmp",
"Compares the two objects by Rust's `Ord`: negative, zero, or positive.",
)],
};
for (method, short, summary) in methods {
h.push_str(&line_doc(summary));
let call = format!("self->inner->{short}");
self.render_callable(h, s, method, &format!("{c}_{short}"), Some(&c), &call)?;
}
}
Ok(())
}

Expand Down
26 changes: 26 additions & 0 deletions cpp-tests/tests/c_api/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,31 @@ static void errors(void) {
capi_error_free(NULL);
}

static void traits(void) {
capi_tag *a = capi_tag_new("a");
capi_tag *same = capi_tag_new("a");
capi_tag *b = capi_tag_new("b");
char *text;

text = capi_tag_to_string(a);
CHECK(streq(text, "#a"));
capi_string_free(text);
text = capi_tag_to_debug_string(a);
CHECK(streq(text, "CapiTag(\"a\")"));
capi_string_free(text);

/* Two handles to equal objects compare by value, not by pointer. */
CHECK(a != same);
CHECK(capi_tag_eq(a, same) && !capi_tag_ne(a, same));
CHECK(!capi_tag_eq(a, b) && capi_tag_ne(a, b));
CHECK(capi_tag_hash(a) == capi_tag_hash(same));
CHECK(capi_tag_cmp(a, b) < 0 && capi_tag_cmp(b, a) > 0 && capi_tag_cmp(a, same) == 0);

capi_tag_free(a);
capi_tag_free(same);
capi_tag_free(b);
}

static void objects(void) {
capi_store *store = NULL;
capi_store *fork;
Expand Down Expand Up @@ -508,6 +533,7 @@ int main(int argc, char **argv) {
durations();
errors();
objects();
traits();
async_calls();
capi_shutdown_dispatcher();
return 0;
Expand Down
19 changes: 19 additions & 0 deletions fixtures/c-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,25 @@ pub fn capi_flat_fail(gone: bool) -> Result<(), CapiFlatError> {
})
}

/// An object exporting every trait the C backend renders as a function.
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, uniffi::Object)]
#[uniffi::export(Debug, Display, Eq, Hash, Ord)]
pub struct CapiTag(String);

impl std::fmt::Display for CapiTag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "#{}", self.0)
}
}

#[uniffi::export]
impl CapiTag {
#[uniffi::constructor]
pub fn new(name: String) -> Arc<Self> {
Arc::new(Self(name))
}
}

/// Durations in every position: a field, an optional, and a list.
#[derive(Clone, Debug, PartialEq, uniffi::Record)]
pub struct CapiTimer {
Expand Down
Loading