From 40c99525a125acd3ac0f2eb792c452640dbae388 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 16 Oct 2026 08:50:19 -0700 Subject: [PATCH 1/2] Strip a type prefix, and always use the bundled tl::expected `strip_type_prefix = "Foo"` names `FooClient` as `Client`, so a crate that prefixes its types for languages without namespaces needs no alias list in C++. It renames through uniffi's `rename`, which skips a constructor's error type and leaves `get_type` keyed by the old names, so the type oracle renames each type it renders as well and `sorted_types` looks types up by name. A rename onto an existing type fails generation. `error_style = "expected"` now always uses the bundled `tl::expected`, never `std::expected`, so bindings built at C++17 link with code built at C++23 instead of silently disagreeing on the type. With exceptions disabled, `value()` on an error aborts with a message instead of reaching `__builtin_unreachable()`. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++ README.md | 2 +- bindgen/src/bindings/cpp/expected.hpp | 20 +----- .../src/bindings/cpp/gen_cpp/filters/mod.rs | 4 +- bindgen/src/bindings/cpp/gen_cpp/mod.rs | 33 +++++++++- bindgen/src/bindings/cpp/mod.rs | 63 +++++++++++++++++-- bindgen/src/bindings/cpp/vendor/README.md | 5 +- .../src/bindings/cpp/vendor/tl_expected.hpp | 10 +-- cpp-tests/CMakeLists.txt | 23 ++++++- cpp-tests/collision.toml | 2 + cpp-tests/renamed.toml | 3 + cpp-tests/tests/expected/main.cpp | 27 +++++++- docs/CONFIGURATION.md | 19 ++++-- 13 files changed, 180 insertions(+), 40 deletions(-) create mode 100644 cpp-tests/collision.toml create mode 100644 cpp-tests/renamed.toml diff --git a/CHANGELOG.md b/CHANGELOG.md index 50667cc..6a22ca6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +#### Unreleased + +---- +- **BREAKING** Core: `error_style = "expected"` always uses the bundled `tl::expected`, never + `std::expected`, so bindings built at one C++ standard link with code built at another. With + exceptions disabled, `value()` on an error now aborts with a message instead of being undefined +- Core: Add the `strip_type_prefix` option, which drops a prefix from type names + (`FooClient` becomes `Client`) + #### v0.11.0-kixelated.4+v0.32.2 ---- diff --git a/README.md b/README.md index 28e5879..a897cfb 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ cargo install uniffi-bindgen-cpp --git https://github.com/NordSecurity/uniffi-bi ``` This fork carries LiveKit's async support (`livekit/uniffi-0.31-async`) ported to UniFFI 0.32, plus -the `error_style = "expected"` option. Its tags add a `-kixelated.N` pre-release so they never +the `error_style = "expected"` and `strip_type_prefix` options. Its tags add a `-kixelated.N` pre-release so they never collide with upstream's: ```bash diff --git a/bindgen/src/bindings/cpp/expected.hpp b/bindgen/src/bindings/cpp/expected.hpp index 819570f..caa1099 100644 --- a/bindgen/src/bindings/cpp/expected.hpp +++ b/bindgen/src/bindings/cpp/expected.hpp @@ -1,27 +1,11 @@ // Generated by uniffi-bindgen-cpp for `error_style = "expected"`. // -// `uniffi::expected` is `std::expected` when the standard library has it and the bundled -// `tl::expected` otherwise. Every translation unit that shares these bindings must agree on -// which one it gets, so build the generated sources with the same standard as their users. +// `uniffi::expected` is the bundled `tl::expected` at every C++ standard, never `std::expected`, +// so bindings built at one standard link with code built at another. #pragma once -#if defined(__has_include) -#if __has_include() -#include -#endif -#endif - -#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202211L -#include - -namespace uniffi { -using std::expected; -using std::unexpected; -} // namespace uniffi -#else {tl_expected} namespace uniffi { using tl::expected; using tl::unexpected; } // namespace uniffi -#endif diff --git a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs index 5e28707..733e99a 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs @@ -12,7 +12,7 @@ use crate::bindings::cpp::{ CodeType, }; -use super::{error_style, EnumStyle, ErrorStyle}; +use super::{error_style, renamed, EnumStyle, ErrorStyle}; type Result = std::result::Result; @@ -176,7 +176,7 @@ pub(crate) trait AsCodeType { impl AsCodeType for T { fn as_codetype(&self) -> Box { - match self.as_type() { + match renamed(self.as_type()) { Type::UInt8 => Box::new(primitives::UInt8CodeType), Type::Int8 => Box::new(primitives::Int8CodeType), Type::UInt16 => Box::new(primitives::UInt16CodeType), diff --git a/bindgen/src/bindings/cpp/gen_cpp/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/mod.rs index 6d393c1..1ddcb47 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/mod.rs @@ -69,12 +69,27 @@ thread_local! { // The type oracle renders type labels without access to the config, and the error style // changes how an error type is spelled, so generation publishes it here. static ERROR_STYLE: Cell = const { Cell::new(ErrorStyle::Exceptions) }; + + // uniffi's `rename` misses some types, such as a constructor's error, so the oracle renames + // each type it renders as well. + static RENAMES: RefCell> = RefCell::default(); } pub(crate) fn error_style() -> ErrorStyle { ERROR_STYLE.with(Cell::get) } +/// `ty` with every type it names under its new name. +pub(crate) fn renamed(mut ty: Type) -> Type { + RENAMES.with(|renames| { + let renames = renames.borrow(); + if !renames.is_empty() { + ty.rename_recursive(&|name| renames.get(name).map_or(name, String::as_str).into()); + } + }); + ty +} + #[derive(Clone, Deserialize, Serialize, Debug, Default)] pub(crate) struct Config { #[serde(default)] @@ -83,6 +98,11 @@ pub(crate) struct Config { enum_style: EnumStyle, #[serde(default)] error_style: ErrorStyle, + #[serde(default)] + strip_type_prefix: Option, + /// Every type renamed by `strip_type_prefix`, across all components, old name to new. + #[serde(skip)] + pub(crate) renames: HashMap, } impl Config { @@ -101,6 +121,10 @@ impl Config { pub(crate) fn enum_style(&self) -> &EnumStyle { &self.enum_style } + + pub(crate) fn strip_type_prefix(&self) -> Option<&str> { + self.strip_type_prefix.as_deref() + } } #[derive(Clone, Deserialize, Serialize, Debug, Default)] @@ -256,7 +280,13 @@ impl<'a> CppWrapperHeader<'a> { if !emitted_names.insert(name) { continue; } - match self.ci.get_type(name) { + // Not `ci.get_type`: uniffi's `rename` leaves that index under the old names. + let found = self + .ci + .iter_local_types() + .chain(self.ci.iter_external_types()) + .find(|t| type_name(t) == Some(name)); + match found { // 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. @@ -407,6 +437,7 @@ pub(crate) fn generate_cpp_bindings(ci: &ComponentInterface, config: &Config) -> } } ERROR_STYLE.with(|style| style.set(config.error_style)); + RENAMES.with(|renames| renames.replace(config.renames.clone())); let scaffolding_header = ScaffoldingHeader::new(ci) .render() diff --git a/bindgen/src/bindings/cpp/mod.rs b/bindgen/src/bindings/cpp/mod.rs index a99f3fd..603e3a1 100644 --- a/bindgen/src/bindings/cpp/mod.rs +++ b/bindgen/src/bindings/cpp/mod.rs @@ -1,11 +1,16 @@ pub(crate) mod gen_cpp; -use std::{fmt::Debug, fs}; +use std::{ + collections::{BTreeSet, HashMap}, + fmt::Debug, + fs, +}; use anyhow::Result; use camino::Utf8Path; use uniffi_bindgen::{ - interface::Literal, BindingGenerator, Component, ComponentInterface, GenerationSettings, + interface::{rename, Literal, Type}, + BindingGenerator, Component, ComponentInterface, GenerationSettings, }; use self::gen_cpp::{generate_cpp_bindings, Bindings}; @@ -62,9 +67,29 @@ impl BindingGenerator for CppBindingGenerator { fn update_component_configs( &self, _settings: &GenerationSettings, - _components: &mut Vec>, + components: &mut Vec>, ) -> Result<()> { - return Ok(()); + // Keyed by crate, so a component that imports a renamed type sees the new name too. + let mut renames = HashMap::new(); + for Component { ci, config, .. } in components.iter() { + if let Some(prefix) = config.strip_type_prefix() { + renames.insert(ci.crate_name().to_string(), strip_type_prefix(ci, prefix)?); + } + } + if renames.is_empty() { + return Ok(()); + } + + let flat: HashMap = renames + .values() + .flatten() + .filter_map(|(old, new)| Some((old.clone(), new.as_str()?.to_string()))) + .collect(); + for component in components.iter_mut() { + rename(&mut component.ci, &renames); + component.config.renames = flat.clone(); + } + Ok(()) } fn write_bindings( @@ -83,6 +108,36 @@ impl BindingGenerator for CppBindingGenerator { } } +/// Renames each local record, object, enum, and callback interface named `` to +/// ``, where `` starts with an uppercase letter. Custom types keep their names, since +/// `custom_types` is keyed by them. Refuses a rename onto a name that is already a type. +fn strip_type_prefix(ci: &ComponentInterface, prefix: &str) -> Result { + let names: BTreeSet<&str> = ci.iter_local_types().filter_map(Type::name).collect(); + + let mut renames = toml::Table::new(); + for ty in ci.iter_local_types() { + let name = match ty { + Type::Record { name, .. } + | Type::Object { name, .. } + | Type::Enum { name, .. } + | Type::CallbackInterface { name, .. } => name, + _ => continue, + }; + let Some(stripped) = name.strip_prefix(prefix) else { + continue; + }; + if !stripped.starts_with(|c: char| c.is_ascii_uppercase()) { + continue; + } + anyhow::ensure!( + !names.contains(stripped), + "strip_type_prefix = \"{prefix}\" renames `{name}` to `{stripped}`, which is already a type" + ); + renames.insert(name.clone(), stripped.into()); + } + Ok(renames) +} + /// Writes `.hpp`, `.cpp`, and `_scaffolding.hpp`, plus /// `uniffi_expected.hpp` under the expected error style. pub(crate) fn write_cpp_bindings( diff --git a/bindgen/src/bindings/cpp/vendor/README.md b/bindgen/src/bindings/cpp/vendor/README.md index 91d51c0..a9197ea 100644 --- a/bindgen/src/bindings/cpp/vendor/README.md +++ b/bindgen/src/bindings/cpp/vendor/README.md @@ -1,3 +1,4 @@ `tl_expected.hpp` is [TartanLlama/expected](https://github.com/TartanLlama/expected) v1.1.0 -(`include/tl/expected.hpp`), unmodified, under CC0. The `error_style = "expected"` bindings ship -it as the `expected` type below C++23. +(`include/tl/expected.hpp`) under CC0. The `error_style = "expected"` bindings ship it as their +`expected` type at every C++ standard. One change: with exceptions disabled, `value()` on an error +prints a message and aborts instead of being `__builtin_unreachable()`. diff --git a/bindgen/src/bindings/cpp/vendor/tl_expected.hpp b/bindgen/src/bindings/cpp/vendor/tl_expected.hpp index afee404..5b9f23e 100644 --- a/bindgen/src/bindings/cpp/vendor/tl_expected.hpp +++ b/bindgen/src/bindings/cpp/vendor/tl_expected.hpp @@ -20,6 +20,8 @@ #define TL_EXPECTED_VERSION_MINOR 1 #define TL_EXPECTED_VERSION_PATCH 0 +#include +#include #include #include #include @@ -214,11 +216,9 @@ template throw std::forward(e); #else (void)e; -#ifdef _MSC_VER - __assume(0); -#else - __builtin_unreachable(); -#endif + std::fputs("uniffi: expected::value() called on an error\n", stderr); + std::fflush(stderr); + std::abort(); #endif } diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index ce13278..436ac61 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -129,7 +129,8 @@ add_executable(expected-test tests/expected/main.cpp ${EXPECTED_BINDINGS_DIR}/futures.cpp ${EXPECTED_BINDINGS_DIR}/error_types_builtin.cpp - ${EXPECTED_BINDINGS_DIR}/trait_methods.cpp) + ${EXPECTED_BINDINGS_DIR}/trait_methods.cpp + ${EXPECTED_BINDINGS_DIR}/capi.cpp) target_include_directories(expected-test PRIVATE ${EXPECTED_BINDINGS_DIR}) target_link_directories(expected-test PRIVATE ${BINDINGS_BUILD_DIR}) target_link_libraries(expected-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) @@ -143,10 +144,26 @@ add_dependencies(expected-test bindings-expected) add_test(NAME expected-test COMMAND expected-test) set_tests_properties(expected-test PROPERTIES TIMEOUT 30) memcheck_test(expected-test) +# Reading the value of an error aborts with a message, rather than being undefined. +add_test(NAME expected-value-on-error-test COMMAND expected-test value-on-error) +set_tests_properties(expected-value-on-error-test PROPERTIES + TIMEOUT 30 + PASS_REGULAR_EXPRESSION "uniffi: expected::value\\(\\) called on an error") list(APPEND EXPECTED_BINDING_FILES ${EXPECTED_BINDINGS_DIR}/futures.cpp ${EXPECTED_BINDINGS_DIR}/error_types_builtin.cpp - ${EXPECTED_BINDINGS_DIR}/trait_methods.cpp) + ${EXPECTED_BINDINGS_DIR}/trait_methods.cpp + ${EXPECTED_BINDINGS_DIR}/capi.cpp) + +# `strip_type_prefix` refuses to rename a type onto one that already exists. +add_test(NAME strip-type-prefix-collision-test + COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX} + --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_cpp_error_types_builtin + --config ${CMAKE_CURRENT_SOURCE_DIR}/collision.toml + --out-dir ${CMAKE_CURRENT_BINARY_DIR}/collision + WORKING_DIRECTORY ${BINDINGS_BUILD_DIR}) +set_tests_properties(strip-type-prefix-collision-test PROPERTIES + PASS_REGULAR_EXPRESSION "renames `Flat[A-Za-z]+` to `[A-Za-z]+`, which is already a type") # The C backend: a C11 header over expected-style C++ bindings, built without exceptions. set(C_BINDINGS_DIR ${BINDINGS_BUILD_DIR}/bindings-c) @@ -230,6 +247,8 @@ add_custom_target(bindings-expected ALL --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_trait_methods --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected + COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_c_api + --config ${CMAKE_CURRENT_SOURCE_DIR}/renamed.toml --out-dir bindings-expected WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} COMMENT "Generating expected-style bindings" ) diff --git a/cpp-tests/collision.toml b/cpp-tests/collision.toml new file mode 100644 index 0000000..ccf2a89 --- /dev/null +++ b/cpp-tests/collision.toml @@ -0,0 +1,2 @@ +[bindings.cpp] +strip_type_prefix = "Flat" diff --git a/cpp-tests/renamed.toml b/cpp-tests/renamed.toml new file mode 100644 index 0000000..8caf688 --- /dev/null +++ b/cpp-tests/renamed.toml @@ -0,0 +1,3 @@ +[bindings.cpp] +error_style = "expected" +strip_type_prefix = "Capi" diff --git a/cpp-tests/tests/expected/main.cpp b/cpp-tests/tests/expected/main.cpp index e3dba3d..f8c12fa 100644 --- a/cpp-tests/tests/expected/main.cpp +++ b/cpp-tests/tests/expected/main.cpp @@ -1,13 +1,16 @@ // Bindings generated with `error_style = "expected"`, built with exceptions and RTTI disabled. +#include #include #include #include #include #include +#include #include #include +#include #include #include @@ -89,6 +92,19 @@ void error_display() { CHECK(nested.error().to_debug_string() == "Nested(NotFound)"); } +void renamed_types() { + // `strip_type_prefix = "Capi"` names every type without the prefix, in signatures too. + auto store = capi::Store::open("store"); + CHECK(store && (*store)->name() == "store"); + + // uniffi's own rename skips a constructor's error type. + auto empty = capi::Store::open(""); + CHECK(!empty); + auto invalid = variant_of(empty.error()); + CHECK(invalid && invalid->v1 == "empty name"); + CHECK(empty.error().to_string() == "invalid: empty name"); +} + void async_results() { CHECK(futures::greet("C++") == "Hello, C++"); CHECK(futures::always_ready().get()); @@ -198,9 +214,18 @@ void shutdown() { CHECK(late.wait_for(0ms) == std::future_status::ready); } -int main() { +int main(int argc, char **argv) { + if (argc > 1 && std::strcmp(argv[1], "value-on-error") == 0) { + // The abort is the expected outcome; the test matches the message printed before it. + std::signal(SIGABRT, [](int) { std::_Exit(0); }); + auto empty = capi::Store::open(""); + (void)empty.value(); + return 1; + } + sync_errors(); error_display(); + renamed_types(); async_results(); continuations(); cancellation(); diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 1f6e2fe..c4dd9ff 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -41,15 +41,26 @@ NOTE: the `enum_style` option is separate for bindings and scaffolding generator - `"exceptions"` - throw the error (default) - `"expected"` - return it, and never throw, so the bindings build with `-fno-exceptions` +- `strip_type_prefix` - a prefix to drop from type names, for crates that prefix their exported + types to keep them unique in languages without namespaces. With `strip_type_prefix = "Foo"`, the + records, objects, enums, and callback interfaces `FooClient` and `FooError` become + `Client` and `Error`. A name continues only after an uppercase letter, so `Foobar` stays as is, + and custom types keep their names. Generation fails if a stripped name is already a type. + + ```toml + [bindings.cpp] + strip_type_prefix = "Foo" + ``` + ### `error_style = "expected"` A fallible function returns `uniffi::expected`, and an async one returns `uniffi::Future` whose `get()` and `then()` continuation deliver the same `expected`. An infallible async function returns `uniffi::Future`, which delivers a plain `T`. -`uniffi::expected` is `std::expected` when the standard library provides it (C++23) and a bundled -[`tl::expected`](https://github.com/TartanLlama/expected) otherwise, written next to the bindings -as `uniffi_expected.hpp`. Build the generated sources with the same standard as the code that -includes them, so both see the same type. +`uniffi::expected` is a bundled [`tl::expected`](https://github.com/TartanLlama/expected), written +next to the bindings as `uniffi_expected.hpp`. It is never `std::expected`, even at C++23, so +generated sources built at one standard link with code built at another. With exceptions disabled, +`value()` on an error aborts with a message. Error enums are plain values rather than exception classes: every error enum becomes a struct holding a `std::variant` of its variants, like any other enum with fields. A flat error From f42a41584e63baa9548a3d8abc5ee99330da3a3f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 16 Oct 2026 19:10:59 -0700 Subject: [PATCH 2/2] Release v0.11.0-kixelated.5+v0.32.2 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- Cargo.lock | 2 +- README.md | 2 +- bindgen/Cargo.toml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a22ca6..230c45f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -#### Unreleased +#### v0.11.0-kixelated.5+v0.32.2 ---- - **BREAKING** Core: `error_style = "expected"` always uses the bundled `tl::expected`, never diff --git a/Cargo.lock b/Cargo.lock index 8503b4c..b975209 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -874,7 +874,7 @@ dependencies = [ [[package]] name = "uniffi-bindgen-cpp" -version = "0.11.0-kixelated.4+v0.32.2" +version = "0.11.0-kixelated.5+v0.32.2" dependencies = [ "anyhow", "askama 0.13.1", diff --git a/README.md b/README.md index a897cfb..f3069f7 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ the `error_style = "expected"` and `strip_type_prefix` options. Its tags add a ` collide with upstream's: ```bash -cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.4+v0.32.2 +cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.5+v0.32.2 ``` # How to generate bindings diff --git a/bindgen/Cargo.toml b/bindgen/Cargo.toml index caa083c..aa4af62 100644 --- a/bindgen/Cargo.toml +++ b/bindgen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "uniffi-bindgen-cpp" -version = "0.11.0-kixelated.4+v0.32.2" +version = "0.11.0-kixelated.5+v0.32.2" edition = "2021" [dependencies]