From eec8e16f6e583500c01d8d88bc3ad380dd9683c7 Mon Sep 17 00:00:00 2001 From: Ernesto Domingo Fuentes Date: Fri, 25 Sep 2026 13:08:14 +0200 Subject: [PATCH] Update bindgen to UniFFI v0.31.0 Signed-off-by: Ernesto Domingo Fuentes --- .github/workflows/cpp.yml | 2 +- CHANGELOG.md | 24 + Cargo.lock | 226 ++++-- Cargo.toml | 4 +- README.md | 4 +- bindgen/Cargo.toml | 4 +- bindgen/src/bindings/cpp/gen_cpp/compounds.rs | 17 +- bindgen/src/bindings/cpp/gen_cpp/custom.rs | 28 +- bindgen/src/bindings/cpp/gen_cpp/enum_.rs | 16 +- .../src/bindings/cpp/gen_cpp/filters/mod.rs | 157 ++++- .../src/bindings/cpp/gen_cpp/miscellany.rs | 2 +- bindgen/src/bindings/cpp/gen_cpp/mod.rs | 109 ++- bindgen/src/bindings/cpp/gen_cpp/object.rs | 33 +- .../src/bindings/cpp/gen_cpp/primitives.rs | 6 +- bindgen/src/bindings/cpp/gen_cpp/record.rs | 39 +- bindgen/src/bindings/cpp/mod.rs | 28 +- .../src/bindings/cpp/templates/callback.hpp | 23 +- .../cpp/templates/callback_iface_tmpl.cpp | 11 +- .../cpp/templates/cpp_scaffolding.cpp | 2 +- bindgen/src/bindings/cpp/templates/custom.hpp | 3 + bindgen/src/bindings/cpp/templates/enum.hpp | 8 +- .../src/bindings/cpp/templates/enum_tmpl.cpp | 6 +- bindgen/src/bindings/cpp/templates/err.hpp | 5 +- .../src/bindings/cpp/templates/handle_map.cpp | 27 +- bindgen/src/bindings/cpp/templates/iface.hpp | 10 + bindgen/src/bindings/cpp/templates/macros.cpp | 96 ++- bindgen/src/bindings/cpp/templates/obj.cpp | 45 +- bindgen/src/bindings/cpp/templates/obj.hpp | 56 +- .../src/bindings/cpp/templates/obj_conv.cpp | 48 +- .../src/bindings/cpp/templates/obj_conv.hpp | 4 +- bindgen/src/bindings/cpp/templates/rec.hpp | 4 +- .../bindings/cpp/templates/scaffolding.hpp | 2 +- .../cpp/templates/scaffolding/macros.cpp | 8 + .../cpp/templates/scaffolding/obj.cpp | 8 +- .../cpp/templates/scaffolding/obj.hpp | 4 +- .../src/bindings/cpp/templates/seq_tmpl.cpp | 4 +- bindgen/src/bindings/cpp/templates/types.cpp | 21 + cpp-tests/CMakeLists.txt | 3 + cpp-tests/tests/coverall/main.cpp | 12 +- cpp-tests/tests/error_types_builtin/main.cpp | 44 ++ cpp-tests/tests/proc_macro/main.cpp | 64 ++ cpp-tests/tests/record_enum_methods/main.cpp | 67 ++ cpp-tests/tests/renaming/main.cpp | 26 + cpp-tests/tests/trait_methods/main.cpp | 117 ++++ cpp-tests/tests/type_flattening/main.cpp | 25 +- docs/CONFIGURATION.md | 27 + fixtures/Cargo.toml | 31 +- fixtures/coverall/Cargo.toml | 27 + fixtures/coverall/README.md | 9 + fixtures/coverall/build.rs | 7 + fixtures/coverall/src/coverall.udl | 317 +++++++++ .../src/ffi_buffer_scaffolding_test.rs | 61 ++ fixtures/coverall/src/lib.rs | 663 ++++++++++++++++++ fixtures/coverall/src/traits.rs | 293 ++++++++ fixtures/custom-types-builtin/src/lib.rs | 4 +- fixtures/error-types-builtin/src/lib.rs | 65 ++ fixtures/ext-types-export/src/lib.rs | 3 + fixtures/ext-types-import/src/lib.rs | 18 + fixtures/record-enum-methods/Cargo.toml | 12 + fixtures/record-enum-methods/src/lib.rs | 114 +++ fixtures/renaming/Cargo.toml | 11 + fixtures/renaming/src/lib.rs | 48 ++ fixtures/renaming/uniffi.toml | 15 + fixtures/src/lib.rs | 3 + fixtures/type-flattening/src/lib.rs | 48 ++ .../type-flattening/src/type_flattening.udl | 16 + 66 files changed, 2966 insertions(+), 278 deletions(-) create mode 100644 bindgen/src/bindings/cpp/templates/iface.hpp create mode 100644 cpp-tests/tests/proc_macro/main.cpp create mode 100644 cpp-tests/tests/record_enum_methods/main.cpp create mode 100644 cpp-tests/tests/renaming/main.cpp create mode 100644 fixtures/coverall/Cargo.toml create mode 100644 fixtures/coverall/README.md create mode 100644 fixtures/coverall/build.rs create mode 100644 fixtures/coverall/src/coverall.udl create mode 100644 fixtures/coverall/src/ffi_buffer_scaffolding_test.rs create mode 100644 fixtures/coverall/src/lib.rs create mode 100644 fixtures/coverall/src/traits.rs create mode 100644 fixtures/record-enum-methods/Cargo.toml create mode 100644 fixtures/record-enum-methods/src/lib.rs create mode 100644 fixtures/renaming/Cargo.toml create mode 100644 fixtures/renaming/src/lib.rs create mode 100644 fixtures/renaming/uniffi.toml diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index 83ed170..fab6ed7 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -56,7 +56,7 @@ jobs: - name: Run tests working-directory: ${{ steps.strings.outputs.build-output-dir }} - run: ctest --build-config ${{ matrix.build_type }} + run: ctest --build-config ${{ matrix.build_type }} --output-on-failure # build-scaffolding-lib: # runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fd775a..f3d7837 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +#### v0.10.0+v0.31.0 + +---- +- Core: Update bindgen to UniFFI v0.31.0. Minimum Rust version is now `1.87` +- Core: **BREAKING** Interfaces cross the FFI as a `uint64_t` handle instead of a `void *` +- Core: **BREAKING** Trait interfaces declared without `WithForeign` now generate an abstract + base class `` and a concrete `Impl` +- Core: **BREAKING** Passing a Rust-implemented trait object back to Rust now clones its + handle, so the reference count on the Rust side is one higher than before +- Core: Add methods on records and enums +- Core: Add uniffi traits (`Display`, `Debug`, `Eq`, `Hash`, `Ord`) on records, enums and errors +- Core: Enums whose variants have no fields are generated as a C++ `enum class`, which cannot + have member functions, so their methods and uniffi traits become free functions +- Core: Add support for objects implementing external traits +- Core: Add support for custom types used as error types +- Core: Add renaming through the `uniffi.toml` file +- Core: Add `#[uniffi(default)]` without a literal, for primitives, `String`, `Bytes`, + optionals, sequences, maps, custom types, objects with a constructor that takes no + arguments, and records whose fields all have a default or a type safe to zero +- Core: Fix cases that aborted generation or produced invalid C++: optional fields with a + non-null default, enum variants with unnamed fields, arguments named with C++ keywords, + methods returning their own type, and error types passed as arguments or returned from a + callback interface. + #### v0.9.0+v0.29.4 ---- diff --git a/Cargo.lock b/Cargo.lock index 565c65f..a05f154 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,20 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d4744ed2eef2645831b441d8f5459689ade2ab27c854488fbab1fbe94fce1a7" dependencies = [ - "askama_derive", + "askama_derive 0.13.1", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75363874b771be265f4ffe307ca705ef6f3baa19011c149da8674a87f1b75c4" +dependencies = [ + "askama_derive 0.14.0", "itoa", "percent-encoding", "serde", @@ -75,7 +88,24 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d661e0f57be36a5c14c48f78d09011e67e0cb618f269cca9f2fd8d15b68c46ac" dependencies = [ - "askama_parser", + "askama_parser 0.13.0", + "basic-toml", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn", +] + +[[package]] +name = "askama_derive" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "129397200fe83088e8a68407a8e2b1f826cf0086b21ccdb866a722c8bcd3a94f" +dependencies = [ + "askama_parser 0.14.0", "basic-toml", "memchr", "proc-macro2", @@ -95,7 +125,19 @@ dependencies = [ "memchr", "serde", "serde_derive", - "winnow", + "winnow 0.7.13", +] + +[[package]] +name = "askama_parser" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6ab5630b3d5eaf232620167977f95eb51f3432fc76852328774afbd242d4358" +dependencies = [ + "memchr", + "serde", + "serde_derive", + "winnow 0.7.13", ] [[package]] @@ -311,6 +353,8 @@ checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -319,6 +363,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.175" @@ -507,11 +557,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_spanned" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "876ac351060d4f882bb1032b6369eb0aef79ad9df1ea8bc404874d8cc3d0cd98" +dependencies = [ + "serde_core", +] + [[package]] name = "siphasher" -version = "0.3.11" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" [[package]] name = "smawk" @@ -622,13 +681,43 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "toml" -version = "0.5.11" +version = "0.9.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" dependencies = [ - "serde", + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.13", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", ] +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + [[package]] name = "topological-sort" version = "0.2.2" @@ -670,8 +759,8 @@ checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" [[package]] name = "uniffi" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "cargo_metadata", @@ -684,10 +773,10 @@ dependencies = [ [[package]] name = "uniffi-bindgen-cpp" -version = "0.9.0+v0.29.4" +version = "0.10.0+v0.31.0" dependencies = [ "anyhow", - "askama", + "askama 0.13.1", "camino", "cargo_metadata", "clap", @@ -721,8 +810,11 @@ dependencies = [ "uniffi-fixture-callbacks", "uniffi-fixture-coverall", "uniffi-fixture-docstring", + "uniffi-fixture-proc-macro", "uniffi-fixture-time", "uniffi-fixture-trait-methods", + "uniffi-record-enum-methods", + "uniffi-renaming", "uniffi-reserved-field-name", "uniffi-type-flattening", ] @@ -763,25 +855,25 @@ dependencies = [ [[package]] name = "uniffi-example-arithmetic" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-example-callbacks" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-example-custom-types" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "bytes", @@ -792,7 +884,7 @@ dependencies = [ [[package]] name = "uniffi-example-geometry" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "uniffi", ] @@ -800,7 +892,7 @@ dependencies = [ [[package]] name = "uniffi-example-rondpoint" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "uniffi", ] @@ -808,7 +900,7 @@ dependencies = [ [[package]] name = "uniffi-example-sprites" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "uniffi", ] @@ -816,19 +908,19 @@ dependencies = [ [[package]] name = "uniffi-example-todolist" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "once_cell", - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-example-traits" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] @@ -850,48 +942,72 @@ dependencies = [ [[package]] name = "uniffi-fixture-callbacks" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-fixture-coverall" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" dependencies = [ "once_cell", - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-fixture-docstring" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ - "thiserror 1.0.50", + "thiserror 2.0.16", + "uniffi", +] + +[[package]] +name = "uniffi-fixture-proc-macro" +version = "0.22.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" +dependencies = [ + "lazy_static", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-fixture-time" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "chrono", - "thiserror 1.0.50", + "thiserror 2.0.16", "uniffi", ] [[package]] name = "uniffi-fixture-trait-methods" version = "0.22.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "once_cell", - "thiserror 1.0.50", + "thiserror 2.0.16", + "uniffi", +] + +[[package]] +name = "uniffi-record-enum-methods" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.16", + "uniffi", +] + +[[package]] +name = "uniffi-renaming" +version = "0.1.0" +dependencies = [ "uniffi", ] @@ -911,11 +1027,11 @@ dependencies = [ [[package]] name = "uniffi_bindgen" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", - "askama", + "askama 0.14.0", "camino", "cargo_metadata", "fs-err", @@ -936,8 +1052,8 @@ dependencies = [ [[package]] name = "uniffi_build" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "camino", @@ -946,8 +1062,8 @@ dependencies = [ [[package]] name = "uniffi_core" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "bytes", @@ -957,8 +1073,8 @@ dependencies = [ [[package]] name = "uniffi_internal_macros" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "indexmap", @@ -969,8 +1085,8 @@ dependencies = [ [[package]] name = "uniffi_macros" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "camino", "fs-err", @@ -985,8 +1101,8 @@ dependencies = [ [[package]] name = "uniffi_meta" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "siphasher", @@ -996,8 +1112,8 @@ dependencies = [ [[package]] name = "uniffi_pipeline" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "heck 0.5.0", @@ -1008,8 +1124,8 @@ dependencies = [ [[package]] name = "uniffi_udl" -version = "0.29.4" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +version = "0.31.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "anyhow", "textwrap", @@ -1037,7 +1153,7 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "weedle2" version = "5.0.0" -source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.29.4#00cd7e313cf73c78637161831ff17f8f53f7b824" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.0#309762f55db3f0548194a9ceba3027fa64b18a93" dependencies = [ "nom", ] @@ -1213,3 +1329,9 @@ checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" dependencies = [ "memchr", ] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" diff --git a/Cargo.toml b/Cargo.toml index 06da37f..ae34e45 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,5 +4,5 @@ members = ["bindgen", "fixtures"] resolver = "2" [workspace.dependencies] -uniffi = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi_bindgen = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4", features = ["cargo-metadata"] } +uniffi = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi_bindgen = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0", features = ["cargo-metadata"] } diff --git a/README.md b/README.md index b8d8ee5..3d4c7f6 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ as a separate project from `uniffi-rs`, as per # How to install -Minimum Rust version required to install `uniffi-bindgen-cpp` is `1.74`. +Minimum Rust version required to install `uniffi-bindgen-cpp` is `1.87`. Newer Rust versions should also work fine. ```bash -cargo install uniffi-bindgen-cpp --git https://github.com/NordSecurity/uniffi-bindgen-cpp --tag v0.8.1+v0.29.4 +cargo install uniffi-bindgen-cpp --git https://github.com/NordSecurity/uniffi-bindgen-cpp --tag v0.10.0+v0.31.0 ``` # How to generate bindings diff --git a/bindgen/Cargo.toml b/bindgen/Cargo.toml index 468c458..b0cb23c 100644 --- a/bindgen/Cargo.toml +++ b/bindgen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "uniffi-bindgen-cpp" -version = "0.9.0+v0.29.4" +version = "0.10.0+v0.31.0" edition = "2021" [dependencies] @@ -13,6 +13,6 @@ paste = "1" serde = "1" topological-sort = "0.2.2" textwrap = "0.16.0" -toml = "0.5" +toml = "0.9" uniffi_bindgen = { workspace = true } cargo_metadata = "0.19" diff --git a/bindgen/src/bindings/cpp/gen_cpp/compounds.rs b/bindgen/src/bindings/cpp/gen_cpp/compounds.rs index 1443802..878d7b9 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/compounds.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/compounds.rs @@ -1,5 +1,8 @@ use crate::bindings::cpp::CodeType; -use uniffi_bindgen::{backend::Type, interface::Literal, ComponentInterface}; +use uniffi_bindgen::{ + interface::{Literal, Type}, + ComponentInterface, +}; use crate::bindings::cpp::gen_cpp::filters::CppCodeOracle; @@ -53,6 +56,10 @@ impl CodeType for OptionalCodeType { _ => CppCodeOracle.find(&self.inner).literal(literal, ci), } } + + fn default_is_value_init(&self) -> bool { + true // nullopt, empty vector, empty map + } } #[derive(Debug)] @@ -87,6 +94,10 @@ impl CodeType for SequenceCodeType { _ => CppCodeOracle.find(&self.inner).literal(literal, ci), } } + + fn default_is_value_init(&self) -> bool { + true // nullopt, empty vector, empty map + } } #[derive(Debug)] @@ -132,4 +143,8 @@ impl CodeType for MapCodeType { _ => CppCodeOracle.find(&self.value).literal(literal, ci), } } + + fn default_is_value_init(&self) -> bool { + true // nullopt, empty vector, empty map + } } diff --git a/bindgen/src/bindings/cpp/gen_cpp/custom.rs b/bindgen/src/bindings/cpp/gen_cpp/custom.rs index 85d8b1f..64cc45a 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/custom.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/custom.rs @@ -1,16 +1,26 @@ -use uniffi_bindgen::ComponentInterface; +use uniffi_bindgen::{ + interface::{DefaultValue, Literal, Type}, + ComponentInterface, +}; -use crate::bindings::cpp::{gen_cpp::filters::external_namespace_prefix, CodeType}; +use crate::bindings::cpp::{ + gen_cpp::filters::external_namespace_prefix, gen_cpp::filters::CppCodeOracle, CodeType, +}; #[derive(Debug)] pub struct CustomCodeType { name: String, module_path: String, + builtin: Type, } impl CustomCodeType { - pub fn new(name: String, module_path: String) -> Self { - CustomCodeType { name, module_path } + pub fn new(name: String, module_path: String, builtin: Type) -> Self { + CustomCodeType { + name, + module_path, + builtin, + } } } @@ -26,4 +36,14 @@ impl CodeType for CustomCodeType { fn canonical_name(&self) -> String { format!("Type{}", self.name) } + + // Defaults come from the wrapped builtin. Correct while the custom type is a typedef of it, + // which stops being true once a `type_name` is configured. + fn literal(&self, literal: &Literal, ci: &ComponentInterface) -> String { + CppCodeOracle.find(&self.builtin).literal(literal, ci) + } + + fn default(&self, default: &DefaultValue, ci: &ComponentInterface) -> String { + CppCodeOracle.find(&self.builtin).default(default, ci) + } } diff --git a/bindgen/src/bindings/cpp/gen_cpp/enum_.rs b/bindgen/src/bindings/cpp/gen_cpp/enum_.rs index 6dd4ef9..6ac0b85 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/enum_.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/enum_.rs @@ -1,4 +1,7 @@ -use uniffi_bindgen::{backend::Literal, ComponentInterface}; +use uniffi_bindgen::{ + interface::{DefaultValue, Literal}, + ComponentInterface, +}; use crate::bindings::cpp::{ gen_cpp::filters::external_namespace_prefix, gen_cpp::filters::CppCodeOracle, CodeType, @@ -39,4 +42,15 @@ impl CodeType for EnumCodeType { fn literal(&self, _: &Literal, _ci: &ComponentInterface) -> String { unreachable!(); } + + fn default(&self, default: &DefaultValue, ci: &ComponentInterface) -> String { + match default { + DefaultValue::Literal(literal) => self.literal(literal, ci), + // Variants are numbered from 1, so a value-initialised enum holds 0 + DefaultValue::Default => unimplemented!( + "`#[uniffi(default)]` without a literal is not supported for enum {}", + self.type_label(ci) + ), + } + } } diff --git a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs index b25fc02..68a46c2 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs @@ -1,7 +1,9 @@ -use askama; use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase}; use uniffi_bindgen::{ - interface::{Argument, AsType, FfiType, Literal, Object, Type, Variant}, + interface::{ + Argument, AsType, DefaultValue, FfiType, Literal, Method, Object, Type, UniffiTraitMethods, + Variant, + }, ComponentInterface, }; @@ -156,7 +158,7 @@ impl CppCodeOracle { pub(crate) fn object_names(&self, obj: &Object) -> (String, String) { let class_name = self.class_name(obj.name()); - if obj.has_callback_interface() { + if obj.is_trait_interface() { let impl_name = format!("{class_name}Impl"); (class_name, impl_name) } else { @@ -165,6 +167,111 @@ impl CppCodeOracle { } } +pub(crate) fn object_bases(obj: &Object, ci: &ComponentInterface) -> Result { + let (interface_name, _) = CppCodeOracle.object_names(obj); + let mut bases = Vec::new(); + + if obj.is_trait_interface() { + bases.push(format!("public {interface_name}")); + } + + for trait_impl in obj.trait_impls() { + if let Type::Object { + module_path, name, .. + } = &trait_impl.trait_ty + { + bases.push(format!( + "public {}{}", + external_namespace_prefix(ci, module_path), + CppCodeOracle.class_name(name) + )); + } + } + + if ci.is_name_used_as_error(obj.name()) { + bases.push("public std::exception".to_string()); + } + + let result = if bases.is_empty() { + String::new() + } else { + format!(" : {}", bases.join(", ")) + }; + + Ok(result) +} + +pub(crate) struct UniffiTraitMethodInfo<'a> { + pub name: &'static str, + pub doc: &'static str, + pub return_type: Type, + pub takes_other: bool, + pub method: &'a Method, +} + +pub(crate) fn uniffi_trait_list( + traits: &UniffiTraitMethods, +) -> Result>> { + let entries = [ + ( + &traits.display_fmt, + "to_string", + "Returns a string representation, internally calls Rust's `Display` trait.", + Type::String, + false, + ), + ( + &traits.debug_fmt, + "to_debug_string", + "Returns a debug representation, internally calls Rust's `Debug` trait.", + Type::String, + false, + ), + ( + &traits.eq_eq, + "eq", + "Equality check, internally calls Rust's `Eq` trait.", + Type::Boolean, + true, + ), + ( + &traits.eq_ne, + "ne", + "Inequality check, internally calls Rust's `Eq` trait.", + Type::Boolean, + true, + ), + ( + &traits.hash_hash, + "hash", + "Returns a hash of the value, internally calls Rust's `Hash` trait.", + Type::UInt64, + false, + ), + ( + &traits.ord_cmp, + "cmp", + "Comparison, internally calls Rust's `Ord` trait. Returns `Ordering` indicating \ + less (-1), equal (0) or greater (1).", + Type::Int8, + true, + ), + ]; + + Ok(entries + .into_iter() + .filter_map(|(method, name, doc, return_type, takes_other)| { + method.as_ref().map(|method| UniffiTraitMethodInfo { + name, + doc, + return_type, + takes_other, + method, + }) + }) + .collect()) +} + pub(crate) trait AsCodeType { fn as_codetype(&self) -> Box; } @@ -212,8 +319,10 @@ impl AsCodeType for T { value_type, } => Box::new(compounds::MapCodeType::new(*key_type, *value_type)), Type::Custom { - name, module_path, .. - } => Box::new(custom::CustomCodeType::new(name, module_path)), + name, + module_path, + builtin, + } => Box::new(custom::CustomCodeType::new(name, module_path, *builtin)), } } } @@ -241,13 +350,21 @@ pub(crate) fn ffi_converter_name(as_ct: &impl AsCodeType) -> Result { pub(crate) fn ffi_error_converter_name(as_type: &impl AsType) -> Result { let mut name = ffi_converter_name(as_type)?; - if matches!(&as_type.as_type(), Type::Object { .. }) { + if is_object_at_root(&as_type.as_type()) { name.push_str("__as_error"); } Ok(name) } +fn is_object_at_root(type_: &Type) -> bool { + match type_ { + Type::Object { .. } => true, + Type::Custom { builtin, .. } => is_object_at_root(builtin), + _ => false, + } +} + pub(crate) fn ffi_struct_name(nm: &str) -> Result { Ok(format!("Uniffi{}", nm)) } @@ -272,19 +389,23 @@ pub(crate) fn object_names(obj: &Object) -> Result<(String, String)> { Ok(CppCodeOracle.object_names(obj)) } -pub(crate) fn literal_cpp( - literal: &Literal, - as_ct: &impl AsCodeType, +pub(crate) fn default_cpp( + default: &DefaultValue, + as_type: &impl AsType, enum_style: &EnumStyle, ci: &ComponentInterface, ) -> Result { - match literal { - Literal::Enum(name, _) => Ok(format!( + match default { + DefaultValue::Literal(Literal::Enum(name, _)) => Ok(format!( "{}::{}", - as_ct.as_codetype().type_label(ci), - CppCodeOracle.enum_variant_name(&name, enum_style), + as_type.as_codetype().type_label(ci), + CppCodeOracle.enum_variant_name(name, enum_style), )), - _ => Ok(as_ct.as_codetype().literal(literal, ci)), + DefaultValue::Literal(Literal::Some { inner }) => match as_type.as_type() { + Type::Optional { inner_type } => default_cpp(inner, &inner_type, enum_style, ci), + _ => Ok(as_type.as_codetype().default(default, ci)), + }, + _ => Ok(as_type.as_codetype().default(default, ci)), } } @@ -339,7 +460,7 @@ pub(crate) fn ffi_type_name(ffi_type: &FfiType) -> Result { FfiType::Int64 => "int64_t".into(), FfiType::Float32 => "float".into(), FfiType::Float64 => "double".into(), - FfiType::RustArcPtr(_) | FfiType::VoidPointer => "void *".into(), + FfiType::VoidPointer => "void *".into(), FfiType::RustBuffer(_) => "RustBuffer".into(), FfiType::ForeignBytes => "ForeignBytes".into(), FfiType::Callback(_) => "void *".into(), @@ -380,9 +501,11 @@ pub(crate) fn by_ref(ci: &ComponentInterface, arg: &Argument) -> bool { } pub(crate) fn parameter(arg: &Argument, ci: &ComponentInterface) -> Result { + let arg_name = CppCodeOracle.var_name(arg.name()); + Ok(match by_ref(ci, arg) { - true => format!("const {} &{}", arg.as_codetype().type_label(ci), arg.name()), - false => format!("{} {}", arg.as_codetype().type_label(ci), arg.name()), + true => format!("const {} &{}", arg.as_codetype().type_label(ci), arg_name), + false => format!("{} {}", arg.as_codetype().type_label(ci), arg_name), }) } diff --git a/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs b/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs index a8fa315..ef32ec7 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs @@ -1,6 +1,6 @@ use crate::bindings::cpp::CodeType; use paste::paste; -use uniffi_bindgen::{backend::Literal, ComponentInterface}; +use uniffi_bindgen::{interface::Literal, ComponentInterface}; macro_rules! impl_code_type_for_miscellany { ($T:ty, $label:literal, $canonical_name:literal) => { diff --git a/bindgen/src/bindings/cpp/gen_cpp/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/mod.rs index e6b0ae0..fa9291c 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/mod.rs @@ -20,22 +20,17 @@ use askama::Template; use filters::CppCodeOracle; use serde::{Deserialize, Serialize}; use topological_sort::{DependencyLink, TopologicalSort}; -use uniffi_bindgen::{interface::*, ComponentInterface}; +use uniffi_bindgen::{interface::*, Component, ComponentInterface}; use crate::bindings::cpp::gen_cpp::filters::callback_interface_name; -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, Default)] pub enum EnumStyle { Capitalized, + #[default] Google, } -impl Default for EnumStyle { - fn default() -> Self { - EnumStyle::Google - } -} - #[derive(Clone, Deserialize, Serialize, Debug, Default)] struct CustomTypesConfig { imports: Option>, @@ -59,6 +54,27 @@ pub(crate) struct Config { custom_types: HashMap, #[serde(default)] enum_style: EnumStyle, + #[serde(default)] + rename: toml::Table, +} + +pub(crate) fn apply_renames(components: &mut [Component]) { + let renames: HashMap = components + .iter() + .filter(|component| !component.config.rename.is_empty()) + .map(|component| { + ( + component.ci.crate_name().to_string(), + component.config.rename.clone(), + ) + }) + .collect(); + + if !renames.is_empty() { + for component in components.iter_mut() { + rename(&mut component.ci, &renames); + } + } } #[derive(Clone, Deserialize, Serialize, Debug, Default)] @@ -109,7 +125,7 @@ impl<'a> ScaffoldingHeader<'a> { pub fn scaffolding_definitions(&self) -> impl Iterator + '_ { self.ci .callback_interface_definitions() - .into_iter() + .iter() .map(|cb| cb.vtable_definition()) .chain( self.ci @@ -168,22 +184,57 @@ impl<'a> CppWrapperHeader<'a> { .ci .iter_local_types() .filter_map(|type_| { - // We take into account only the Record and Enum types, as they are the - // only types that can have member variables that reference other structures + // Records and Enums are ordered by their field types, as those are embedded by + // value. Only field types matter. A signature only needs a forward + // declaration, which we always emit, so including them would make a method + // returning its own type look like a cycle. + // + // Objects are ordered by the traits they implement. Those become base classes, + // and a base class has to be complete since a forward declaration is not enough + // for inheritance. match type_ { - Type::Record { name, .. } => self - .ci - .get_record_definition(name.as_str()) - .map(|record| (name, record.iter_types())), - Type::Enum { name, .. } => self - .ci - .get_enum_definition(name.as_str()) - .map(|enum_| (name, enum_.iter_types())), + Type::Record { name, .. } => { + self.ci.get_record_definition(name.as_str()).map(|record| { + ( + name, + record + .fields() + .iter() + .flat_map(Field::iter_types) + .collect::>(), + ) + }) + } + Type::Enum { name, .. } => { + self.ci.get_enum_definition(name.as_str()).map(|enum_| { + ( + name, + enum_ + .variants() + .iter() + .flat_map(Variant::iter_types) + .collect::>(), + ) + }) + } + Type::Object { name, .. } => { + self.ci.get_object_definition(name).map(|object| { + ( + name, + object + .trait_impls() + .iter() + .map(|trait_impl| &trait_impl.trait_ty) + .collect::>(), + ) + }) + } _ => None, } }) .flat_map(|(name, types)| { types + .into_iter() .filter_map(type_name) .map(|field_name| DependencyLink { prec: field_name, @@ -192,19 +243,21 @@ impl<'a> CppWrapperHeader<'a> { }) .collect::>(); + let local_types: HashMap<&str, &Type> = self + .ci + .iter_local_types() + .filter_map(|type_| type_name(type_).map(|name| (name, type_))) + .collect(); + let mut sorted: Vec = Vec::new(); while !definition_topology.peek_all().is_empty() { let list = definition_topology.pop_all(); for name in list { - match self.ci.get_type(name) { - // External types are defined in their own namespace's header with their own - // converters declared, which we `#include`. They must not enter the local - // definition ordering, or we'd try to emit a definition we don't have. - Some(type_) if self.ci.is_external(&type_) => {} - Some(type_) => sorted.push(type_.clone()), - None => { - panic!("Type {} not found", name) - } + // External types are defined in their own namespace's header with their own + // converters declared, which we `#include`. They must not enter the local + // definition ordering, or we'd try to emit a definition we don't have. + if let Some(type_) = local_types.get(name) { + sorted.push((*type_).clone()); } } } diff --git a/bindgen/src/bindings/cpp/gen_cpp/object.rs b/bindgen/src/bindings/cpp/gen_cpp/object.rs index 3088cba..c7536bd 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/object.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/object.rs @@ -1,4 +1,7 @@ -use uniffi_bindgen::{backend::Literal, interface::ObjectImpl, ComponentInterface}; +use uniffi_bindgen::{ + interface::{DefaultValue, Literal, Object, ObjectImpl}, + ComponentInterface, +}; use crate::bindings::cpp::{ gen_cpp::filters::callback_interface_name, gen_cpp::filters::external_namespace_prefix, @@ -39,6 +42,34 @@ impl CodeType for ObjectCodeType { unreachable!(); } + fn default(&self, default: &DefaultValue, ci: &ComponentInterface) -> String { + match default { + DefaultValue::Literal(literal) => self.literal(literal, ci), + // An object is constructed through its primary constructor, which is emitted as a + // static `init()`. Only a constructor taking no arguments can serve as the default. + DefaultValue::Default => { + let takes_no_args = ci + .get_object_definition(&self.id) + .and_then(Object::primary_constructor) + .is_some_and(|ctor| ctor.arguments().is_empty()); + + if takes_no_args { + format!( + "{}{}::init()", + external_namespace_prefix(ci, &self.module_path), + self.canonical_name() + ) + } else { + unimplemented!( + "`#[uniffi(default)]` is not supported for {}: it requires a constructor \ + taking no arguments", + self.type_label(ci) + ) + } + } + } + } + fn initialization_fn(&self) -> Option { self.imp.has_callback_interface().then(|| { format!( diff --git a/bindgen/src/bindings/cpp/gen_cpp/primitives.rs b/bindgen/src/bindings/cpp/gen_cpp/primitives.rs index 19db704..dbd6aaa 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/primitives.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/primitives.rs @@ -1,6 +1,6 @@ use crate::bindings::cpp::CodeType; use paste::paste; -use uniffi_bindgen::{backend::Literal, interface::Radix, ComponentInterface}; +use uniffi_bindgen::{interface::Literal, interface::Radix, ComponentInterface}; fn render_literal(literal: &Literal) -> String { match literal { @@ -45,6 +45,10 @@ macro_rules! impl_code_type_for_primitive { fn literal(&self, literal: &Literal, _ci: &ComponentInterface) -> String { render_literal(&literal) } + + fn default_is_value_init(&self) -> bool { + true // 0, false, "", empty byte + } } } }; diff --git a/bindgen/src/bindings/cpp/gen_cpp/record.rs b/bindgen/src/bindings/cpp/gen_cpp/record.rs index e15ce0d..ea9fb4f 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/record.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/record.rs @@ -1,9 +1,32 @@ -use uniffi_bindgen::{backend::Literal, ComponentInterface}; +use uniffi_bindgen::{ + interface::{AsType, DefaultValue, Literal, Type}, + ComponentInterface, +}; use crate::bindings::cpp::{ gen_cpp::filters::external_namespace_prefix, gen_cpp::filters::CppCodeOracle, CodeType, }; +/// Whether `T()` is a valid way to construct this record. It zeroes every field lacking an +/// initialiser of its own. +fn is_value_initialisable(name: &str, ci: &ComponentInterface) -> bool { + ci.get_record_definition(name).is_some_and(|record| { + record.fields().iter().all(|field| { + field.default_value().is_some() + || match field.as_type() { + // 0 is no variant since they are numbered from 1. A non-flat enum also keeps + // its default constructor private. + Type::Enum { .. } => false, + // 0 leaves a null handle, which `lower` dereferences. + Type::Object { .. } | Type::CallbackInterface { .. } => false, + Type::Record { name, .. } => is_value_initialisable(&name, ci), + Type::Custom { .. } => false, + _ => true, + } + }) + }) +} + #[derive(Debug)] pub(crate) struct RecordCodeType { id: String, @@ -32,4 +55,18 @@ impl CodeType for RecordCodeType { fn literal(&self, _literal: &Literal, _ci: &ComponentInterface) -> String { unreachable!(); } + + fn default(&self, default: &DefaultValue, ci: &ComponentInterface) -> String { + match default { + DefaultValue::Literal(literal) => self.literal(literal, ci), + DefaultValue::Default if is_value_initialisable(&self.id, ci) => { + format!("{}()", self.type_label(ci)) + } + DefaultValue::Default => unimplemented!( + "`#[uniffi(default)]` is not supported for {}: it has a field with no default \ + of its own that cannot be value-initialised", + self.type_label(ci) + ), + } + } } diff --git a/bindgen/src/bindings/cpp/mod.rs b/bindgen/src/bindings/cpp/mod.rs index 7b938e7..8833d70 100644 --- a/bindgen/src/bindings/cpp/mod.rs +++ b/bindgen/src/bindings/cpp/mod.rs @@ -5,7 +5,8 @@ use std::{fmt::Debug, fs}; use anyhow::Result; use serde::{Deserialize, Serialize}; use uniffi_bindgen::{ - backend::Literal, BindingGenerator, Component, ComponentInterface, GenerationSettings, + interface::DefaultValue, interface::Literal, BindingGenerator, Component, ComponentInterface, + GenerationSettings, }; use self::gen_cpp::{generate_cpp_bindings, Bindings}; @@ -51,6 +52,24 @@ pub trait CodeType: Debug { unimplemented!("Unimplemented for {}", self.type_label(ci)) } + /// Whether `T()` is the right way to construct this type with no arguments. + fn default_is_value_init(&self) -> bool { + false + } + + fn default(&self, default: &DefaultValue, ci: &ComponentInterface) -> String { + match default { + DefaultValue::Literal(literal) => self.literal(literal, ci), + DefaultValue::Default if self.default_is_value_init() => { + format!("{}()", self.type_label(ci)) + } + DefaultValue::Default => unimplemented!( + "`#[uniffi(default)]` without a literal is not supported for {}", + self.type_label(ci) + ), + } + } + /// Name of the FfiConverter fn ffi_converter_name(&self) -> String { format!("FfiConverter{}", self.canonical_name()) @@ -82,9 +101,10 @@ impl BindingGenerator for CppBindingGenerator { fn update_component_configs( &self, _settings: &GenerationSettings, - _components: &mut Vec>, + components: &mut Vec>, ) -> Result<()> { - return Ok(()); + gen_cpp::apply_renames(components); + Ok(()) } fn write_bindings( @@ -107,7 +127,7 @@ impl BindingGenerator for CppBindingGenerator { scaffolding_header, header, source, - } = generate_cpp_bindings(&ci, &config)?; + } = generate_cpp_bindings(ci, config)?; let scaffolding_header_path = settings .out_dir diff --git a/bindgen/src/bindings/cpp/templates/callback.hpp b/bindgen/src/bindings/cpp/templates/callback.hpp index 54efb62..e3e88b6 100644 --- a/bindgen/src/bindings/cpp/templates/callback.hpp +++ b/bindgen/src/bindings/cpp/templates/callback.hpp @@ -2,32 +2,25 @@ {%- let canonical_type_name = typ|canonical_name %} {%- let trait_impl = canonical_type_name|callback_interface_name %} -{% call macros::docstring_value(interface_docstring, 0) %} -struct {{ interface_name }} { - virtual ~{{ interface_name }}() {} - - {%- for method in methods.iter() %} - {%- call macros::docstring(method, 4) %} - virtual - {% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} - {{- method.name()|fn_name }}({% call macros::param_list(method) %}) = 0; - {%- endfor %} -}; +{% include "iface.hpp" %} namespace uniffi { struct {{ trait_impl }} { + static void uniffi_free(uint64_t uniffi_handle); + static uint64_t uniffi_clone(uint64_t uniffi_handle); + static void init(); + {%- for (ffi_callback, method) in vtable_methods.iter() %} static {% call macros::ffi_return_type(ffi_callback) %} {{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}); {%- endfor %} - static void uniffi_free(uint64_t uniffi_handle); - static void init(); private: - static inline {{ vtable|ffi_type_name }} vtable = {{ vtable|ffi_type_name}} { + static inline {{ vtable|ffi_type_name }} vtable = {{ vtable|ffi_type_name }} { + .uniffi_free = reinterpret_cast(&uniffi_free), + .uniffi_clone = reinterpret_cast(&uniffi_clone), {%- for (ffi_callback, meth) in vtable_methods.iter() %} .{{ meth.name()|var_name }} = reinterpret_cast(&{{ meth.name()|var_name }}), {%- endfor %} - .uniffi_free = reinterpret_cast(&uniffi_free) }; }; } diff --git a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp index d881585..42a6679 100644 --- a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp @@ -23,7 +23,7 @@ {% match method.return_type() %} {% when Some(t) %} auto write_value = [&]({{ t|type_name(ci) }} v) { - uniffi_out_return = {{ t|lower_fn }}(v); + uniffi_out_return = {{ t|lower_fn }}({{ t.as_type()|cpp_deref(ci) }}v); }; {% when None %} auto write_value = [](){}; @@ -38,10 +38,15 @@ } {%- endfor %} +void {{ trait_impl }}::init() { + {{ ffi_init_callback.name() }}(vtable); +} + void {{ trait_impl }}::uniffi_free(uint64_t uniffi_handle) { {{ ffi_converter_name }}::handle_map.erase(uniffi_handle); } -void {{ trait_impl }}::init() { - {{ ffi_init_callback.name() }}(vtable); +uint64_t {{ trait_impl }}::uniffi_clone(uint64_t uniffi_handle) { + return {{ ffi_converter_name }}::handle_map.clone(uniffi_handle); } + diff --git a/bindgen/src/bindings/cpp/templates/cpp_scaffolding.cpp b/bindgen/src/bindings/cpp/templates/cpp_scaffolding.cpp index 55bd69a..7c16d2c 100644 --- a/bindgen/src/bindings/cpp/templates/cpp_scaffolding.cpp +++ b/bindgen/src/bindings/cpp/templates/cpp_scaffolding.cpp @@ -197,7 +197,7 @@ UNIFFI_EXPORT {%- call macros::fn_definition(ffi_ctor) %} { {%- for arg in ctor.arguments() %} {{- arg|lift_fn }}({{ arg.name()|var_name }}){% if !loop.last %}, {% endif -%} {% endfor %}); - return (void*){{ obj.name() }}_map.insert(obj); + return (uint64_t){{ obj.name() }}_map.insert(obj); } {% endfor %} diff --git a/bindgen/src/bindings/cpp/templates/custom.hpp b/bindgen/src/bindings/cpp/templates/custom.hpp index 2c2dfe1..cd7d68a 100644 --- a/bindgen/src/bindings/cpp/templates/custom.hpp +++ b/bindgen/src/bindings/cpp/templates/custom.hpp @@ -13,4 +13,7 @@ struct {{ typ|ffi_converter_name }} { {%- endmatch %} {%- else -%} typedef struct {{ builtin|ffi_converter_name }} {{ typ|ffi_converter_name }}; +{%- if ci.is_name_used_as_error(name) && typ|ffi_error_converter_name != typ|ffi_converter_name %} +typedef struct {{ builtin|ffi_error_converter_name }} {{ typ|ffi_error_converter_name }}; +{% endif %} {%- endmatch %} diff --git a/bindgen/src/bindings/cpp/templates/enum.hpp b/bindgen/src/bindings/cpp/templates/enum.hpp index bcb687c..56d9673 100644 --- a/bindgen/src/bindings/cpp/templates/enum.hpp +++ b/bindgen/src/bindings/cpp/templates/enum.hpp @@ -10,6 +10,8 @@ enum class {{ type_name }}: int32_t { {%- endif %} {%- endfor %} }; +{%- call macros::method_free_decls(e.methods(), type_name) %} +{%- call macros::uniffi_trait_free_decls(e.uniffi_trait_methods(), type_name) %} {%- else %} namespace uniffi { struct {{ ffi_converter_name }}; @@ -24,9 +26,9 @@ struct {{ type_name }} { struct {{ variant|variant_name(config.enum_style) }} { {%- for field in variant.fields() %} {%- call macros::docstring(field, 8) %} - {{ field|type_name(ci) }} {{ field.name()|var_name }} + {{ field|type_name(ci) }} {% call macros::field_name(field, loop.index) %} {%- match field.default_value() %} - {%- when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style, ci) }};{%- else -%}; + {%- when Some with (default) %} = {{ default|default_cpp(field, config.enum_style, ci) }};{%- else -%}; {%- endmatch %} {%- endfor %} }; @@ -55,6 +57,8 @@ struct {{ type_name }} { const std::variant<{% for variant in e.variants() %}{{ variant|variant_name(config.enum_style) }}{% if !loop.last %}, {% endif %}{% endfor %}> &get_variant() const { return variant; } + {%- call macros::method_decls(e.methods(), "", " const") %} + {%- call macros::uniffi_trait_decls(e.uniffi_trait_methods(), type_name) %} private: std::variant<{% for variant in e.variants() %}{{ variant|variant_name(config.enum_style) }}{% if !loop.last %}, {% endif %}{% endfor %}> variant; diff --git a/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp b/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp index 48b947c..602890c 100644 --- a/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp @@ -74,7 +74,7 @@ RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { case {{ loop.index }}: return {{ type_name }}::{{ variant|variant_name(config.enum_style) }} { {%- for field in variant.fields() %} - .{{field.name()|var_name}} = {{ field|read_fn }}(stream), + .{% call macros::field_name(field, loop.index) %} = {{ field|read_fn }}(stream), {%- endfor %} }; {% endfor %} @@ -93,7 +93,7 @@ void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} & {%- for variant in e.variants() %} {% if !loop.first %}else {% endif %}if constexpr (std::is_same_v) { {%- for field in variant.fields() %} - {{ field|write_fn }}(stream, {{ field.as_type()|cpp_deref(ci) }}arg.{{ field.name()|var_name }}); + {{ field|write_fn }}(stream, {{ field.as_type()|cpp_deref(ci) }}arg.{% call macros::field_name(field, loop.index) %}); {%- endfor %} } {%- endfor %} @@ -114,7 +114,7 @@ uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name|class_name {% if !loop.first %}else {% endif %}if constexpr (std::is_same_v) { uint64_t size = 0; {%- for field in variant.fields() %} - size += {{ field|allocation_size_fn }}({{ field.as_type()|cpp_deref(ci) }}arg.{{ field.name()|var_name }}); + size += {{ field|allocation_size_fn }}({{ field.as_type()|cpp_deref(ci) }}arg.{% call macros::field_name(field, loop.index) %}); {%- endfor %} return size; } diff --git a/bindgen/src/bindings/cpp/templates/err.hpp b/bindgen/src/bindings/cpp/templates/err.hpp index bcec06f..ec04ac6 100644 --- a/bindgen/src/bindings/cpp/templates/err.hpp +++ b/bindgen/src/bindings/cpp/templates/err.hpp @@ -18,6 +18,9 @@ struct {{ class_name }}: std::runtime_error { throw *this; } + {% call macros::method_decls(e.methods(), "", " const") %} + {%- call macros::uniffi_trait_decls(e.uniffi_trait_methods(), class_name) %} + protected: virtual int32_t get_variant_idx() const { return 0; @@ -35,7 +38,7 @@ struct {{ variant.name()|class_name }}: {{ class_name }} { {%- for field in variant.fields() %} {{ field|type_name(ci) }} {% call macros::field_name(field, loop.index) %} {%- match field.default_value() %} - {% when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style, ci) }};{% else %}; + {% when Some with (default) %} = {{ default|default_cpp(field, config.enum_style, ci) }};{% else %}; {%- endmatch %} {%- endfor %} diff --git a/bindgen/src/bindings/cpp/templates/handle_map.cpp b/bindgen/src/bindings/cpp/templates/handle_map.cpp index 8607aa3..7fe1986 100644 --- a/bindgen/src/bindings/cpp/templates/handle_map.cpp +++ b/bindgen/src/bindings/cpp/templates/handle_map.cpp @@ -1,4 +1,3 @@ - template struct HandleMap { HandleMap() = default; @@ -11,12 +10,13 @@ template struct HandleMap { uint64_t insert(std::shared_ptr impl) { std::lock_guard guard(this->mutex); - auto handle = this->cur_handle; + return this->insert_locked(impl); + } - this->map.insert({ handle, impl }); - this->cur_handle += 1; + uint64_t clone(uint64_t handle) { + std::lock_guard guard(this->mutex); - return handle; + return this->insert_locked(this->map.at(handle)); } void erase(uint64_t handle) { @@ -31,6 +31,7 @@ template struct HandleMap { } } } + private: HandleMap(const HandleMap &) = delete; HandleMap(HandleMap &&) = delete; @@ -39,6 +40,20 @@ template struct HandleMap { HandleMap &operator=(HandleMap &&) = delete; std::mutex mutex; - uint64_t cur_handle = 0; + /// Rust handles are generated by leaking a raw pointer. + /// Foreign handles are generated with a handle map that only generates odd values. + /// * 0 is an invalid value. + /// * The lowest bit will always be set for foreign handles and never set for Rust ones + uint64_t cur_handle = 1; std::map> map; + + + uint64_t insert_locked(std::shared_ptr impl) { + auto handle = this->cur_handle; + + this->map.insert({ handle, impl }); + this->cur_handle += 2; + + return handle; + } }; diff --git a/bindgen/src/bindings/cpp/templates/iface.hpp b/bindgen/src/bindings/cpp/templates/iface.hpp new file mode 100644 index 0000000..f260095 --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/iface.hpp @@ -0,0 +1,10 @@ +{% call macros::docstring_value(interface_docstring, 0) %} +struct {{ interface_name }} { + virtual ~{{ interface_name }}() {} + + {%- call macros::method_decls(methods, "virtual ", " = 0") %} + + {%- if ci.is_name_used_as_error(name) %} + virtual void throw_underlying() = 0; + {%- endif %} +}; \ No newline at end of file diff --git a/bindgen/src/bindings/cpp/templates/macros.cpp b/bindgen/src/bindings/cpp/templates/macros.cpp index 934ac89..7252e45 100644 --- a/bindgen/src/bindings/cpp/templates/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/macros.cpp @@ -8,10 +8,10 @@ nullptr {%- endmatch %} {%- if !func.arguments().is_empty() %}, {% else %}{% endif %} - {%- call arg_list_lowered(func) -%}) + {%- call arg_list_lowered(func, true) -%}) {%- endmacro %} -{% macro rust_call_with_prefix(prefix, func) -%} +{% macro rust_call_with_prefix(prefix, func, deref) -%} uniffi::rust_call( {{ func.ffi_func().name() }}, {%- match func.throws_type() %} @@ -22,7 +22,7 @@ {%- endmatch %} {{ prefix }} {%- if !func.arguments().is_empty() %}, {% else %}{% endif %} - {%- call arg_list_lowered(func) -%}) + {%- call arg_list_lowered(func, deref) -%}) {%- endmacro %} {% macro param_list(func) %} @@ -32,6 +32,92 @@ {% endfor -%} {% endmacro %} + +{#- An enum whose variants have no fields is generated as a C++ `enum class`, which cannot + have member functions, so its methods are emitted as free functions taking the value. #} +{%- macro method_decls(methods, qualifier, suffix) %} +{%- for method in methods %} +{%- call docstring(method, 4) %} + {{ qualifier }}{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} + {{- method.name()|fn_name }}({% call param_list(method) %}){{ suffix }}; +{%- endfor %} +{%- endmacro %} + +{%- macro method_defs(methods, define_on, self_expr, suffix) %} +{%- for method in methods %} +{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} +{{- define_on }}::{{ method.name()|fn_name }}({% call param_list(method) %}){{ suffix }} { + {%- match method.return_type() %} + {% when Some with (return_type) %} + return uniffi::{{ return_type|lift_fn }}({% call rust_call_with_prefix(self_expr, method, true) %}); + {%- else %} + {% call rust_call_with_prefix(self_expr, method, true) -%}; + {%- endmatch %} +} +{%- endfor %} +{%- endmacro %} + +{%- macro method_free_decls(methods, param_type) %} +{%- for method in methods %} +{%- call docstring(method, 0) %} +{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} +{{- method.name()|fn_name }}({{ param_type }} value{% if !method.arguments().is_empty() %}, {% endif %}{% call param_list(method) %}); +{%- endfor %} +{%- endmacro %} + +{%- macro method_free_defs(methods, param_type, self_expr) %} +{%- for method in methods %} +{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} +{{- method.name()|fn_name }}({{ param_type }} value{% if !method.arguments().is_empty() %}, {% endif %}{% call param_list(method) %}) { + {%- match method.return_type() %} + {% when Some with (return_type) %} + return uniffi::{{ return_type|lift_fn }}({% call rust_call_with_prefix(self_expr, method, true) %}); + {%- else %} + {% call rust_call_with_prefix(self_expr, method, true) -%}; + {%- endmatch %} +} +{%- endfor %} +{%- endmacro %} + + +{#- The uniffi traits that a type exports. These are rendered apart from plain methods + because their C++ names are not taken from Rust, so they cannot be emitted from a `Method` alone. + They split into member and free variants for the same reason as the methods above. #} +{%- macro uniffi_trait_decls(uniffi_traits, param_type) %} +{%- for t in uniffi_traits|uniffi_trait_list %} + /** + * {{ t.doc }} + */ + {{ t.return_type|type_name(ci) }} {{ t.name }}({% if t.takes_other %}const {{ param_type }} &other{% endif %}) const; +{%- endfor %} +{%- endmacro %} + +{%- macro uniffi_trait_defs(uniffi_traits, define_on, param_type, self_expr) %} +{%- for t in uniffi_traits|uniffi_trait_list %} +{{ t.return_type|type_name(ci) }} {{ define_on }}::{{ t.name }}({% if t.takes_other %}const {{ param_type }} &other{% endif %}) const { + return uniffi::{{ t.return_type|lift_fn }}({% call rust_call_with_prefix(self_expr, t.method, false) %}); +} +{%- endfor %} +{%- endmacro %} + +{%- macro uniffi_trait_free_decls(uniffi_traits, param_type) %} +{%- for t in uniffi_traits|uniffi_trait_list %} +/** + * {{ t.doc }} + */ +{{ t.return_type|type_name(ci) }} {{ t.name }}({{ param_type }} value{% if t.takes_other %}, {{ param_type }} other{% endif %}); +{%- endfor %} +{%- endmacro %} + +{%- macro uniffi_trait_free_defs(uniffi_traits, param_type, self_expr) %} +{%- for t in uniffi_traits|uniffi_trait_list %} +{{ t.return_type|type_name(ci) }} {{ t.name }}({{ param_type }} value{% if t.takes_other %}, {{ param_type }} other{% endif %}) { + return uniffi::{{ t.return_type|lift_fn }}({% call rust_call_with_prefix(self_expr, t.method, false) %}); +} +{%- endfor %} +{%- endmacro %} + + {% macro field_name(field, field_num) %} {%- if field.name().is_empty() -%} v{{- field_num -}} @@ -40,9 +126,9 @@ v{{- field_num -}} {%- endif -%} {%- endmacro %} -{% macro arg_list_lowered(func) %} +{% macro arg_list_lowered(func, deref) %} {%- for arg in func.arguments() -%} -uniffi::{{ arg|lower_fn }}({{ arg.name()|var_name }}) +uniffi::{{ arg|lower_fn }}({% if deref %}{{ arg.as_type()|cpp_deref(ci) }}{% endif %}{{ arg.name()|var_name }}) {%- if !loop.last -%}, {% endif -%} {% endfor -%} {% endmacro %} diff --git a/bindgen/src/bindings/cpp/templates/obj.cpp b/bindgen/src/bindings/cpp/templates/obj.cpp index 3f1de51..debc93d 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -14,11 +14,11 @@ namespace uniffi { {%- endif %} -{{ impl_class_name }}::{{ impl_class_name }}(void *ptr): instance(ptr) {} +{{ impl_class_name }}::{{ impl_class_name }}(uint64_t ptr): instance(ptr) {} -{{ impl_class_name }}::{{ impl_class_name }}(const {{ impl_class_name }} &other) : instance(nullptr) { +{{ impl_class_name }}::{{ impl_class_name }}(const {{ impl_class_name }} &other) : instance(0) { if (other.instance) { - instance = other._uniffi_internal_clone_pointer(); + instance = other._uniffi_internal_clone_handle(); } } @@ -44,18 +44,7 @@ namespace uniffi { } {% endfor %} -{%- for method in obj.methods() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { - auto ptr = this->_uniffi_internal_clone_pointer(); - {%- match method.return_type() %} - {% when Some with (return_type) %} - return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_prefix("ptr", method) %}); - {%- else %} - {% call macros::rust_call_with_prefix("ptr", method) -%}; - {%- endmatch %} -} -{%- endfor %} +{% call macros::method_defs(obj.methods(), impl_class_name, "this->_uniffi_internal_clone_handle()", "") %} {{ impl_class_name }}::~{{ impl_class_name }}() { uniffi::rust_call( @@ -65,7 +54,7 @@ namespace uniffi { ); } -void *{{ impl_class_name }}::_uniffi_internal_clone_pointer() const { +uint64_t {{ impl_class_name }}::_uniffi_internal_clone_handle() const { return uniffi::rust_call( {{ obj.ffi_object_clone().name() }}, nullptr, @@ -73,26 +62,4 @@ void *{{ impl_class_name }}::_uniffi_internal_clone_pointer() const { ); } -{%- for method in obj.uniffi_traits() %} -{% match method %} -{% when UniffiTrait::Display { fmt } %} -std::string {{ impl_class_name }}::to_string() const { - return uniffi::{{ Type::String.borrow()|lift_fn }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", fmt) %}); -} -{% when UniffiTrait::Debug { fmt } %} -std::string {{ impl_class_name }}::to_debug_string() const { - return uniffi::{{ Type::String.borrow()|lift_fn }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", fmt) %}); -} -{% when UniffiTrait::Eq { eq, ne } %} -bool {{ impl_class_name }}::eq(const {{ type_name }} &other) const { - return uniffi::{{ Type::Boolean.borrow()|lift_fn }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", eq) %}); -} -bool {{ impl_class_name }}::ne(const {{ type_name }} &other) const { - return uniffi::{{ Type::Boolean.borrow()|lift_fn }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", ne) %}); -} -{% when UniffiTrait::Hash { hash } %} -uint64_t {{ impl_class_name }}::hash() const { - return uniffi::{{ Type::UInt64.borrow()|lift_fn }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", hash) %}); -} -{% endmatch %} -{%- endfor %} +{% call macros::uniffi_trait_defs(obj.uniffi_trait_methods(), impl_class_name, type_name, "this->_uniffi_internal_clone_handle()") %} diff --git a/bindgen/src/bindings/cpp/templates/obj.hpp b/bindgen/src/bindings/cpp/templates/obj.hpp index fb02106..b35d906 100644 --- a/bindgen/src/bindings/cpp/templates/obj.hpp +++ b/bindgen/src/bindings/cpp/templates/obj.hpp @@ -3,13 +3,15 @@ {%- let class_name = type_name|class_name %} {%- let ffi_converter_name = typ|ffi_converter_name %} {%- let canonical_type_name = typ|canonical_name %} +{%- let methods = obj.methods() %} +{%- let interface_docstring = obj.docstring() %} {%- if obj.has_callback_interface() %} {%- let vtable = obj.vtable().expect("trait interface should have a vtable") %} {%- let vtable_methods = obj.vtable_methods() %} -{%- let methods = obj.methods() %} {%- let ffi_init_callback = obj.ffi_init_callback() %} -{%- let interface_docstring = obj.docstring() %} {% include "callback.hpp" %} +{%- else if obj.is_trait_interface() %} +{% include "iface.hpp" %} {%- endif %} namespace uniffi { @@ -17,14 +19,7 @@ namespace uniffi { } // namespace uniffi {%~ call macros::docstring(obj, 0) %} -struct {{ impl_class_name }} -{# - Since an interface being a callback interface or an error is mutually exclusive, - we don't need to complex branching for multiple inheritance -#} -{% if obj.has_callback_interface() %} : public {{ interface_name }} {% endif %} -{% if ci.is_name_used_as_error(name) %} : public std::exception {% endif %} -{ +struct {{ impl_class_name }}{{ obj|object_bases(ci) }} { friend uniffi::{{ ffi_converter_name|class_name }}; {{ impl_class_name }}() = delete; @@ -48,40 +43,9 @@ struct {{ impl_class_name }} static {{ type_name }} {{ ctor.name() }}({% call macros::param_list(ctor) %}); {%- endfor %} - {%- for method in obj.methods() %} - {%- call macros::docstring(method, 4) %} - {% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} - {{- method.name()|fn_name }}({% call macros::param_list(method) %}); - {%- endfor %} + {%- call macros::method_decls(obj.methods(), "", "") %} - {%- for method in obj.uniffi_traits() %} - {%- match method %} - {%- when UniffiTrait::Display { fmt } %} - /** - * Returns a string representation of the object, internally calls Rust's `Display` trait. - */ - std::string to_string() const; - {%- when UniffiTrait::Debug { fmt } %} - /** - * Returns a string representation of the object, internally calls Rust's `Debug` trait. - */ - std::string to_debug_string() const; - {%- when UniffiTrait::Eq { eq, ne } %} - /** - * Equality check, internally calls Rust's `Eq` trait. - */ - bool eq(const {{ type_name }} &other) const; - /** - * Inequality check, internally calls Rust's `Ne` trait. - */ - bool ne(const {{ type_name }} &other) const; - {%- when UniffiTrait::Hash { hash } %} - /** - * Returns a hash of the object, internally calls Rust's `Hash` trait. - */ - uint64_t hash() const; - {%- endmatch %} - {%- endfor %} + {%- call macros::uniffi_trait_decls(obj.uniffi_trait_methods(), type_name) %} {% if ci.is_name_used_as_error(name) %} void throw_underlying(); @@ -89,9 +53,9 @@ struct {{ impl_class_name }} private: {{ impl_class_name }}(const {{ impl_class_name }} &); - {{ impl_class_name }}(void *); + {{ impl_class_name }}(uint64_t); - void *_uniffi_internal_clone_pointer() const; + uint64_t _uniffi_internal_clone_handle() const; - void *instance = nullptr; + uint64_t instance = 0; }; diff --git a/bindgen/src/bindings/cpp/templates/obj_conv.cpp b/bindgen/src/bindings/cpp/templates/obj_conv.cpp index 27f70ef..6794420 100644 --- a/bindgen/src/bindings/cpp/templates/obj_conv.cpp +++ b/bindgen/src/bindings/cpp/templates/obj_conv.cpp @@ -3,7 +3,7 @@ {%- let is_error = ci.is_name_used_as_error(name) %} {%- if is_error %} -{{ type_name }} {{ typ|ffi_error_converter_name}}::lift(RustBuffer buf) { +{{ type_name }} {{ typ|ffi_error_converter_name }}::lift(RustBuffer buf) { auto stream = RustStream(&buf); auto val = {{ ffi_converter_name }}::read(stream); rustbuffer_free(buf); @@ -12,28 +12,56 @@ } {% endif %} -{{ type_name }} {{ ffi_converter_name }}::lift(void *ptr) { - return {{ type_name }}(new {{ impl_class_name }}(ptr)); +{{ type_name }} {{ ffi_converter_name }}::lift(uint64_t handle) { + {%- if obj.has_callback_interface() %} + // This interface can be implemented on either side of the FFI. + // Rust makes its handles by leaking a pointer, so they are always even. + if ((handle & 1) == 0) { + return {{ type_name }}(new {{ impl_class_name }}(handle)); + } + + auto impl = handle_map.at(handle); + handle_map.erase(handle); + + return impl; + {%- else %} + return {{ type_name }}(new {{ impl_class_name }}(handle)); + {%- endif %} } -void *{{ ffi_converter_name }}::lower(const {{ type_name }} &obj) { +uint64_t {{ ffi_converter_name }}::lower(const {{ type_name }} &obj) { + {%- if obj.is_trait_interface() %} + // Rust values are instances of the generated implementation and own a handle we + // can clone. Anything else is a C++ implementation of the trait. + if (auto impl = std::dynamic_pointer_cast<{{ impl_class_name }}>(obj)) { + return impl->_uniffi_internal_clone_handle(); + } {%- if obj.has_callback_interface() %} - auto ptr = handle_map.insert(obj); - return reinterpret_cast(ptr); + + // The trait is `WithForeign`, so Rust can call back through the vtable using a handle of + // our own. + return handle_map.insert(obj); + {%- else %} + + // Without a vtable there is no way to represent a C++ implementation, so report it rather than reinterpreting the pointer. + throw std::runtime_error( + "cannot pass this implementation of {{ interface_name }} to Rust: " + "only values returned from Rust can be lowered"); + {%- endif %} {%- else %} - return reinterpret_cast<{{ impl_class_name}}*>(obj.get())->_uniffi_internal_clone_pointer(); + return reinterpret_cast<{{ impl_class_name}}*>(obj.get())->_uniffi_internal_clone_handle(); {%- endif %} } {{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - std::uintptr_t ptr; + uint64_t ptr; stream >> ptr; - return {{ ffi_converter_name}}::lift(reinterpret_cast(ptr)); + return {{ ffi_converter_name }}::lift(ptr); } void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &obj) { - stream << reinterpret_cast({{ ffi_converter_name }}::lower(obj)); + stream << {{ ffi_converter_name }}::lower(obj); } uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &) { diff --git a/bindgen/src/bindings/cpp/templates/obj_conv.hpp b/bindgen/src/bindings/cpp/templates/obj_conv.hpp index 682f408..e19f802 100644 --- a/bindgen/src/bindings/cpp/templates/obj_conv.hpp +++ b/bindgen/src/bindings/cpp/templates/obj_conv.hpp @@ -10,8 +10,8 @@ struct {{ typ|ffi_error_converter_name}} { {% endif %} struct {{ typ|ffi_converter_name }} { - static {{ type_name }} lift(void *); - static void *lower(const {{ type_name }} &); + static {{ type_name }} lift(uint64_t); + static uint64_t lower(const {{ type_name }} &); static {{ type_name }} read(RustStream &); static void write(RustStream &, const {{ type_name }} &); static uint64_t allocation_size(const {{ type_name }} &); diff --git a/bindgen/src/bindings/cpp/templates/rec.hpp b/bindgen/src/bindings/cpp/templates/rec.hpp index e0e2902..61f4b11 100644 --- a/bindgen/src/bindings/cpp/templates/rec.hpp +++ b/bindgen/src/bindings/cpp/templates/rec.hpp @@ -5,7 +5,9 @@ struct {{ type_name }} { {%- call macros::docstring(field, 4) %} {{ field|type_name(ci) }} {{ field.name()|var_name }} {%- match field.default_value() %} - {%- when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style, ci) }};{%- else -%}; + {%- when Some with (default) %} = {{ default|default_cpp(field, config.enum_style, ci) }};{%- else -%}; {%- endmatch %} {%- endfor %} + {%- call macros::method_decls(rec.methods(), "", " const") %} + {%- call macros::uniffi_trait_decls(rec.uniffi_trait_methods(), type_name) %} }; diff --git a/bindgen/src/bindings/cpp/templates/scaffolding.hpp b/bindgen/src/bindings/cpp/templates/scaffolding.hpp index 216436d..56b3d92 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding.hpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding.hpp @@ -44,7 +44,7 @@ struct {{ ffi_struct.name()|ffi_struct_name }} { {% match func.return_type() -%} {% when Some with (return_type) %}{{ return_type|ffi_type_name }} {% when None %}void {% endmatch %}{{ func.name() }}( {%- for arg in func.arguments() %} -{{- arg.type_().borrow()|ffi_type_name }} {{ arg.name() }}{% if !loop.last || func.has_rust_call_status_arg() %}, {% endif -%} +{{- arg.type_().borrow()|ffi_type_name }} {{ arg.name()|var_name }}{% if !loop.last || func.has_rust_call_status_arg() %}, {% endif -%} {% endfor %} {%- if func.has_rust_call_status_arg() %}RustCallStatus *out_status{% endif -%} ); diff --git a/bindgen/src/bindings/cpp/templates/scaffolding/macros.cpp b/bindgen/src/bindings/cpp/templates/scaffolding/macros.cpp index d8ff781..4cfba50 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding/macros.cpp @@ -1,3 +1,11 @@ +{% macro field_name(field, field_num) -%} +{%- if field.name().is_empty() -%} +v{{- field_num -}} +{%- else -%} +{{ field.name()|var_name }} +{%- endif -%} +{%- endmacro %} + {% macro fn_prologue(ci, func, ffi_func) -%} {%- if ffi_func.has_rust_call_status_arg() %} out_status->code = UNIFFI_CALL_STATUS_OK; diff --git a/bindgen/src/bindings/cpp/templates/scaffolding/obj.cpp b/bindgen/src/bindings/cpp/templates/scaffolding/obj.cpp index 240d41b..a94d738 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding/obj.cpp @@ -1,14 +1,14 @@ -{{ type_name }} {{ ffi_converter_name }}::lift(void *ptr) { +{{ type_name }} {{ ffi_converter_name }}::lift(uint64_t ptr) { return {{ name }}_map.at((uint64_t)ptr); } -void *{{ ffi_converter_name }}::lower(const {{ type_name }} &obj) { +uint64_t {{ ffi_converter_name }}::lower(const {{ type_name }} &obj) { auto ret = {{ name }}_map.insert(obj); - return (void *)ret; + return ret; } {{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - std::uintptr_t ptr; + std::uint64_t ptr; stream >> ptr; return {{ name }}_map.at(ptr); diff --git a/bindgen/src/bindings/cpp/templates/scaffolding/obj.hpp b/bindgen/src/bindings/cpp/templates/scaffolding/obj.hpp index 5d69641..c2acefe 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding/obj.hpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding/obj.hpp @@ -1,7 +1,7 @@ {%- let type_name = typ|type_name(ci) %} struct {{ typ|ffi_converter_name }} { - static {{ type_name }} lift(void *); - static void *lower(const {{ type_name }} &); + static {{ type_name }} lift(uint64_t); + static uint64_t lower(const {{ type_name }} &); static {{ type_name }} read(RustStream &); static void write(RustStream &, const {{ type_name }} &); static int32_t allocation_size(const {{ type_name }} &); diff --git a/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp b/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp index 06f27ce..25f105f 100644 --- a/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp @@ -35,7 +35,7 @@ RustBuffer {{ class_name }}::lower(const {{ type_name }} &val) { void {{ class_name }}::write(RustStream &stream, const {{ type_name }} &val) { stream << static_cast(val.size()); - for (auto &elem : val) { + for (const auto &elem : val) { {{ inner_type|write_fn }}(stream, {{ inner_type.as_type()|cpp_deref(ci) }}elem); } } @@ -43,7 +43,7 @@ void {{ class_name }}::write(RustStream &stream, const {{ type_name }} &val) { uint64_t {{ class_name }}::allocation_size(const {{ type_name }} &val) { uint64_t size = sizeof(int32_t); - for (auto &elem : val) { + for (const auto &elem : val) { size += {{ inner_type|allocation_size_fn }}({{inner_type.as_type()|cpp_deref(ci) }}elem); } diff --git a/bindgen/src/bindings/cpp/templates/types.cpp b/bindgen/src/bindings/cpp/templates/types.cpp index 47ba6e0..4280c1b 100644 --- a/bindgen/src/bindings/cpp/templates/types.cpp +++ b/bindgen/src/bindings/cpp/templates/types.cpp @@ -10,6 +10,27 @@ {%- match typ %} {%- when Type::Object { module_path, name, imp } %} {% include "obj.cpp" %} +{%- when Type::Record { module_path, name } %} +{%- let rec = ci.get_record_definition(name).unwrap() %} +{%- let self_expr = format!("uniffi::{}::lower(*this)", ffi_converter_name) %} +{% call macros::method_defs(rec.methods(), type_name, self_expr, " const") %} +{% call macros::uniffi_trait_defs(rec.uniffi_trait_methods(), type_name, type_name, self_expr) %} +{%- when Type::Enum { module_path, name } %} +{%- let e = ci.get_enum_definition(name).unwrap() %} +{%- if ci.is_name_used_as_error(name) %} +{%- let class_name = typ|canonical_name %} +{%- let self_expr = format!("uniffi::{}::lower(*this)", ffi_converter_name) %} +{% call macros::method_defs(e.methods(), class_name, self_expr, " const") %} +{% call macros::uniffi_trait_defs(e.uniffi_trait_methods(), class_name, class_name, self_expr) %} +{%- else if e.is_flat() %} +{%- let self_expr = format!("uniffi::{}::lower(value)", ffi_converter_name) %} +{% call macros::method_free_defs(e.methods(), type_name, self_expr) %} +{% call macros::uniffi_trait_free_defs(e.uniffi_trait_methods(), type_name, self_expr) %} +{%- else %} +{%- let self_expr = format!("uniffi::{}::lower(*this)", ffi_converter_name) %} +{% call macros::method_defs(e.methods(), type_name, self_expr, " const") %} +{% call macros::uniffi_trait_defs(e.uniffi_trait_methods(), type_name, type_name, self_expr) %} +{%- endif %} {%- else %} {%- endmatch %} {% endfor ~%} diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 0d946cd..4517420 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -73,6 +73,9 @@ test_case(empty_type) test_case(error_types_builtin) test_case(reserved_field_name) test_case(type_flattening) +test_case(record_enum_methods) +test_case(renaming) +test_case(proc_macro) add_executable(ext_types_import-test tests/ext_types_import/main.cpp diff --git a/cpp-tests/tests/coverall/main.cpp b/cpp-tests/tests/coverall/main.cpp index 385a8e6..3980d42 100644 --- a/cpp-tests/tests/coverall/main.cpp +++ b/cpp-tests/tests/coverall/main.cpp @@ -447,7 +447,7 @@ void test_path() { ASSERT_EQ(2, traits[1]->strong_count()); traits[0]->set_parent(traits[1]); - ASSERT_EQ(2, traits[1]->strong_count()); + ASSERT_EQ(3, traits[1]->strong_count()); ASSERT_EQ(std::vector {"node-2"} , coverall::ancestor_names(traits[0])); ASSERT_EQ(std::vector {} , coverall::ancestor_names(traits[1])); @@ -504,6 +504,15 @@ void test_rust_only_traits() { auto traits = coverall::get_string_util_traits(); ASSERT_EQ("cowboy", traits[0]->concat("cow", "boy")); ASSERT_EQ("cowboy", traits[1]->concat("cow", "boy")); + + ASSERT_EQ("cowboy", coverall::concat_with_string_util(traits[0], "cow", "boy")); +} + +void test_object_implementing_trait() { + auto object = coverall::StringUtilObject::init("-"); + + std::shared_ptr as_trait = object; + ASSERT_EQ("cow-boy", as_trait->concat("cow", "boy")); } void test_html_error() { @@ -532,6 +541,7 @@ int main() { test_path(); test_round_tripping(); test_rust_only_traits(); + test_object_implementing_trait(); test_html_error(); return 0; diff --git a/cpp-tests/tests/error_types_builtin/main.cpp b/cpp-tests/tests/error_types_builtin/main.cpp index 0a79f0f..978b8fe 100644 --- a/cpp-tests/tests/error_types_builtin/main.cpp +++ b/cpp-tests/tests/error_types_builtin/main.cpp @@ -2,6 +2,17 @@ #include +// A C++ implementation of a trait whose method returns an error type. Rust calls back into +// this, and the generated vtable lowers the returned value, which is a `shared_ptr` here +// while the converter takes a `const &`. +struct Producer : error_types_builtin::ErrorProducer { + std::shared_ptr produce() override { + auto value = std::make_shared(); + value->v1 = 7; + return value; + } +}; + int main() { try { error_types_builtin::oops(); @@ -181,5 +192,38 @@ int main() { ASSERT_TRUE(false); } + try { + error_types_builtin::oops_tuple(1); + ASSERT_TRUE(false); + } catch(error_types_builtin::TupleError& e) { + ASSERT_EQ("value: 1", e.describe()); + } catch(...) { + ASSERT_TRUE(false); + } + + + try { + error_types_builtin::oops_custom(7); + ASSERT_TRUE(false); + } catch (error_types_builtin::TupleError& e) { + auto subtype = dynamic_cast(&e); + ASSERT_TRUE(subtype != nullptr); + ASSERT_EQ(subtype->v1, 7); + } catch (...) { + ASSERT_TRUE(false); + } + + try { + error_types_builtin::oops_custom_object(); + ASSERT_TRUE(false); + } catch (error_types_builtin::ErrorInterface& e) { + ASSERT_EQ(std::vector {"custom-object-oops"}, e.chain()); + } catch (...) { + ASSERT_TRUE(false); + } + + auto produced = error_types_builtin::describe_produced(std::make_shared()); + ASSERT_EQ("value: 7", produced); + return 0; } diff --git a/cpp-tests/tests/proc_macro/main.cpp b/cpp-tests/tests/proc_macro/main.cpp new file mode 100644 index 0000000..d19dc84 --- /dev/null +++ b/cpp-tests/tests/proc_macro/main.cpp @@ -0,0 +1,64 @@ +#include "test_common.hpp" + +#include + +int main() +{ + auto implicit_defaults = proc_macro::RecordWithImplicitDefaults{}; + + ASSERT_EQ(false, implicit_defaults.boolean); + ASSERT_EQ(0, implicit_defaults.int8); + ASSERT_EQ(0, implicit_defaults.uint8); + ASSERT_EQ(0, implicit_defaults.int16); + ASSERT_EQ(0, implicit_defaults.uint16); + ASSERT_EQ(0, implicit_defaults.int32); + ASSERT_EQ(0, implicit_defaults.uint32); + ASSERT_EQ(0, implicit_defaults.int64); + ASSERT_EQ(0, implicit_defaults.uint64); + ASSERT_EQ(0.0f, implicit_defaults.afloat); + ASSERT_EQ(0.0, implicit_defaults.adouble); + ASSERT_EQ(std::nullopt, implicit_defaults.opt_int32); + ASSERT_TRUE(implicit_defaults.vec.empty()); + ASSERT_TRUE(implicit_defaults.map.empty()); + ASSERT_TRUE(implicit_defaults.some_bytes.empty()); + + ASSERT_NE(nullptr, implicit_defaults.object); + ASSERT_EQ(proc_macro::MaybeBool::kUncertain, implicit_defaults.object->is_heavy()); + ASSERT_EQ(0, implicit_defaults.custom_integer); + + auto error = std::make_shared(); + ASSERT_EQ(42, implicit_defaults.object->take_error(error)); + + auto defaults = proc_macro::RecordWithDefaults{}; + + ASSERT_EQ(true, defaults.boolean); + ASSERT_EQ(42, defaults.integer); + ASSERT_EQ(4.2, defaults.float_var); + ASSERT_EQ(42, defaults.opt_integer); + ASSERT_EQ(std::nullopt, defaults.opt_vec); + ASSERT_EQ(false, defaults.boolean_default); + ASSERT_EQ("", defaults.string_default); + ASSERT_EQ(std::nullopt, defaults.opt_default); + ASSERT_EQ("", defaults.no_default_string); + ASSERT_TRUE(defaults.vec.empty()); + ASSERT_EQ(42, defaults.custom_integer); + ASSERT_EQ(0, defaults.sub.int32); + ASSERT_NE(nullptr, defaults.sub.object); + + // `std::vector` is a special case in C++ because it packs elements into single + // bits rather than storing a real bool, so iterating it yields a temporary value + // instead of a reference to an element. + const std::vector bools = {true, false, true}; + auto lowered = proc_macro::uniffi::FfiConverterSequenceBool::lower(bools); + auto roundtripped = proc_macro::uniffi::FfiConverterSequenceBool::lift(lowered); + ASSERT_EQ(bools, roundtripped); + + ASSERT_EQ(42, proc_macro::double_with_default(21)); + ASSERT_EQ(30, proc_macro::sum_with_default(10, 20)); + + auto object = proc_macro::ObjectWithDefaults::init(30); + ASSERT_EQ(42, object->add_to_num(12)); + ASSERT_EQ(30, object->add_to_implicit_num(0)); + + return 0; +} diff --git a/cpp-tests/tests/record_enum_methods/main.cpp b/cpp-tests/tests/record_enum_methods/main.cpp new file mode 100644 index 0000000..0a0a398 --- /dev/null +++ b/cpp-tests/tests/record_enum_methods/main.cpp @@ -0,0 +1,67 @@ +#include "test_common.hpp" + +#include +#include + +void test_record_methods() +{ + auto point = record_enum_methods::Point{.x = 3, .y = 4}; + + ASSERT_EQ(25, point.magnitude_squared()); + + auto moved = point.translated(2, -1); + ASSERT_EQ(5, moved.x); + ASSERT_EQ(3, moved.y); + + ASSERT_EQ(3, point.x); + ASSERT_EQ(4, point.y); + + ASSERT_EQ("(3, 4)", point.label()); +} + +void test_enum_methods() +{ + auto circle = record_enum_methods::Shape(record_enum_methods::Shape::kCircle{.radius = 2.0}); + auto rectangle = record_enum_methods::Shape(record_enum_methods::Shape::kRectangle{.width = 3.0, .height = 4.0}); + + ASSERT_TRUE(std::abs(circle.area() - (M_PI * 4.0)) < 1e-9); + ASSERT_TRUE(std::abs(rectangle.area() - 12.0) < 1e-9); + + ASSERT_EQ("circle r=2", circle.describe()); + ASSERT_EQ("rectangle 3x4", rectangle.describe()); + + auto bigger = rectangle.scaled(2.0); + ASSERT_TRUE(std::abs(bigger.area() - 48.0) < 1e-9); + + EXPECT_EXCEPTION(circle.scaled(-1.0), record_enum_methods::shape_error::NegativeScale); +} + +void test_flat_enum_methods() +{ + auto on = record_enum_methods::Flag::kOn; + + ASSERT_EQ(record_enum_methods::Flag::kOff, inverted(on)); + ASSERT_EQ(record_enum_methods::Flag::kOn, inverted(inverted(on))); +} + +void test_trait_impl_order() +{ + auto alpha = record_enum_methods::Alpha::init(); + ASSERT_EQ(42, alpha->zeta()); + + std::shared_ptr as_trait = alpha; + ASSERT_EQ(42, as_trait->zeta()); + + auto trait_from_rust = record_enum_methods::make_zeta(); + ASSERT_EQ(42, trait_from_rust->zeta()); +} + +int main() +{ + test_record_methods(); + test_enum_methods(); + test_flat_enum_methods(); + test_trait_impl_order(); + + return 0; +} diff --git a/cpp-tests/tests/renaming/main.cpp b/cpp-tests/tests/renaming/main.cpp new file mode 100644 index 0000000..7cabf93 --- /dev/null +++ b/cpp-tests/tests/renaming/main.cpp @@ -0,0 +1,26 @@ +#include "test_common.hpp" + +#include + +void test_renaming() +{ + // Renamed record, and a renamed field on it. + auto record = renaming::cpp_function(21); + ASSERT_EQ(21, record.cpp_field); + + // Renamed object, with a renamed method and argument. + auto object = renaming::CppObject::init(20); + ASSERT_EQ(22, object->cpp_method(2)); + + // Renamed enum variant, and a renamed field inside it. + auto value = renaming::make_rust_enum(); + auto variant = std::get(value.get_variant()); + ASSERT_EQ(7, variant.cpp_variant_field); +} + +int main() +{ + test_renaming(); + + return 0; +} diff --git a/cpp-tests/tests/trait_methods/main.cpp b/cpp-tests/tests/trait_methods/main.cpp index dc866a6..699965a 100644 --- a/cpp-tests/tests/trait_methods/main.cpp +++ b/cpp-tests/tests/trait_methods/main.cpp @@ -66,9 +66,126 @@ void test_proc_methods() { ASSERT_NE(trait->to_debug_string(), trait2->to_debug_string()); } +void test_record_traits() { + auto recordA1 = trait_methods::TraitRecord { .s = "a", .i = 1 }; + auto recordA2 = trait_methods::TraitRecord { .s = "a", .i = 2 }; + auto recordB1 = trait_methods::TraitRecord { .s = "b", .i = 1 }; + + ASSERT_TRUE(recordA1.eq(recordA2)); + ASSERT_FALSE(recordA1.ne(recordA2)); + ASSERT_EQ(0, recordA1.cmp(recordA2)); + ASSERT_EQ(recordA1.hash(), recordA2.hash()); + + ASSERT_FALSE(recordA1.eq(recordB1)); + ASSERT_TRUE(recordA1.ne(recordB1)); + ASSERT_EQ(-1, recordA1.cmp(recordB1)); + ASSERT_EQ(1, recordB1.cmp(recordA1)); + ASSERT_NE(recordA1.hash(), recordB1.hash()); + + ASSERT_EQ("TraitRecord { s: \"a\", i: 1 }", recordA1.to_debug_string()); + + auto udlRecord1 = trait_methods::UdlRecord { .s = "a", .i = 1 }; + auto udlRecord2 = trait_methods::UdlRecord { .s = "a", .i = 2 }; + ASSERT_TRUE(udlRecord1.eq(udlRecord2)); + ASSERT_EQ(0, udlRecord1.cmp(udlRecord2)); + ASSERT_EQ(udlRecord1.hash(), udlRecord2.hash()); +} + +void test_enum_traits() { + using TraitEnum = trait_methods::TraitEnum; + + auto variantS1 = TraitEnum(TraitEnum::kS { .v1 = "variantS1" }); + auto variantS2 = TraitEnum(TraitEnum::kS { .v1 = "variantS2" }); + auto variantI0 = TraitEnum(TraitEnum::kI { .v1 = 0 }); + auto variantN = TraitEnum(TraitEnum::kN {}); + + ASSERT_TRUE(variantS1.eq(variantS2)); + ASSERT_FALSE(variantS1.ne(variantS2)); + ASSERT_EQ(0, variantS1.cmp(variantS2)); + ASSERT_EQ(variantS1.hash(), variantS2.hash()); + + // Ordering between variants is S < I < N + ASSERT_FALSE(variantS1.eq(variantI0)); + ASSERT_EQ(-1, variantS1.cmp(variantI0)); + ASSERT_EQ(1, variantI0.cmp(variantS1)); + ASSERT_EQ(-1, variantI0.cmp(variantN)); + ASSERT_NE(variantS1.hash(), variantI0.hash()); + + ASSERT_EQ("TraitEnum::S(\"variantS1\")", variantS1.to_string()); + ASSERT_EQ("S(\"variantS1\")", variantS1.to_debug_string()); + ASSERT_EQ("TraitEnum::I(0)", variantI0.to_string()); + + using UdlEnum = trait_methods::UdlEnum; + auto udlVariantS1 = UdlEnum(UdlEnum::kS { .s = "variantS1" }); + auto udlVariantS2 = UdlEnum(UdlEnum::kS { .s = "variantS2" }); + auto udlVariantI0 = UdlEnum(UdlEnum::kI { .i = 0 }); + + ASSERT_TRUE(udlVariantS1.eq(udlVariantS2)); + ASSERT_EQ(0, udlVariantS1.cmp(udlVariantS2)); + ASSERT_EQ(udlVariantS1.hash(), udlVariantS2.hash()); + ASSERT_EQ(-1, udlVariantS1.cmp(udlVariantI0)); +} + +void test_flat_enum_traits() { + auto alpha = trait_methods::get_flat_trait_enum(0); + auto beta = trait_methods::get_flat_trait_enum(1); + + ASSERT_EQ(trait_methods::FlatTraitEnum::kAlpha, alpha); + ASSERT_EQ(trait_methods::FlatTraitEnum::kBeta, beta); + + ASSERT_EQ("FlatTraitEnum::flat-alpha", to_string(alpha)); + ASSERT_EQ("FlatTraitEnum::flat-beta", to_string(beta)); + ASSERT_EQ("Alpha", to_debug_string(alpha)); +} + +void test_error_traits() { + // FlatError exports Display only. + try + { + trait_methods::throw_flat_error(0); + ASSERT_TRUE(false); + } + catch(trait_methods::FlatError &e) + { + ASSERT_EQ("error: not found", e.to_string()); + } + + // MultipleTraitError exports Debug, Display, Eq, Ord and Hash. + try { + trait_methods::throw_multiple_trait_error(0); + ASSERT_TRUE(false); + } catch (trait_methods::MultipleTraitError &noData) { + ASSERT_EQ("MultipleTraitError::NoData", noData.to_string()); + ASSERT_TRUE(noData.eq(noData)); + ASSERT_FALSE(noData.ne(noData)); + ASSERT_EQ(0, noData.cmp(noData)); + + try { + trait_methods::throw_multiple_trait_error(1); + ASSERT_TRUE(false); + } catch (trait_methods::MultipleTraitError &nested) { + ASSERT_FALSE(noData.eq(nested)); + ASSERT_EQ(-1, noData.cmp(nested)); + ASSERT_EQ(1, nested.cmp(noData)); + ASSERT_NE(noData.hash(), nested.hash()); + } + } + + try { + trait_methods::throw_api_failure(0); + ASSERT_TRUE(false); + } catch (trait_methods::ApiFailure &e) { + ASSERT_EQ("api network issue", e.to_string()); + } +} + int main() { test_trait_methods(); test_proc_methods(); + test_record_traits(); + test_enum_traits(); + test_flat_enum_traits(); + test_error_traits(); return 0; } \ No newline at end of file diff --git a/cpp-tests/tests/type_flattening/main.cpp b/cpp-tests/tests/type_flattening/main.cpp index 7069da3..e98f249 100644 --- a/cpp-tests/tests/type_flattening/main.cpp +++ b/cpp-tests/tests/type_flattening/main.cpp @@ -2,7 +2,8 @@ #include -int main() { +int main() +{ int value = 42; auto structure = type_flattening::get_struct(value); @@ -13,5 +14,27 @@ int main() { ASSERT_NE(roundtrip.optional_arc, nullptr); ASSERT_EQ(roundtrip.optional_arc->get_value(), value); + auto defaults = type_flattening::OptionalDefaults{}; + ASSERT_EQ(42, defaults.maybe_int); + ASSERT_EQ("hello", defaults.maybe_text); + ASSERT_EQ(true, defaults.maybe_bool); + ASSERT_EQ(std::nullopt, defaults.maybe_null); + + auto enum_default = type_flattening::OptionalEnumDefault{}; + ASSERT_EQ(type_flattening::Colour::kRed, enum_default.maybe_colour); + + auto supported_defaults = type_flattening::SupportedDefaults{}; + ASSERT_EQ(0, supported_defaults.int_); + ASSERT_EQ(false, supported_defaults.flag); + ASSERT_EQ(0.0, supported_defaults.float_); + ASSERT_EQ("", supported_defaults.text); + ASSERT_EQ(std::nullopt, supported_defaults.maybe); + ASSERT_EQ(nullptr, supported_defaults.maybe_object); + ASSERT_TRUE(supported_defaults.bytes.empty()); + ASSERT_TRUE(supported_defaults.list.empty()); + ASSERT_TRUE(supported_defaults.table.empty()); + ASSERT_TRUE(supported_defaults.enum_list.empty()); + ASSERT_TRUE(supported_defaults.enum_table.empty()); + return 0; } diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 68f93df..e897a5c 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -31,6 +31,33 @@ uniffi-bindgen-cpp path/to/definitions.udl --config path/to/uniffi.toml will be expanded into variable containing the custom value. The expression is used in a return statement, i.e. `return `. +- `rename` - C++ names for items that keep a different name in Rust. Nested items are addressed + with dot notation. + + ```toml + [bindings.cpp.rename] + # Types + RustRecord = "CppRecord" + + # Fields, variants, methods and their arguments + "RustRecord.rust_field" = "cpp_field" + "RustEnum.RustVariant" = "CppVariant" + "RustObject.rust_method" = "cpp_method" + "RustObject.rust_method.rust_arg" = "cpp_arg" + + # Free functions and their arguments + rust_function = "cpp_function" + "rust_function.rust_arg" = "cpp_arg" + ``` + + Renames are applied before the usual naming conventions, so a renamed enum variant still + picks up `enum_style`, and a rename into a C++ keyword still gets `_` appended. + + A crate can only rename its own items, not types it imports from another crate. To rename an + item for every language rather than just C++, rename it in the Rust source instead, with + `#[uniffi(name = "...")]` on types, fields and variants, or `#[uniffi::export(name = "...")]` + on functions and methods. + - `enum_style` - style for enum variant naming, possible options are: - `"Capitalized"` - producing enum variants named `ENUM_VARIANT` - `"Google"` - producing enum variants name `kEnumVariant` (default) diff --git a/fixtures/Cargo.toml b/fixtures/Cargo.toml index 476486c..ca318a0 100644 --- a/fixtures/Cargo.toml +++ b/fixtures/Cargo.toml @@ -7,19 +7,22 @@ edition = "2021" crate-type = ["cdylib", "lib", "staticlib"] [dependencies] -uniffi-example-arithmetic = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-custom-types = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-geometry = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-rondpoint = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-sprites = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-todolist = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-example-traits = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-fixture-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-fixture-coverall = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-fixture-docstring = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-fixture-time = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } -uniffi-fixture-trait-methods = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.29.4" } +uniffi-example-arithmetic = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-custom-types = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-geometry = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-rondpoint = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-sprites = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-todolist = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-example-traits = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-fixture-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +# Vendored at fixtures/coverall rather than taken from git: the upstream fixture exports an +# `async fn` as of v0.30.0, which the C++ bindgen cannot generate. See that crate's Cargo.toml. +uniffi-fixture-coverall = { path = "coverall" } +uniffi-fixture-docstring = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-fixture-proc-macro = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-fixture-time = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } +uniffi-fixture-trait-methods = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.0" } uniffi-error-types-builtin = { path = "error-types-builtin" } uniffi-custom-types-builtin = { path = "custom-types-builtin" } @@ -27,6 +30,8 @@ uniffi-enum-style-test = { path = "enum-style-test" } uniffi-empty-type = { path = "empty-type" } uniffi-reserved-field-name = { path = "reserved-field-name" } uniffi-type-flattening = { path = "type-flattening" } +uniffi-record-enum-methods = { path = "record-enum-methods" } +uniffi-renaming = { path = "renaming" } uniffi-ext-types-export = { path = "ext-types-export" } uniffi-ext-types-import = { path = "ext-types-import" } diff --git a/fixtures/coverall/Cargo.toml b/fixtures/coverall/Cargo.toml new file mode 100644 index 0000000..99aa02f --- /dev/null +++ b/fixtures/coverall/Cargo.toml @@ -0,0 +1,27 @@ +# Local copy of uniffi-rs's `fixtures/coverall`, taken at tag v0.31.0. +# +# It is vendored rather than used as a git dependency because since v0.30.0 the upstream +# fixture exports an `async fn`, and the C++ bindgen refuses any namespace containing one. +# That would block generating bindings for every other fixture in the library too. +# +# The only deliberate difference from upstream is that `async fn async_bool` is omitted. +# Drop this crate and go back to the upstream git dependency once async is supported. +[package] +name = "uniffi-fixture-coverall" +version = "0.22.0" +edition = "2021" +license = "MPL-2.0" +publish = false + +[lib] +crate-type = ["lib", "cdylib"] +name = "uniffi_coverall" + +[dependencies] +# Add the "scaffolding-ffi-buffer-fns" feature to make sure things can build correctly +uniffi = { workspace = true, features = ["scaffolding-ffi-buffer-fns"] } +once_cell = "1.12" +thiserror = "2" + +[build-dependencies] +uniffi = { workspace = true, features = ["build"] } diff --git a/fixtures/coverall/README.md b/fixtures/coverall/README.md new file mode 100644 index 0000000..c99a885 --- /dev/null +++ b/fixtures/coverall/README.md @@ -0,0 +1,9 @@ +# A "Coverall" test for uniffi components + +This is similar to our examples, but it's intended to be contrived and to +ensure we get good test coverage of all possible options. + +It's here so it doesn't even need to make a cursory effort to be a "good" +example; it intentionally panics, asserts params are certain values, has +no-op methods etc. If you're trying to get your head around uniffi then the +"examples" directory will be a much better bet. diff --git a/fixtures/coverall/build.rs b/fixtures/coverall/build.rs new file mode 100644 index 0000000..983731d --- /dev/null +++ b/fixtures/coverall/build.rs @@ -0,0 +1,7 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +fn main() { + uniffi::generate_scaffolding("src/coverall.udl").unwrap(); +} diff --git a/fixtures/coverall/src/coverall.udl b/fixtures/coverall/src/coverall.udl new file mode 100644 index 0000000..49b8a5c --- /dev/null +++ b/fixtures/coverall/src/coverall.udl @@ -0,0 +1,317 @@ +namespace coverall { + SimpleDict create_some_dict(); + SimpleDict create_none_dict(); + + u64 get_num_alive(); + + sequence get_traits(); + + MaybeSimpleDict get_maybe_simple_dict(i8 index); + + // void returning error throwing namespace function to catch clippy warnings (eg, #1330) + [Throws=CoverallError] + void println(string text); + + [Throws=CoverallFlatError] + void throw_flat_error(); + + [Throws=CoverallRichErrorNoVariantData] + void throw_rich_error_no_variant_data(); + + Getters make_rust_getters(); + void test_getters(Getters g); + + sequence ancestor_names(NodeTrait node); + + sequence get_string_util_traits(); + + ReturnOnlyDict output_return_only_dict(); + ReturnOnlyEnum output_return_only_enum(); + + void try_input_return_only_dict(ReturnOnlyDict d); + + [Throws=ComplexError] + f32 divide_by_text(f32 value, string value_as_text); + + Getters test_round_trip_through_rust(Getters getters); + void test_round_trip_through_foreign(Getters getters); + + // Always throws an InvalidHTML error + [Throws=HTMLError] + void validate_html(string source); +}; + +dictionary SimpleDict { + string text; + string? maybe_text; + bytes some_bytes; + bytes? maybe_some_bytes; + boolean a_bool; + boolean? maybe_a_bool; + u8 unsigned8; + u8? maybe_unsigned8; + u16 unsigned16; + u16? maybe_unsigned16; + u64 unsigned64; + u64? maybe_unsigned64; + i8 signed8; + i8? maybe_signed8; + i64 signed64; + i64? maybe_signed64; + float float32; + float? maybe_float32; + double float64; + double? maybe_float64; + Coveralls? coveralls; + sequence coveralls_list; + record coveralls_map; + NodeTrait? test_trait; +}; + +// Create a type that stores `CoverallFlatError` and therefore can only be lowered but not lifted. +// UniFFI should define a `Lower` implementation but not try to define `Lift`. +dictionary ReturnOnlyDict { + CoverallFlatError e; +}; + +// More complicated version of the above, each variant is return-only for different reasons +[Enum] +interface ReturnOnlyEnum { + One(CoverallFlatError e); + Two(ReturnOnlyDict d); + Three(sequence l); + Four(record m); +}; + +dictionary DictWithDefaults { + string name = "default-value"; + string? category = null; + u64 integer = 31; + sequence item_list = []; + record item_map = {}; +}; + +[Enum] +interface MaybeSimpleDict { + Yeah(SimpleDict d); + Nah(); +}; + +[Enum] +interface MaybeObject { + Obj(Patch p); + Nah(); +}; + +// Note that UDL *can not* express flat enums (ie, those with variants that carry data which +// should be ignored for the ffi), only flat errors? +//enum SimpleFlatEnum { +// "First", +// "Second", +//}; + +[Error] +enum CoverallError { + "TooManyHoles" +}; + +// This error is described in Rust with variants, but because it's declared +// here via an `enum` it's considered "flat" +[Error] +enum CoverallFlatError { + "TooManyVariants" +}; + +// This error is for an enum that's still "flat" on the Rust side (ie, no +// variants have associated data), but it behaves differently on the bindings +// side than had it been described via `enum` +[Error] +interface CoverallRichErrorNoVariantData { + TooManyPlainVariants(); +}; + +[Error] +interface ComplexError { + OsError(i16 code, i16 extended_code); + PermissionDenied(string reason); + UnknownError(); +}; + +interface Coveralls { + constructor(string name); + + // Either constructs a new object or throws an error. + [Throws=CoverallError, Name="fallible_new"] + constructor(string name, boolean should_fail); + + // Always panics, just to test panics in ctors are handled. + [Name="panicking_new"] + constructor(string message); + + string get_name(); + + [Throws=CoverallError] + boolean maybe_throw(boolean should_throw); + + /// Throws something that impls `Into`, + /// rather than directly throwing `CoverallError`. + [Throws=CoverallError] + boolean maybe_throw_into(boolean should_throw); + + [Throws=ComplexError] + boolean maybe_throw_complex(i8 input); + + void panic(string message); + + [Throws=CoverallError] + void fallible_panic(string message); + + // *** Test functions which take either `self` or other params as `Arc` *** + + /// Calls `Arc::strong_count()` on the `Arc` containing `self`. + [Self=ByArc] + u64 strong_count(); + + /// Takes an `Arc` and stores it in `self`, dropping the existing + /// reference. Note you can create circular references by passing `self`. + void take_other(Coveralls? other); + + /// Returns what was previously set via `take_other()`, or null. + Coveralls? get_other(); + + /// Same signature as `take_other` but always fails. + [Self=ByArc, Throws=CoverallError] + void take_other_fallible(); + + /// Same signature as `take_other` but with an extra string arg - always + /// panics with that message.. + [Self=ByArc] + void take_other_panic(string message); + + // can't name it `clone` as it conflicts with the Clone trait and ours has a different signature + Coveralls clone_me(); + + // regression test: using a parameter name that was also used by UniFFI runtime code + string get_status(string status); + + /// Simple string->integer dictionary, using the legacy `DOMString` type. + record get_dict(string key, u64 value); + + /// Simple string->integer dictionary, using the classic string type + record get_dict2(string key, u64 value); + + /// integer->integer dictionary + record get_dict3(u32 key, u64 value); + + /// Adds a new repair at the current time. + void add_patch(Patch patch); + + /// Adds a new repair at the specified time. + void add_repair(Repair repair); + + /// Returns all repairs made. + sequence get_repairs(); + + /// Reverses the bytes. + bytes reverse(bytes value); + + EmptyStruct set_and_get_empty_struct(EmptyStruct empty_struct); +}; + +// coveralls keep track of their repairs (an interface in a dict) +dictionary Repair { + timestamp when; + Patch patch; +}; + +// All coveralls end up with a patch. +enum Color {"Red", "Blue", "Green"}; + +interface Patch { + constructor(Color color); + + Color get_color(); +}; + +interface FalliblePatch { + [Throws=CoverallError] + constructor(); + + [Throws=CoverallError, Name="secondary"] + constructor(); +}; + +interface ThreadsafeCounter { + constructor(); + void busy_wait(i32 ms); + i32 increment_if_busy(); +}; + +// Test trait interface #1 +// +// The goal here is to test all possible arg, return, and error types. +[Trait, WithForeign] +interface Getters { + boolean get_bool(boolean v, boolean arg2); + [Throws=CoverallError] + string get_string(string v, boolean arg2); + [Throws=ComplexError] + string? get_option(string v, boolean arg2); + sequence get_list(sequence v, boolean arg2); + void get_nothing(string v); + Coveralls round_trip_object(Coveralls coveralls); +}; + +// Test trait interface #2 +// +// The goal here is test passing objects back and forth between Rust and the foreign side +[Trait, WithForeign] +interface NodeTrait { + string name(); // The name of the this node + + /// Takes an `Arc` and stores it our parent node, dropping any existing / reference. Note + /// you can create circular references with this. + void set_parent(NodeTrait? parent); + + /// Returns what was previously set via `set_parent()`, or null. + NodeTrait? get_parent(); + + /// Calls `Arc::strong_count()` on the `Arc` containing `self`. + [Self=ByArc] + u64 strong_count(); +}; + +// Test trait interface #3 +// +// The goal here is test Rust-only trait interfaces +[Trait] +interface StringUtil { + string concat([ByRef]string a, [ByRef]string b); +}; + +// Forward/backward declarations are fine in UDL. +// Running the Python tests & type checks will ensure this works, +// no function calls needed + +interface IFirst { + constructor(); + + // Handling optional with a default value + boolean compare(optional ISecond? other = null); +}; + +interface ISecond { + constructor(); + + // Default only + boolean compare(IFirst? other); +}; + +dictionary EmptyStruct {}; + +// Error class with a controversial camel case. This can cause errors if we don't consistently +// convert the name. +[Error] +enum HTMLError { + "InvalidHTML" +}; diff --git a/fixtures/coverall/src/ffi_buffer_scaffolding_test.rs b/fixtures/coverall/src/ffi_buffer_scaffolding_test.rs new file mode 100644 index 0000000..5a037f4 --- /dev/null +++ b/fixtures/coverall/src/ffi_buffer_scaffolding_test.rs @@ -0,0 +1,61 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use crate::ComplexError; +use uniffi::{ + ffi_buffer_size, FfiBufferElement, FfiSerialize, LiftReturn, Lower, RustBuffer, RustCallStatus, +}; + +/// Test the FFI-buffer version of our scaffolding functions by manually calling one. +/// +/// We use the `get_complex_error` version, since it's one of more complex cases: +/// - It inputs multiple arguments +/// - The Rust function returns a Result<> type, which means the ffi-buffer scaffolding function +/// needs to deserialize the `RustCallStatus` out pointer, pass it to the regular scaffolding +/// function, and everything needs to be put back together in the end. +#[test] +fn test_ffi_buffer_scaffolding() { + // Call the ffi-buffer version of the scaffolding function for `divide_by_text` + // + // This simulates the work that happens on the foreign side. + fn call_ffi_buffer_divide_by_text( + value: f32, + value_as_text: String, + ) -> Result { + // Get buffers ready to store the arguments/return values + let mut args_ffi_buffer = [FfiBufferElement::default(); ffi_buffer_size!(f32, RustBuffer)]; + let mut return_ffi_buffer = + [FfiBufferElement::default(); ffi_buffer_size!(f32, RustCallStatus)]; + // Lower the arguments + let value_lowered = >::lower(value); + let value_as_text_lowered = >::lower(value_as_text); + // Serialize the lowered arguments plus the RustCallStatus into the argument buffer + let args_cursor = &mut args_ffi_buffer.as_mut_slice(); + ::write(args_cursor, value_lowered); + ::write(args_cursor, value_as_text_lowered); + // Call the ffi-buffer version of the scaffolding function + unsafe { + crate::uniffi_ffibuffer_uniffi_coverall_fn_func_divide_by_text( + args_ffi_buffer.as_mut_ptr(), + return_ffi_buffer.as_mut_ptr(), + ); + } + // Deserialize the return and the RustCallStatus from the return buffer + let return_cursor = &mut return_ffi_buffer.as_slice(); + let return_value = ::read(return_cursor); + let rust_call_status = ::read(return_cursor); + // Lift the return from the deserialized value. + as LiftReturn>::lift_foreign_return( + return_value, + rust_call_status, + ) + } + + assert_eq!(call_ffi_buffer_divide_by_text(1.0, "2".into()), Ok(0.5)); + assert_eq!(call_ffi_buffer_divide_by_text(5.0, "2.5".into()), Ok(2.0)); + assert_eq!( + call_ffi_buffer_divide_by_text(1.0, "two".into()), + Err(ComplexError::UnknownError) + ); +} diff --git a/fixtures/coverall/src/lib.rs b/fixtures/coverall/src/lib.rs new file mode 100644 index 0000000..85c108c --- /dev/null +++ b/fixtures/coverall/src/lib.rs @@ -0,0 +1,663 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::SystemTime; + +use once_cell::sync::Lazy; + +#[cfg(test)] +mod ffi_buffer_scaffolding_test; + +mod traits; +pub use traits::{ + ancestor_names, get_string_util_traits, get_traits, make_rust_getters, test_getters, + test_round_trip_through_foreign, test_round_trip_through_rust, Getters, NodeTrait, StringUtil, +}; + +static NUM_ALIVE: Lazy> = Lazy::new(|| RwLock::new(0)); + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum CoverallError { + #[error("The coverall has too many holes")] + TooManyHoles, +} + +#[derive(Debug, thiserror::Error)] +pub enum CoverallFlatError { + #[error("Too many variants: {num}")] + TooManyVariants { num: i16 }, +} + +fn throw_flat_error() -> Result<(), CoverallFlatError> { + Err(CoverallFlatError::TooManyVariants { num: 99 }) +} + +#[derive(Debug, thiserror::Error, uniffi::Error)] +#[uniffi(flat_error)] // "flat" isn't really the correct terminology here. +pub enum CoverallMacroError { + #[error("The coverall has too many macros")] + TooManyMacros, +} + +#[uniffi::export] +fn throw_macro_error() -> Result<(), CoverallMacroError> { + Err(CoverallMacroError::TooManyMacros) +} + +#[derive(Debug, thiserror::Error, uniffi::Error)] +#[uniffi(flat_error)] +pub enum CoverallFlatMacroError { + #[error("Too many variants: {num}")] + TooManyVariants { num: i16 }, +} + +#[uniffi::export] +fn throw_flat_macro_error() -> Result<(), CoverallFlatMacroError> { + Err(CoverallFlatMacroError::TooManyVariants { num: 88 }) +} + +#[derive(Debug, thiserror::Error)] +pub enum CoverallRichErrorNoVariantData { + #[error("TooManyPlainVariants")] + TooManyPlainVariants, +} + +fn throw_rich_error_no_variant_data() -> Result<(), CoverallRichErrorNoVariantData> { + Err(CoverallRichErrorNoVariantData::TooManyPlainVariants) +} + +/// This error doesn't appear in the interface, instead +/// we rely on an `Into` impl to surface it to consumers. +#[derive(Debug, thiserror::Error)] +pub enum InternalCoverallError { + #[error("The coverall has an excess of holes")] + ExcessiveHoles, +} + +impl From for CoverallError { + fn from(err: InternalCoverallError) -> CoverallError { + match err { + InternalCoverallError::ExcessiveHoles => CoverallError::TooManyHoles, + } + } +} + +#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)] +pub enum ComplexError { + #[error("OsError: {code} ({extended_code})")] + OsError { code: i16, extended_code: i16 }, + #[error("PermissionDenied: {reason}")] + PermissionDenied { reason: String }, + #[error("Unknown error")] + UnknownError, +} + +#[derive(Debug, thiserror::Error, uniffi::Error)] +pub enum ComplexMacroError { + #[error("OsError: {code} ({extended_code})")] + OsError { code: i16, extended_code: i16 }, + #[error("PermissionDenied: {reason}")] + PermissionDenied { reason: String }, + #[error("Unknown error")] + UnknownError, +} + +#[uniffi::export] +fn throw_complex_macro_error() -> Result<(), ComplexMacroError> { + Err(ComplexMacroError::OsError { + code: 1, + extended_code: 2, + }) +} + +// Note: intentionally *does not* derive `uniffi::Error`, yet ends with `Error`, just to +// mess with Kotlin etc. +#[derive(Clone, Debug, uniffi::Enum)] +pub enum OtherError { + Unexpected, +} + +#[derive(Clone, Debug, thiserror::Error, uniffi::Error)] +pub enum RootError { + #[error(transparent)] + // XXX - note Kotlin fails if this variant was called ComplexError + // (ie, the variant name can't match an existing type) + Complex { + #[from] + error: ComplexError, + }, + #[error("Other Error")] + Other { error: OtherError }, +} + +// For Kotlin, we throw a variant which itself is a plain enum. +#[uniffi::export] +fn throw_root_error() -> Result<(), RootError> { + Err(RootError::Complex { + error: ComplexError::OsError { + code: 1, + extended_code: 2, + }, + }) +} + +#[uniffi::export] +fn get_root_error() -> RootError { + RootError::Other { + error: OtherError::Unexpected, + } +} + +#[uniffi::export] +fn get_complex_error(e: Option) -> ComplexError { + e.unwrap_or(ComplexError::PermissionDenied { + reason: "too complex".to_string(), + }) +} + +#[uniffi::export] +fn get_error_dict(d: Option) -> ErrorDict { + d.unwrap_or_default() +} + +#[derive(Default, Debug, uniffi::Record)] +pub struct ErrorDict { + complex_error: Option, + root_error: Option, + errors: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct SimpleDict { + text: String, + maybe_text: Option, + some_bytes: Vec, + maybe_some_bytes: Option>, + a_bool: bool, + maybe_a_bool: Option, + unsigned8: u8, + maybe_unsigned8: Option, + unsigned16: u16, + maybe_unsigned16: Option, + unsigned64: u64, + maybe_unsigned64: Option, + signed8: i8, + maybe_signed8: Option, + signed64: i64, + maybe_signed64: Option, + float32: f32, + maybe_float32: Option, + float64: f64, + maybe_float64: Option, + coveralls: Option>, + coveralls_list: Vec>>, + coveralls_map: HashMap>>, + test_trait: Option>, +} + +pub struct ReturnOnlyDict { + e: CoverallFlatError, +} + +pub enum ReturnOnlyEnum { + One { + e: CoverallFlatError, + }, + Two { + d: ReturnOnlyDict, + }, + Three { + l: Vec, + }, + Four { + m: HashMap, + }, +} + +fn output_return_only_dict() -> ReturnOnlyDict { + ReturnOnlyDict { + e: CoverallFlatError::TooManyVariants { num: 1 }, + } +} + +fn output_return_only_enum() -> ReturnOnlyEnum { + ReturnOnlyEnum::One { + e: CoverallFlatError::TooManyVariants { num: 2 }, + } +} + +fn try_input_return_only_dict(_d: ReturnOnlyDict) { + // This function can't work because ReturnOnlyDict contains a flat error and therefore + // can't be lifted by Rust. There's a Python test that the UniFFI code panics before we get here. + // + // FIXME: should be a compile-time error rather than a runtime error (#1850) +} + +pub fn divide_by_text(value: f32, value_as_text: String) -> Result { + match value_as_text.parse::() { + Ok(divisor) if divisor != 0.0 => Ok(value / divisor), + _ => Err(ComplexError::UnknownError), + } +} + +#[derive(Debug, Clone)] +pub struct DictWithDefaults { + name: String, + category: Option, + integer: u64, + item_list: Vec, + item_map: HashMap, +} + +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Clone)] +pub enum MaybeSimpleDict { + Yeah { d: SimpleDict }, + Nah, +} + +fn get_maybe_simple_dict(index: i8) -> MaybeSimpleDict { + match index { + 0 => MaybeSimpleDict::Yeah { + d: SimpleDict::default(), + }, + 1 => MaybeSimpleDict::Nah, + _ => unreachable!("invalid index: {index}"), + } +} + +#[derive(Debug)] +enum MaybeObject { + Obj { p: Arc }, + Nah, +} + +#[uniffi::export] +fn get_maybe_object(index: i8) -> MaybeObject { + match index { + 0 => MaybeObject::Obj { + p: Arc::new(Patch { color: Color::Red }), + }, + 1 => MaybeObject::Nah, + _ => unreachable!("invalid index: {index}"), + } +} + +// UDL can not describe this as a "flat" enum, but we'll keep it here to help demonstrate that! +#[derive(Debug, Clone)] +pub enum SimpleFlatEnum { + First { val: String }, + Second { num: u16 }, +} + +#[derive(Debug, Clone, uniffi::Enum)] +pub enum SimpleFlatMacroEnum { + First { val: String }, + Second { num: u16 }, +} + +#[uniffi::export] +fn get_simple_flat_macro_enum(index: i8) -> SimpleFlatMacroEnum { + match index { + 0 => SimpleFlatMacroEnum::First { + val: "the first".to_string(), + }, + 1 => SimpleFlatMacroEnum::Second { num: 2 }, + _ => unreachable!("invalid index: {index}"), + } +} + +fn create_some_dict() -> SimpleDict { + SimpleDict { + text: "text".to_string(), + maybe_text: Some("maybe_text".to_string()), + some_bytes: b"some_bytes".to_vec(), + maybe_some_bytes: Some(b"maybe_some_bytes".to_vec()), + a_bool: true, + maybe_a_bool: Some(false), + unsigned8: 1, + maybe_unsigned8: Some(2), + unsigned16: 3, + maybe_unsigned16: Some(4), + unsigned64: u64::MAX, + maybe_unsigned64: Some(u64::MIN), + signed8: 8, + maybe_signed8: Some(0), + signed64: i64::MAX, + maybe_signed64: Some(0), + float32: 1.2345, + maybe_float32: Some(22.0 / 7.0), + float64: 0.0, + maybe_float64: Some(1.0), + coveralls: Some(Arc::new(Coveralls::new("some_dict".to_string()))), + coveralls_list: vec![ + Some(Arc::new(Coveralls::new("some_dict_1".to_string()))), + None, + Some(Arc::new(Coveralls::new("some_dict_2".to_string()))), + ], + coveralls_map: [ + ( + "some_dict_3".to_string(), + Some(Arc::new(Coveralls::new("some_dict_3".to_string()))), + ), + ("none".to_string(), None), + ( + "some_dict_4".to_string(), + Some(Arc::new(Coveralls::new("some_dict_4".to_string()))), + ), + ] + .into_iter() + .collect(), + test_trait: Some(Arc::new(traits::Node::default())), + } +} + +fn create_none_dict() -> SimpleDict { + SimpleDict { + text: "text".to_string(), + some_bytes: b"some_bytes".to_vec(), + a_bool: true, + unsigned8: 1, + unsigned16: 3, + unsigned64: u64::MAX, + signed8: 8, + signed64: i64::MAX, + float32: 1.2345, + ..Default::default() + } +} + +fn get_num_alive() -> u64 { + *NUM_ALIVE.read().unwrap() +} + +type Result = std::result::Result; +type ComplexResult = std::result::Result; + +fn println(text: String) -> Result<()> { + println!("coveralls println: {text}"); + Ok(()) +} + +#[derive(Debug)] +pub struct Coveralls { + name: String, + // A reference to another Coveralls. Currently will be only a reference + // to `self`, so will create a circular reference. + other: Mutex>>, + // Repairs we've made to this coverall. + repairs: Mutex>, +} + +impl Coveralls { + fn new(name: String) -> Self { + *NUM_ALIVE.write().unwrap() += 1; + Self { + name, + other: Mutex::new(None), + repairs: Mutex::new(Vec::new()), + } + } + + fn fallible_new(name: String, should_fail: bool) -> Result { + if should_fail { + Err(CoverallError::TooManyHoles) + } else { + Ok(Self::new(name)) + } + } + + fn fallible_panic(&self, message: String) -> Result<()> { + panic!("{message}"); + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn panicking_new(message: String) -> Self { + panic!("{message}"); + } + + fn maybe_throw(&self, should_throw: bool) -> Result { + if should_throw { + Err(CoverallError::TooManyHoles) + } else { + Ok(true) + } + } + + fn maybe_throw_into(&self, should_throw: bool) -> Result { + if should_throw { + Err(InternalCoverallError::ExcessiveHoles) + } else { + Ok(true) + } + } + + fn maybe_throw_complex(&self, input: i8) -> ComplexResult { + match input { + 0 => Ok(true), + 1 => Err(ComplexError::OsError { + code: 10, + extended_code: 20, + }), + 2 => Err(ComplexError::PermissionDenied { + reason: "Forbidden".to_owned(), + }), + 3 => Err(ComplexError::UnknownError), + _ => panic!("Invalid input"), + } + } + + fn panic(&self, message: String) { + panic!("{message}"); + } + + fn strong_count(self: Arc) -> u64 { + Arc::strong_count(&self) as u64 + } + + fn take_other(&self, other: Option>) { + *self.other.lock().unwrap() = other.map(|arc| Arc::clone(&arc)) + } + + fn get_other(&self) -> Option> { + (*self.other.lock().unwrap()).clone() + } + + fn take_other_fallible(self: Arc) -> Result<()> { + Err(CoverallError::TooManyHoles) + } + + fn take_other_panic(self: Arc, message: String) { + panic!("{message}"); + } + + fn clone_me(&self) -> Arc { + let other = self.other.lock().unwrap(); + let new_other = Mutex::new(other.clone()); + *NUM_ALIVE.write().unwrap() += 1; + Arc::new(Self { + name: self.name.clone(), + other: new_other, + repairs: Mutex::new(Vec::new()), + }) + } + + fn get_status(&self, status: String) -> String { + format!("status: {status}") + } + + fn get_dict(&self, key: String, value: u64) -> HashMap { + let mut map = HashMap::new(); + map.insert(key, value); + map + } + + fn get_dict2(&self, key: String, value: u64) -> HashMap { + let mut map = HashMap::new(); + map.insert(key, value); + map + } + + fn get_dict3(&self, key: u32, value: u64) -> HashMap { + let mut map = HashMap::new(); + map.insert(key, value); + map + } + + fn add_patch(&self, patch: Arc) { + let repair = Repair { + when: SystemTime::now(), + patch, + }; + let mut repairs = self.repairs.lock().unwrap(); + repairs.push(repair); + } + + fn add_repair(&self, repair: Repair) { + let mut repairs = self.repairs.lock().unwrap(); + repairs.push(repair); + } + + fn get_repairs(&self) -> Vec { + let repairs = self.repairs.lock().unwrap(); + repairs.clone() + } + + fn reverse(&self, mut value: Vec) -> Vec { + value.reverse(); + value + } + + fn set_and_get_empty_struct(&self, empty_struct: EmptyStruct) -> EmptyStruct { + empty_struct + } +} + +impl Drop for Coveralls { + fn drop(&mut self) { + *NUM_ALIVE.write().unwrap() -= 1; + } +} + +#[derive(Debug, Clone)] +pub struct Repair { + when: SystemTime, + patch: Arc, +} + +#[derive(Debug, Clone, Copy)] +pub enum Color { + Red, + Blue, + Green, +} + +#[derive(Debug, Clone)] +struct Patch { + color: Color, +} + +impl Patch { + fn new(color: Color) -> Self { + Self { color } + } + + fn get_color(&self) -> Color { + self.color + } +} + +struct FalliblePatch {} + +impl FalliblePatch { + fn new() -> Result { + Err(CoverallError::TooManyHoles) + } + + fn secondary() -> Result { + Err(CoverallError::TooManyHoles) + } +} + +// This is a small implementation of a counter that allows waiting on one thread, +// and counting on another thread. We use it to test that the UniFFI generated scaffolding +// doesn't introduce unexpected locking behaviour between threads. +struct ThreadsafeCounter { + is_busy: AtomicBool, + count: AtomicI32, +} + +impl ThreadsafeCounter { + fn new() -> Self { + Self { + is_busy: AtomicBool::new(false), + count: AtomicI32::new(0), + } + } + + fn busy_wait(&self, ms: i32) { + self.is_busy.store(true, Ordering::SeqCst); + // Pretend to do some work in a blocking fashion. + std::thread::sleep(std::time::Duration::from_millis(ms as u64)); + self.is_busy.store(false, Ordering::SeqCst); + } + + fn increment_if_busy(&self) -> i32 { + if self.is_busy.load(Ordering::SeqCst) { + self.count.fetch_add(1, Ordering::SeqCst) + 1 + } else { + self.count.load(Ordering::SeqCst) + } + } +} + +#[derive(Default)] +pub struct IFirst; + +impl IFirst { + pub fn new() -> Self { + Self + } + + pub fn compare(&self, _other: Option>) -> bool { + false + } +} + +#[derive(Default)] +pub struct ISecond; + +impl ISecond { + pub fn new() -> Self { + Self + } + + pub fn compare(&self, _other: Option>) -> bool { + false + } +} + +pub struct EmptyStruct; + +#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)] +pub enum HTMLError { + #[error("InvalidHTML")] + InvalidHTML, +} + +pub fn validate_html(_source: String) -> Result<(), HTMLError> { + Err(HTMLError::InvalidHTML) +} + +// NOTE: upstream also exports `pub async fn async_bool(b: bool) -> bool` here. It is omitted +// in this copy because the C++ bindgen does not support async functions yet, and library-mode +// generation refuses any namespace that contains one. Restore it alongside async support. + +uniffi::include_scaffolding!("coverall"); diff --git a/fixtures/coverall/src/traits.rs b/fixtures/coverall/src/traits.rs new file mode 100644 index 0000000..0426163 --- /dev/null +++ b/fixtures/coverall/src/traits.rs @@ -0,0 +1,293 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::{ComplexError, CoverallError, Coveralls}; +use std::sync::{Arc, Mutex}; + +// namespace functions. +pub fn get_traits() -> Vec> { + vec![ + Arc::new(SimpleNodeImpl::default()), + Arc::new(Node::default()), + ] +} + +#[uniffi::trait_interface] +pub trait NodeTrait: Send + Sync + std::fmt::Debug { + fn name(&self) -> String; + + fn set_parent(&self, parent: Option>); + + fn get_parent(&self) -> Option>; + + fn strong_count(self: Arc) -> u64 { + Arc::strong_count(&self) as u64 + } +} + +pub fn ancestor_names(node: Arc) -> Vec { + let mut names = vec![]; + let mut parent = node.get_parent(); + while let Some(node) = parent { + names.push(node.name()); + parent = node.get_parent(); + } + names +} + +/// Test trait +/// +/// The goal here is to test all possible arg, return, and error types. +#[uniffi::trait_interface] +pub trait Getters: Send + Sync { + fn get_bool(&self, v: bool, arg2: bool) -> bool; + fn get_string(&self, v: String, arg2: bool) -> Result; + fn get_option(&self, v: String, arg2: bool) -> Result, ComplexError>; + fn get_list(&self, v: Vec, arg2: bool) -> Vec; + fn get_nothing(&self, v: String); + fn round_trip_object(&self, coveralls: Arc) -> Arc; +} + +pub fn test_round_trip_through_rust(getters: Arc) -> Arc { + getters +} + +pub fn test_round_trip_through_foreign(getters: Arc) { + let coveralls = getters.round_trip_object(Arc::new(Coveralls::new("round-trip".to_owned()))); + assert_eq!(coveralls.get_name(), "round-trip"); +} + +struct RustGetters; + +impl Getters for RustGetters { + fn get_bool(&self, v: bool, arg2: bool) -> bool { + v ^ arg2 + } + + fn get_string(&self, v: String, arg2: bool) -> Result { + if v == "too-many-holes" { + Err(CoverallError::TooManyHoles) + } else if v == "unexpected-error" { + panic!("unexpected error") + } else if arg2 { + Ok(v.to_uppercase()) + } else { + Ok(v) + } + } + + fn get_option(&self, v: String, arg2: bool) -> Result, ComplexError> { + if v == "os-error" { + Err(ComplexError::OsError { + code: 100, + extended_code: 200, + }) + } else if v == "unknown-error" { + Err(ComplexError::UnknownError) + } else if arg2 { + if !v.is_empty() { + Ok(Some(v.to_uppercase())) + } else { + Ok(None) + } + } else { + Ok(Some(v)) + } + } + + fn get_list(&self, v: Vec, arg2: bool) -> Vec { + if arg2 { + v + } else { + vec![] + } + } + + fn get_nothing(&self, _v: String) {} + + fn round_trip_object(&self, coveralls: Arc) -> Arc { + coveralls + } +} + +pub fn make_rust_getters() -> Arc { + Arc::new(RustGetters) +} + +pub fn test_getters(getters: Arc) { + assert!(!getters.get_bool(true, true)); + assert!(getters.get_bool(true, false)); + assert!(getters.get_bool(false, true)); + assert!(!getters.get_bool(false, false)); + + assert_eq!( + getters.get_string("hello".to_owned(), false).unwrap(), + "hello" + ); + assert_eq!( + getters.get_string("hello".to_owned(), true).unwrap(), + "HELLO" + ); + + assert_eq!( + getters.get_option("hello".to_owned(), true).unwrap(), + Some("HELLO".to_owned()) + ); + assert_eq!( + getters.get_option("hello".to_owned(), false).unwrap(), + Some("hello".to_owned()) + ); + assert_eq!(getters.get_option("".to_owned(), true).unwrap(), None); + + assert_eq!(getters.get_list(vec![1, 2, 3], true), vec![1, 2, 3]); + assert_eq!(getters.get_list(vec![1, 2, 3], false), Vec::::new()); + + // Call get_nothing to make sure it doesn't panic. There's no point in checking the output + // though + getters.get_nothing("hello".to_owned()); + + assert_eq!( + getters.get_string("too-many-holes".to_owned(), true), + Err(CoverallError::TooManyHoles) + ); + assert_eq!( + getters.get_option("os-error".to_owned(), true), + Err(ComplexError::OsError { + code: 100, + extended_code: 200 + }) + ); + assert_eq!( + getters.get_option("unknown-error".to_owned(), true), + Err(ComplexError::UnknownError) + ); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + getters.get_string("unexpected-error".to_owned(), true) + })); + assert!(result.is_err()); +} + +// An object only exposed as a `dyn T` +#[derive(Debug, Default)] +pub(crate) struct SimpleNodeImpl { + // A reference to another trait. + parent: Mutex>>, +} + +impl NodeTrait for SimpleNodeImpl { + fn name(&self) -> String { + "node-1".to_string() + } + + fn set_parent(&self, parent: Option>) { + *self.parent.lock().unwrap() = parent.map(|arc| Arc::clone(&arc)) + } + + fn get_parent(&self) -> Option> { + (*self.parent.lock().unwrap()).clone() + } +} + +// An object exported and also able to be exposed as a `dyn T` +#[derive(uniffi::Object, Debug, Default)] +#[uniffi::export(Debug)] +pub struct Node { + name: Option, + parent: Mutex>>, +} + +// The object methods. +#[uniffi::export] +impl Node { + #[uniffi::constructor] + fn new(name: String) -> Self { + Self { + parent: Mutex::new(Some(Arc::new(Node { + name: Some(format!("via {name}")), + parent: Mutex::new(None), + }))), + name: Some(name), + } + } + + fn describe_parent(&self) -> String { + format!("{:?}", self.parent.lock().unwrap()) + } +} + +// The trait impl also exposed as methods +#[uniffi::export] +impl NodeTrait for Node { + fn name(&self) -> String { + self.name.clone().unwrap_or_else(|| "node-2".to_string()) + } + + fn set_parent(&self, parent: Option>) { + *(self.parent.lock().unwrap()) = parent; + } + + fn get_parent(&self) -> Option> { + self.parent.lock().unwrap().clone() + } + + // Even though the trait supplies a default impl, we must have one + // or the foreign code doesn't know it exists. + fn strong_count(self: Arc) -> u64 { + Arc::strong_count(&self) as u64 + } +} + +#[uniffi::trait_interface] +pub trait StringUtil: Send + Sync { + fn concat(&self, a: &str, b: &str) -> String; +} + +pub struct StringUtilImpl1; +pub struct StringUtilImpl2; + +pub fn get_string_util_traits() -> Vec> { + vec![Arc::new(StringUtilImpl1), Arc::new(StringUtilImpl2)] +} + +impl StringUtil for StringUtilImpl1 { + fn concat(&self, a: &str, b: &str) -> String { + format!("{a}{b}") + } +} + +impl StringUtil for StringUtilImpl2 { + fn concat(&self, a: &str, b: &str) -> String { + format!("{a}{b}") + } +} + +/// Object that implements `StringUtil` +/// This lets us test what happens if foreign bindings pass in `StringUtilImpl` when `StringUtil` was expected. +/// Ideally, languages should coerce the object to it's trait, however that's not supported at this time. +/// The current test is simply that this doesn't cause a segfault (#2649) +#[derive(uniffi::Object)] +pub struct StringUtilObject { + separator: String, +} + +#[uniffi::export] +impl StringUtilObject { + #[uniffi::constructor] + pub fn new(separator: String) -> Self { + Self { separator } + } +} + +#[uniffi::export] +impl StringUtil for StringUtilObject { + fn concat(&self, a: &str, b: &str) -> String { + let separator = &self.separator; + format!("{a}{separator}{b}") + } +} + +#[uniffi::export] +pub fn concat_with_string_util(string_util: Arc, a: &str, b: &str) -> String { + string_util.concat(a, b) +} diff --git a/fixtures/custom-types-builtin/src/lib.rs b/fixtures/custom-types-builtin/src/lib.rs index d0653a5..cb009dc 100644 --- a/fixtures/custom-types-builtin/src/lib.rs +++ b/fixtures/custom-types-builtin/src/lib.rs @@ -56,7 +56,7 @@ pub struct CustomTypesBuiltin { } pub fn get_custom_types_builtin() -> CustomTypesBuiltin { - return CustomTypesBuiltin { + CustomTypesBuiltin { string: MyString("Hello, world!".to_string()), custom_string: CustomString("Custom string".to_string()), array: Array(vec!["Hello, world!".to_string()]), @@ -73,7 +73,7 @@ pub fn get_custom_types_builtin() -> CustomTypesBuiltin { uint64: UInt64(u64::MAX), flt: Float(f32::MAX), dbl: Double(f64::MAX), - }; + } } pub fn return_custom_types_builtin(custom_types: CustomTypesBuiltin) -> CustomTypesBuiltin { diff --git a/fixtures/error-types-builtin/src/lib.rs b/fixtures/error-types-builtin/src/lib.rs index 66b2f0a..91b77d6 100644 --- a/fixtures/error-types-builtin/src/lib.rs +++ b/fixtures/error-types-builtin/src/lib.rs @@ -228,9 +228,74 @@ fn oops_tuple(i: u16) -> Result<(), TupleError> { } } +#[uniffi::export] +impl TupleError { + fn describe(&self) -> String { + match self { + TupleError::Oops(s) => format!("oops: {s}"), + TupleError::Value(v) => format!("value: {v}"), + } + } +} + #[uniffi::export(default(t = None))] fn get_tuple(t: Option) -> TupleError { t.unwrap_or_else(|| TupleError::Oops("oops".to_string())) } +#[uniffi::export(with_foreign)] +pub trait ErrorProducer: Send + Sync { + fn produce(&self) -> TupleError; +} + +#[uniffi::export] +fn describe_produced(producer: Arc) -> String { + producer.produce().describe() +} + +#[derive(Debug)] +pub struct CustomError(pub u16); + +impl std::fmt::Display for CustomError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} + +uniffi::custom_type!(CustomError, TupleError, { + try_lift: |val| { + let TupleError::Value(v) = val else { + return Err(anyhow::anyhow!("not a Value variant")); + }; + Ok(CustomError(v)) + }, + lower: |val| TupleError::Value(val.0) +}); + +#[uniffi::export] +fn oops_custom(i: u16) -> Result<(), CustomError> { + Err(CustomError(i)) +} + +#[derive(Debug)] +pub struct CustomObjectError(pub Arc); + +impl std::fmt::Display for CustomObjectError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self.0) + } +} + +uniffi::custom_type!(CustomObjectError, Arc, { + try_lift: |val| Ok(CustomObjectError(val)), + lower: |val| val.0 +}); + +#[uniffi::export] +fn oops_custom_object() -> Result<(), CustomObjectError> { + Err(CustomObjectError(Arc::new( + anyhow::Error::msg("custom-object-oops").into(), + ))) +} + uniffi::include_scaffolding!("error_types_builtin"); diff --git a/fixtures/ext-types-export/src/lib.rs b/fixtures/ext-types-export/src/lib.rs index 593d6cf..5189665 100644 --- a/fixtures/ext-types-export/src/lib.rs +++ b/fixtures/ext-types-export/src/lib.rs @@ -32,6 +32,8 @@ impl Counter { self.value.load(std::sync::atomic::Ordering::SeqCst) } } + +#[uniffi::trait_interface] pub trait Greeter: Send + Sync { fn greet(&self) -> String; } @@ -41,6 +43,7 @@ pub enum Shape { Rectangle { width: f64, height: f64 }, } +#[uniffi::trait_interface] pub trait Vehicle: Send + Sync { fn year(&self) -> i32; } diff --git a/fixtures/ext-types-import/src/lib.rs b/fixtures/ext-types-import/src/lib.rs index 913a735..b47639e 100644 --- a/fixtures/ext-types-import/src/lib.rs +++ b/fixtures/ext-types-import/src/lib.rs @@ -70,4 +70,22 @@ pub fn vehicle_year(v: Arc) -> i32 { v.year() } +#[derive(uniffi::Object)] +pub struct LocalGreeter; + +#[uniffi::export] +impl LocalGreeter { + #[uniffi::constructor] + pub fn new() -> Self { + LocalGreeter + } +} + +#[uniffi::export] +impl Greeter for LocalGreeter { + fn greet(&self) -> String { + "local".to_string() + } +} + uniffi::include_scaffolding!("ext_types_import"); diff --git a/fixtures/record-enum-methods/Cargo.toml b/fixtures/record-enum-methods/Cargo.toml new file mode 100644 index 0000000..71ab6bc --- /dev/null +++ b/fixtures/record-enum-methods/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "uniffi-record-enum-methods" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["lib", "cdylib"] +name = "uniffi_record_enum_methods" + +[dependencies] +uniffi = { workspace = true } +thiserror = "2" diff --git a/fixtures/record-enum-methods/src/lib.rs b/fixtures/record-enum-methods/src/lib.rs new file mode 100644 index 0000000..0bf0641 --- /dev/null +++ b/fixtures/record-enum-methods/src/lib.rs @@ -0,0 +1,114 @@ +#[derive(uniffi::Error, Debug, thiserror::Error)] +pub enum ShapeError { + #[error("negative scale factor: {factor}")] + NegativeScale { factor: f64 }, +} + +#[derive(uniffi::Record, Clone, Debug, PartialEq)] +pub struct Point { + pub x: i32, + pub y: i32, +} + +#[uniffi::export] +impl Point { + pub fn magnitude_squared(&self) -> i64 { + (self.x as i64) * (self.x as i64) + (self.y as i64) * (self.y as i64) + } + + pub fn translated(&self, dx: i32, dy: i32) -> Point { + Point { + x: self.x + dx, + y: self.y + dy, + } + } + + pub fn label(&self) -> String { + format!("({}, {})", self.x, self.y) + } +} + +#[derive(uniffi::Enum, Clone, Debug, PartialEq)] +pub enum Shape { + Circle { radius: f64 }, + Rectangle { width: f64, height: f64 }, +} + +#[uniffi::export] +impl Shape { + pub fn area(&self) -> f64 { + match self { + Shape::Circle { radius } => std::f64::consts::PI * radius * radius, + Shape::Rectangle { width, height } => width * height, + } + } + + /// Fallible, to check that throwing methods work on enums too. + pub fn scaled(&self, factor: f64) -> Result { + if factor < 0.0 { + return Err(ShapeError::NegativeScale { factor }); + } + Ok(match self { + Shape::Circle { radius } => Shape::Circle { + radius: radius * factor, + }, + Shape::Rectangle { width, height } => Shape::Rectangle { + width: width * factor, + height: height * factor, + }, + }) + } + + pub fn describe(&self) -> String { + match self { + Shape::Circle { radius } => format!("circle r={radius}"), + Shape::Rectangle { width, height } => format!("rectangle {width}x{height}"), + } + } +} + +#[derive(uniffi::Enum, Clone, Debug)] +pub enum Flag { + On, + Off, +} + +#[uniffi::export] +impl Flag { + pub fn inverted(&self) -> Flag { + match self { + Flag::On => Flag::Off, + Flag::Off => Flag::On, + } + } +} + +#[uniffi::export] +pub trait Zeta: Send + Sync { + fn zeta(&self) -> i32; +} + +#[derive(uniffi::Object)] +pub struct Alpha; + +#[uniffi::export] +impl Alpha { + #[uniffi::constructor] + pub fn new() -> Self { + Alpha + } +} + +#[uniffi::export] +impl Zeta for Alpha { + fn zeta(&self) -> i32 { + 42 + } +} + +#[uniffi::export] +pub fn make_zeta() -> std::sync::Arc { + std::sync::Arc::new(Alpha) +} + +uniffi::setup_scaffolding!("record_enum_methods"); diff --git a/fixtures/renaming/Cargo.toml b/fixtures/renaming/Cargo.toml new file mode 100644 index 0000000..b86bf74 --- /dev/null +++ b/fixtures/renaming/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "uniffi-renaming" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["lib", "cdylib"] +name = "uniffi_renaming" + +[dependencies] +uniffi = { workspace = true } diff --git a/fixtures/renaming/src/lib.rs b/fixtures/renaming/src/lib.rs new file mode 100644 index 0000000..91a9e13 --- /dev/null +++ b/fixtures/renaming/src/lib.rs @@ -0,0 +1,48 @@ +#[derive(uniffi::Record, Clone, Debug)] +pub struct RustRecord { + pub rust_field: i32, +} + +#[derive(uniffi::Enum, Clone, Debug)] +pub enum RustEnum { + RustVariant { rust_variant_field: i32 }, + OtherVariant, +} + +#[derive(uniffi::Object)] +pub struct RustObject { + value: i32, +} + +#[uniffi::export] +impl RustObject { + #[uniffi::constructor] + pub fn new(value: i32) -> Self { + Self { value } + } + + pub fn rust_method(&self, rust_arg: i32) -> i32 { + self.value + rust_arg + } +} + +#[uniffi::export] +pub fn rust_function(rust_arg: i32) -> RustRecord { + RustRecord { + rust_field: rust_arg, + } +} + +#[uniffi::export] +pub fn make_rust_enum() -> RustEnum { + RustEnum::RustVariant { + rust_variant_field: 7, + } +} + +#[uniffi::export] +pub fn needs_escaping(value: i32) -> i32 { + value +} + +uniffi::setup_scaffolding!("renaming"); diff --git a/fixtures/renaming/uniffi.toml b/fixtures/renaming/uniffi.toml new file mode 100644 index 0000000..efb318f --- /dev/null +++ b/fixtures/renaming/uniffi.toml @@ -0,0 +1,15 @@ +[bindings.cpp.rename] +RustRecord = "CppRecord" +RustEnum = "CppEnum" +RustObject = "CppObject" + +"RustRecord.rust_field" = "cpp_field" +"RustEnum.RustVariant" = "CppVariant" +"RustEnum.RustVariant.rust_variant_field" = "cpp_variant_field" +"RustObject.rust_method" = "cpp_method" +"RustObject.rust_method.rust_arg" = "cpp_arg" + +rust_function = "cpp_function" +"rust_function.rust_arg" = "cpp_arg" + +"needs_escaping.value" = "class" diff --git a/fixtures/src/lib.rs b/fixtures/src/lib.rs index 9c31212..5fe16a9 100644 --- a/fixtures/src/lib.rs +++ b/fixtures/src/lib.rs @@ -19,6 +19,9 @@ mod uniffi_fixtures { uniffi_empty_type::uniffi_reexport_scaffolding!(); uniffi_reserved_field_name::uniffi_reexport_scaffolding!(); uniffi_type_flattening::uniffi_reexport_scaffolding!(); + uniffi_record_enum_methods::uniffi_reexport_scaffolding!(); + uniffi_renaming::uniffi_reexport_scaffolding!(); + uniffi_proc_macro::uniffi_reexport_scaffolding!(); uniffi_ext_types_export::uniffi_reexport_scaffolding!(); uniffi_ext_types_import::uniffi_reexport_scaffolding!(); diff --git a/fixtures/type-flattening/src/lib.rs b/fixtures/type-flattening/src/lib.rs index ce66939..696c852 100644 --- a/fixtures/type-flattening/src/lib.rs +++ b/fixtures/type-flattening/src/lib.rs @@ -30,4 +30,52 @@ pub fn struct_roundtrip(structure: Structure) -> Structure { structure } +pub struct OptionalDefaults { + pub maybe_int: Option, + pub maybe_text: Option, + pub maybe_bool: Option, + pub maybe_null: Option, +} + +/// C++ types whose default value has to coincide with Rust's `Default`. The rest fail on generation instead. +#[derive(uniffi::Record)] +pub struct SupportedDefaults { + #[uniffi(default)] + pub int: i32, + #[uniffi(default)] + pub flag: bool, + #[uniffi(default)] + pub float: f64, + #[uniffi(default)] + pub text: String, + #[uniffi(default)] + pub bytes: Vec, + #[uniffi(default)] + pub maybe: Option, + #[uniffi(default)] + pub list: Vec, + #[uniffi(default)] + pub table: std::collections::HashMap, + #[uniffi(default)] + pub maybe_object: Option>, + #[uniffi(default)] + pub enum_list: Vec, + #[uniffi(default)] + pub enum_table: std::collections::HashMap, +} + +#[derive(uniffi::Enum)] +pub enum Shape { + Circle { radius: f64 }, +} + +pub enum Colour { + Red, + Green, +} + +pub struct OptionalEnumDefault { + pub maybe_colour: Option, +} + uniffi::include_scaffolding!("type_flattening"); diff --git a/fixtures/type-flattening/src/type_flattening.udl b/fixtures/type-flattening/src/type_flattening.udl index ec04355..5d95a2c 100644 --- a/fixtures/type-flattening/src/type_flattening.udl +++ b/fixtures/type-flattening/src/type_flattening.udl @@ -1,3 +1,19 @@ namespace type_flattening { }; + +dictionary OptionalDefaults { + i32? maybe_int = 42; + string? maybe_text = "hello"; + boolean? maybe_bool = true; + i32? maybe_null = null; +}; + +enum Colour { + "Red", + "Green", +}; + +dictionary OptionalEnumDefault { + Colour? maybe_colour = "Red"; +};