diff --git a/CHANGELOG.md b/CHANGELOG.md index b6e49c2..0f8a32d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ---- diff --git a/Cargo.lock b/Cargo.lock index b466b7f..1113f11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -874,7 +874,7 @@ dependencies = [ [[package]] name = "uniffi-bindgen-cpp" -version = "0.11.0-kixelated.7+v0.32.2" +version = "0.11.0-kixelated.8+v0.32.2" dependencies = [ "anyhow", "askama 0.13.1", diff --git a/README.md b/README.md index bad0d9a..7ce7300 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 `_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: + `_to_string` (`Display`), `_to_debug_string` (`Debug`), `_eq` and + `_ne` (`Eq`), `_hash` (`Hash`), and `_cmp` (`Ord`). Two handles are + distinct pointers even to equal objects, so compare them with `_eq`. * Callbacks run on the default dispatcher thread unless `_set_dispatcher` installs a host's own, which receives `_work *` items to run with `_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 diff --git a/bindgen/Cargo.toml b/bindgen/Cargo.toml index 6f009c9..4d20ece 100644 --- a/bindgen/Cargo.toml +++ b/bindgen/Cargo.toml @@ -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] diff --git a/bindgen/src/bindings/c/gen_c.rs b/bindgen/src/bindings/c/gen_c.rs index 43bd3b9..135744f 100644 --- a/bindgen/src/bindings/c/gen_c.rs +++ b/bindgen/src/bindings/c/gen_c.rs @@ -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, }; @@ -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", @@ -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(()) } diff --git a/cpp-tests/tests/c_api/main.c b/cpp-tests/tests/c_api/main.c index 1e65995..ef4c193 100644 --- a/cpp-tests/tests/c_api/main.c +++ b/cpp-tests/tests/c_api/main.c @@ -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; @@ -508,6 +533,7 @@ int main(int argc, char **argv) { durations(); errors(); objects(); + traits(); async_calls(); capi_shutdown_dispatcher(); return 0; diff --git a/fixtures/c-api/src/lib.rs b/fixtures/c-api/src/lib.rs index 97e2862..a7c4d0b 100644 --- a/fixtures/c-api/src/lib.rs +++ b/fixtures/c-api/src/lib.rs @@ -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 { + Arc::new(Self(name)) + } +} + /// Durations in every position: a field, an optional, and a list. #[derive(Clone, Debug, PartialEq, uniffi::Record)] pub struct CapiTimer {