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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
#### v0.11.0-kixelated.6+v0.32.2

----
- Core: Add the `strip_function_prefix` option, which drops a prefix from top-level function names
(`foo_connect` becomes `connect`)

#### v0.11.0-kixelated.5+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"` and `strip_type_prefix` options. Its tags add a `-kixelated.N` pre-release so they never
the `error_style = "expected"`, `strip_type_prefix`, and `strip_function_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.5+v0.32.2
cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.6+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.5+v0.32.2"
version = "0.11.0-kixelated.6+v0.32.2"
edition = "2021"

[dependencies]
Expand Down
2 changes: 1 addition & 1 deletion bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type Result<T> = std::result::Result<T, askama::Error>;

// Keywords and other commonly used words that are in fact macros that
// expand to expressions (like `errno`).
const RESERVED_CPP_WORDS: [&str; 100] = [
pub(crate) const RESERVED_CPP_WORDS: [&str; 100] = [
// Keywords
"alignas",
"alignof",
Expand Down
6 changes: 6 additions & 0 deletions bindgen/src/bindings/cpp/gen_cpp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ pub(crate) struct Config {
error_style: ErrorStyle,
#[serde(default)]
strip_type_prefix: Option<String>,
#[serde(default)]
strip_function_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>,
Expand All @@ -125,6 +127,10 @@ impl Config {
pub(crate) fn strip_type_prefix(&self) -> Option<&str> {
self.strip_type_prefix.as_deref()
}

pub(crate) fn strip_function_prefix(&self) -> Option<&str> {
self.strip_function_prefix.as_deref()
}
}

#[derive(Clone, Deserialize, Serialize, Debug, Default)]
Expand Down
53 changes: 45 additions & 8 deletions bindgen/src/bindings/cpp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use uniffi_bindgen::{
BindingGenerator, Component, ComponentInterface, GenerationSettings,
};

use self::gen_cpp::{generate_cpp_bindings, Bindings};
use self::gen_cpp::{filters::RESERVED_CPP_WORDS, generate_cpp_bindings, Bindings};

pub(crate) struct CppBindingGenerator {
pub scaffolding_mode: bool,
Expand Down Expand Up @@ -71,23 +71,33 @@ impl BindingGenerator for CppBindingGenerator {
) -> Result<()> {
// Keyed by crate, so a component that imports a renamed type sees the new name too.
let mut renames = HashMap::new();
// Types only: the type oracle renames each type it renders, and functions are not types.
let mut type_renames = HashMap::new();
for Component { ci, config, .. } in components.iter() {
let mut table = toml::Table::new();
if let Some(prefix) = config.strip_type_prefix() {
renames.insert(ci.crate_name().to_string(), strip_type_prefix(ci, prefix)?);
let types = strip_type_prefix(ci, prefix)?;
type_renames.extend(
types
.iter()
.filter_map(|(old, new)| Some((old.clone(), new.as_str()?.to_string()))),
);
table.extend(types);
}
if let Some(prefix) = config.strip_function_prefix() {
table.extend(strip_function_prefix(ci, prefix)?);
}
if !table.is_empty() {
renames.insert(ci.crate_name().to_string(), table);
}
}
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();
for component in components.iter_mut() {
rename(&mut component.ci, &renames);
component.config.renames = flat.clone();
component.config.renames = type_renames.clone();
}
Ok(())
}
Expand Down Expand Up @@ -138,6 +148,33 @@ fn strip_type_prefix(ci: &ComponentInterface, prefix: &str) -> Result<toml::Tabl
Ok(renames)
}

/// Renames each top-level function named `<prefix><name>` to `<name>`, where `<name>` starts with a
/// lowercase letter. Methods keep their names, since their class already scopes them. Refuses a
/// rename onto a name that is already a function or a C++ keyword.
fn strip_function_prefix(ci: &ComponentInterface, prefix: &str) -> Result<toml::Table> {
let names: BTreeSet<&str> = ci.function_definitions().iter().map(|f| f.name()).collect();

let mut renames = toml::Table::new();
for name in &names {
let Some(stripped) = name.strip_prefix(prefix) else {
continue;
};
if !stripped.starts_with(|c: char| c.is_ascii_lowercase()) {
continue;
}
anyhow::ensure!(
!names.contains(stripped),
"strip_function_prefix = \"{prefix}\" renames `{name}` to `{stripped}`, which is already a function"
);
anyhow::ensure!(
!RESERVED_CPP_WORDS.contains(&stripped),
"strip_function_prefix = \"{prefix}\" renames `{name}` to `{stripped}`, which is reserved in C++"
);
renames.insert(name.to_string(), 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
20 changes: 20 additions & 0 deletions cpp-tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,26 @@ add_test(NAME strip-type-prefix-collision-test
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")

# `strip_function_prefix` refuses to rename a function onto one that already exists, or onto a
# C++ keyword. `--config` applies to every crate in the library, whose order varies by platform, so
# each prefix renames onto a taken name in exactly one crate.
add_test(NAME strip-function-prefix-collision-test
COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX}
--library ${UNIFFI_FIXTURES_LIB} --crate uniffi_fixture_async_calls
--config ${CMAKE_CURRENT_SOURCE_DIR}/function-collision.toml
--out-dir ${CMAKE_CURRENT_BINARY_DIR}/function-collision
WORKING_DIRECTORY ${BINDINGS_BUILD_DIR})
set_tests_properties(strip-function-prefix-collision-test PROPERTIES
PASS_REGULAR_EXPRESSION "renames `async_maybe_new_megaphone` to `new_megaphone`, which is already a function")
add_test(NAME strip-function-prefix-keyword-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}/function-keyword.toml
--out-dir ${CMAKE_CURRENT_BINARY_DIR}/function-keyword
WORKING_DIRECTORY ${BINDINGS_BUILD_DIR})
set_tests_properties(strip-function-prefix-keyword-test PROPERTIES
PASS_REGULAR_EXPRESSION "renames `oops_enum` to `enum`, which is reserved in C\\+\\+")

# The C backend: a C11 header over expected-style C++ bindings, built without exceptions.
set(C_BINDINGS_DIR ${BINDINGS_BUILD_DIR}/bindings-c)
set(C_BINDING_FILES ${C_BINDINGS_DIR}/capi.cpp ${C_BINDINGS_DIR}/capi_c.cpp)
Expand Down
2 changes: 2 additions & 0 deletions cpp-tests/function-collision.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[bindings.cpp]
strip_function_prefix = "async_maybe_"
2 changes: 2 additions & 0 deletions cpp-tests/function-keyword.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[bindings.cpp]
strip_function_prefix = "oops_"
1 change: 1 addition & 0 deletions cpp-tests/renamed.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[bindings.cpp]
error_style = "expected"
strip_type_prefix = "Capi"
strip_function_prefix = "capi_"
9 changes: 9 additions & 0 deletions cpp-tests/tests/expected/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ void renamed_types() {
CHECK(empty.error().to_string() == "invalid: empty name");
}

void renamed_functions() {
// `strip_function_prefix = "capi_"` names each free function without the prefix, async ones too.
CHECK(capi::checksum({1, 2, 3}) == 6);
CHECK(capi::fail(0));
CHECK(!capi::fail(1));
CHECK(capi::sum({1, 2, 3}).get() == 6);
}

void async_results() {
CHECK(futures::greet("C++") == "Hello, C++");
CHECK(futures::always_ready().get());
Expand Down Expand Up @@ -226,6 +234,7 @@ int main(int argc, char **argv) {
sync_errors();
error_display();
renamed_types();
renamed_functions();
async_results();
continuations();
cancellation();
Expand Down
9 changes: 9 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ NOTE: the `enum_style` option is separate for bindings and scaffolding generator
strip_type_prefix = "Foo"
```

- `strip_function_prefix` - the same for top-level functions. With `strip_function_prefix = "foo_"`,
`foo_connect` becomes `connect`. A name continues only after a lowercase letter, and methods
keep their names. Generation fails if a stripped name is already a function or a C++ keyword.

```toml
[bindings.cpp]
strip_function_prefix = "foo_"
```

### `error_style = "expected"`

A fallible function returns `uniffi::expected<T, E>`, and an async one returns
Expand Down
Loading