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

Filter by extension

Filter by extension


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

----
- **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

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

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

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ 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
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
Expand Down
2 changes: 1 addition & 1 deletion bindgen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uniffi-bindgen-cpp"
version = "0.11.0-kixelated.4+v0.32.2"
version = "0.11.0-kixelated.5+v0.32.2"
edition = "2021"

[dependencies]
Expand Down
20 changes: 2 additions & 18 deletions bindgen/src/bindings/cpp/expected.hpp
Original file line number Diff line number Diff line change
@@ -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(<version>)
#include <version>
#endif
#endif

#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202211L
#include <expected>

namespace uniffi {
using std::expected;
using std::unexpected;
} // namespace uniffi
#else
{tl_expected}
namespace uniffi {
using tl::expected;
using tl::unexpected;
} // namespace uniffi
#endif
4 changes: 2 additions & 2 deletions bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::bindings::cpp::{
CodeType,
};

use super::{error_style, EnumStyle, ErrorStyle};
use super::{error_style, renamed, EnumStyle, ErrorStyle};

type Result<T> = std::result::Result<T, askama::Error>;

Expand Down Expand Up @@ -176,7 +176,7 @@ pub(crate) trait AsCodeType {

impl<T: AsType> AsCodeType for T {
fn as_codetype(&self) -> Box<dyn CodeType> {
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),
Expand Down
33 changes: 32 additions & 1 deletion bindgen/src/bindings/cpp/gen_cpp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ErrorStyle> = 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<HashMap<String, String>> = 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)]
Expand All @@ -83,6 +98,11 @@ pub(crate) struct Config {
enum_style: EnumStyle,
#[serde(default)]
error_style: ErrorStyle,
#[serde(default)]
strip_type_prefix: Option<String>,
/// Every type renamed by `strip_type_prefix`, across all components, old name to new.
#[serde(skip)]
pub(crate) renames: HashMap<String, String>,
}

impl Config {
Expand All @@ -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)]
Expand Down Expand Up @@ -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));
Comment on lines +284 to +288

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish external types in dependency lookup

When stripping a prefix makes a local record share a simple name with an imported record—for example, local FooCoordinates becomes Coordinates while one of its fields is ext::Coordinates—this name-only, local-first lookup conflates the two. The dependency graph can consequently contain a false Coordinates -> Coordinates self-edge and report a cyclic dependency even though the C++ types are valid in separate namespaces. Use the module path as part of topology keys and lookup.

Useful? React with 👍 / 👎.

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.
Expand Down Expand Up @@ -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()
Expand Down
63 changes: 59 additions & 4 deletions bindgen/src/bindings/cpp/mod.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -62,9 +67,29 @@ impl BindingGenerator for CppBindingGenerator {
fn update_component_configs(
&self,
_settings: &GenerationSettings,
_components: &mut Vec<uniffi_bindgen::Component<Self::Config>>,
components: &mut Vec<uniffi_bindgen::Component<Self::Config>>,
) -> 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<String, String> = renames
.values()
.flatten()
.filter_map(|(old, new)| Some((old.clone(), new.as_str()?.to_string())))
.collect();
Comment on lines +83 to +87

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep fallback renames scoped to their defining crate

When library mode generates multiple components, flattening the crate-keyed rename tables and copying the result to every component loses the type's module identity. If one generated crate strips FooError while another component imports an unrenamed FooError from a crate not present in renames—or two crates map the same spelling differently—renamed() rewrites that reference using this global entry even though the defining header retains the original name, producing uncompilable bindings. Preserve the crate/module key in the fallback mapping.

Useful? React with 👍 / 👎.

for component in components.iter_mut() {
rename(&mut component.ci, &renames);
component.config.renames = flat.clone();
}
Ok(())
}

fn write_bindings(
Expand All @@ -83,6 +108,36 @@ impl BindingGenerator for CppBindingGenerator {
}
}

/// Renames each local record, object, enum, and callback interface named `<prefix><Name>` to
/// `<Name>`, where `<Name>` 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<toml::Table> {
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 `<namespace>.hpp`, `<namespace>.cpp`, and `<namespace>_scaffolding.hpp`, plus
/// `uniffi_expected.hpp` under the expected error style.
pub(crate) fn write_cpp_bindings(
Expand Down
5 changes: 3 additions & 2 deletions bindgen/src/bindings/cpp/vendor/README.md
Original file line number Diff line number Diff line change
@@ -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()`.
10 changes: 5 additions & 5 deletions bindgen/src/bindings/cpp/vendor/tl_expected.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
#define TL_EXPECTED_VERSION_MINOR 1
#define TL_EXPECTED_VERSION_PATCH 0

#include <cstdio>
#include <cstdlib>
#include <exception>
#include <functional>
#include <type_traits>
Expand Down Expand Up @@ -214,11 +216,9 @@ template <typename E>
throw std::forward<E>(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
}

Expand Down
23 changes: 21 additions & 2 deletions cpp-tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand All @@ -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)
Expand Down Expand Up @@ -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"
)
2 changes: 2 additions & 0 deletions cpp-tests/collision.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[bindings.cpp]
strip_type_prefix = "Flat"
3 changes: 3 additions & 0 deletions cpp-tests/renamed.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[bindings.cpp]
error_style = "expected"
strip_type_prefix = "Capi"
27 changes: 26 additions & 1 deletion cpp-tests/tests/expected/main.cpp
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// Bindings generated with `error_style = "expected"`, built with exceptions and RTTI disabled.

#include <capi.hpp>
#include <error_types_builtin.hpp>
#include <futures.hpp>
#include <trait_methods.hpp>

#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <variant>

Expand Down Expand Up @@ -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<capi::Error::kInvalid>(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());
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading