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 ffi/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## Unreleased

- Each `pub` field of an object exports a setter, `<type>_set_<field>`, so a method
named `set_<field>` on the same type, such as `Limit::set_max` beside `pub max`,
clashes with it: give the method another name with a `rename`.
- A field is refused whole when its setter does not map, even if its getter did, such as
one holding a reference (`pub label: &'static str`), which a handle holds `'static` and
C's borrow for a call cannot fill: `exclude` it to leave it out.
- In `exclude` and `rename`, a path that a field shares with a method or constant of its
type, such as `Backoff::initial`, names only the method, as in rustdoc. Name the field
`field@Backoff::initial`: an `exclude` that left out both now needs both entries.
Expand Down
12 changes: 9 additions & 3 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export's, and adds nothing; another crate's type is refused.
| any other type, if `Send` | an object: an opaque handle to an `Arc`, freed with `_free` |
| a type whose only generic parameters are lifetimes, such as `Path<'a>` | an object holding its `'static` form |
| a generic type, at each instance it infers | that instance as any other type, with each method whose impl and own bounds it meets; any other instance is refused |
| a `pub` field of an object | a getter returning a copy |
| a `pub` field of an object | a getter returning a copy, and a setter assigning in place, as `x.field = value` does |
| a `pub` trait | a callback interface: a table of C functions and their data |
| a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce`, which no lifetime bound or return lets outlive the call | a C function and its `void *` data, which Rust calls only during the call; any other closure is refused |
| `fn` and inherent `pub` methods | functions named through their type |
Expand Down Expand Up @@ -110,7 +110,9 @@ refused, and the census counts why.
value that is not `Sync` is shared on one thread at a time, and held exclusively by a
future, which may be polled on any thread. A borrow Rust would
refuse at compile time aborts, naming the function, as does a null or moved-out handle:
there is no Rust caller to return an error to.
there is no Rust caller to return an error to. A setter borrows as `&mut T` and takes
its value as `T`, so it writes the value the handle holds, or the one Rust lent it,
while a getter's copy is C's own: a nested field is got, set, and set back.
- **Values** are copied in from the caller's memory, which Rust never frees, and lowered
into memory the caller frees once with the type's `_free`.
- **Futures** run no runtime: C polls with a `<prefix>_waker` and polls again when woken.
Expand Down Expand Up @@ -141,7 +143,9 @@ refused, and the census counts why.
name is registered, and two items claiming one is a compile error at both spans, fixed
by a `rename`: moq-net's `session::Stats` and `Session::stats` are both
`moq_session_stats`. So are a field and the method of its name, as moq-tokio's
`Backoff::initial`; `field@Backoff::initial` names the field.
`Backoff::initial`; `field@Backoff::initial` names the field. A field's setter is
named as its getter, with `set_` after its type's name: `moq_connect_config_set_tls`,
and `moq_backoff_set_initial_setting` once renamed.

An instance is named by its generic item's name, then each argument but those at their
defaults after the last that is not, so the instance at its defaults is named as the
Expand Down Expand Up @@ -210,6 +214,8 @@ kotlinx-coroutines. Each value crosses JNI as a scalar, a handle as a `Long`, by
- **Objects** are classes owning their handle, `AutoCloseable`, which `close()` frees once
no call holds it; a call after it throws. A `self` method, or passing the object by
value, closes it once the call returns. `Clone` is `clone()`, and `PartialEq` is `equals`.
A field is a `val`, and its setter a function, `setFirst(value)`, since setting an object
moves it in and closes its handle, which an assignment would hide.
- **Records** are data classes, compared by their fields, and **enums** an `enum class`,
or for one with data a sealed class of a data class per variant. `Display` is
`toString()`, `Debug` `debug()`, and `Default` a companion's `default()`.
Expand Down
19 changes: 17 additions & 2 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ fn main() {
counter.edited() && counter.get() == 6
});
println!("edit {edited} {}", registry.first.get());
// A setter moves an object in, as assignment does.
registry.first = Counter::new("second", 3);
println!("set first {} {}", registry.first.get(), registry.first.name());
println!("walk {}", api_lib::walk(3, |cursor| cursor.at() * 2));
println!("offset {}", api_lib::offset(|| 7, 3));

Expand Down Expand Up @@ -156,10 +159,19 @@ fn main() {
println!("secs {}", stamp.secs());
println!("later {}", Stamp::from_millis(3000).later(stamp));
println!("secs {}", stamp.secs());
let message = Message::new(Some(stamp), Bytes::from_static(b"body"));
let mut message = Message::new(Some(stamp), Bytes::from_static(b"body"));
println!("payload {}", String::from_utf8_lossy(&message.payload));
println!("stamp {:?}", message.stamp.unwrap());
println!("sent {}", message.sent());
// Setters assign in place: the bytes are copied in, and a `Copy` handle copied.
let reset = Stamp::from_millis(4000);
message.stamp = Some(reset);
message.payload = Bytes::from_static(b"edited");
println!("payload {}", String::from_utf8_lossy(&message.payload));
println!("stamp {:?}", message.stamp.unwrap());
println!("secs {}", reset.secs());
message.stamp = None;
println!("stamp {}", message.stamp.is_some());

println!("kept {}", api_lib::emit(Print, vec![1, 2, 3, 4]));
let logger = Logger::new(Box::new(Print));
Expand Down Expand Up @@ -293,7 +305,7 @@ fn main() {
drop(token);
println!("dropped {}", api_lib::dropped());

let retry = api_lib::Retry::new(Some(5));
let mut retry = api_lib::Retry::new(Some(5));
let limit = retry.limit;
println!(
"retry {} {} {} {}",
Expand All @@ -302,5 +314,8 @@ fn main() {
retry.limit(),
retry.delay()
);
// The renamed field's setter, named as its getter.
retry.limit = None;
println!("retry {}", retry.limit());
println!("slot {}", api_lib::Slot::<u8>::new(200).value());
}
13 changes: 8 additions & 5 deletions ffi/fixtures/reject/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,15 @@ fixtures/reject/src/lib.rs:246:9: rust2-ffi: cannot export use `HashSet`: re-exp
fixtures/reject/src/lib.rs:249:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:264:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C
fixtures/reject/src/lib.rs:256:2: note: field `reject_fixture::Limit::max` is here
fixtures/reject/src/lib.rs:269:2: rust2-ffi: fn `reject_fixture::Limit::set_max` and setter of field `reject_fixture::Limit::max` are both `reject_limit_set_max` in C
fixtures/reject/src/lib.rs:256:2: note: setter of field `reject_fixture::Limit::max` is here
fixtures/reject/src/lib.rs:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:270:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:275:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:280:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:286:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:292:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:278:2: rust2-ffi: cannot export field `Tag::label`: 'static borrow `&'static str`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:288:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:293:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:298:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:304:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:310:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option<std::boxed::Box<std::option::Option<u32>>>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:40:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box<Opaque>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:45:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out
Expand Down
18 changes: 18 additions & 0 deletions ffi/fixtures/reject/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,24 @@ impl Limit {
pub fn max(&self) -> u32 {
self.max.max(1)
}

/// The name of `max`'s setter too.
pub fn set_max(&mut self, max: u32) {
self.max = max;
}
}

/// A field holding a `'static` borrow, which a setter cannot take from C's borrow for
/// the call.
#[non_exhaustive]
pub struct Tag {
pub label: &'static str,
}

impl Tag {
pub fn new() -> Self {
Self { label: "tag" }
}
}

/// A closure kept past the call, as a `'static` bound lets it be.
Expand Down
43 changes: 42 additions & 1 deletion ffi/moq/moq.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/* moq's exported C API against the real library: a broadcast's track, published and
* subscribed to in one process, with every read polled as a future, and an origin.
* moq-pattern, moq-clock, moq-tokio, hang, and moq-mux export into the same library, and
* each names the others' types, and the catalog is lent to C for a call.
* each names the others' types, the catalog is lent to C for a call, and a session's
* config is filled in field by field.
*
* It needs no runtime: the waker counts wakes, and each poll that must wait is polled
* again after the write that wakes it. */
Expand Down Expand Up @@ -50,6 +51,22 @@ static void lists_state(void *data, moq_hang_catalog_extra *catalog) {
moq_buf_free(json);
}

/* Moves the stats track in data into the lent catalog, in place. */
static void sets_stats(void *data, moq_hang_catalog_extra *catalog) {
moq_hang_catalog_extra_set_stats(catalog, data);
}

/* Whether the lent catalog lists its stats track as `stats`: counts it in data. */
static void lists_stats(void *data, moq_hang_catalog_extra *catalog) {
moq_catalog_stats *stats = moq_hang_catalog_extra_stats(catalog);
moq_catalog_stats *want = moq_catalog_stats_new(str("stats"));
if (stats != NULL && moq_catalog_stats_eq(stats, want)) {
(*(int *)data)++;
}
moq_catalog_stats_free(want);
moq_catalog_stats_free(stats);
}

static int wakes = 0;

static void wake(void *data) {
Expand Down Expand Up @@ -299,6 +316,13 @@ int main(void) {
int listed_state = 0;
CHECK(moq_catalog_producer_extra_mutate(catalog, lists_state, &listed_state, &mux_err));
CHECK(listed_state == 1);
/* A field of the lent catalog, set in place: the next call reads it. */
moq_catalog_stats *stats = moq_catalog_stats_new(str("stats"));
CHECK(moq_catalog_producer_extra_mutate(catalog, sets_stats, stats, &mux_err));
moq_catalog_stats_free(stats);
int listed_stats = 0;
CHECK(moq_catalog_producer_extra_mutate(catalog, lists_stats, &listed_stats, &mux_err));
CHECK(listed_stats == 1);
moq_binary_snapshot_free(snapshot);
moq_catalog_producer_extra_free(catalog);
moq_broadcast_producer_free(publisher);
Expand All @@ -308,6 +332,23 @@ int main(void) {
CHECK(moq_connect_error_is_auth(&unauthorized));
CHECK(is(moq_connect_error_to_string(&unauthorized), "unauthorized"));

/* A session's config, filled in as Rust assigns it, and a nested field by getting a copy,
* editing it, and setting it back. */
moq_connect_config *connect = moq_connect_config_default();
moq_tls_connect *tls = moq_connect_config_tls(connect);
moq_tls_connect_set_insecure(tls, (moq_option_bool){.some = true, .value = true});
moq_tls_connect_set_host_name(tls, str("relay.example"));
moq_connect_config_set_tls(connect, tls);
moq_tls_connect_free(tls);
moq_connect_config_set_implementation(connect, str("moq.c"));
tls = moq_connect_config_tls(connect);
moq_option_bool insecure = moq_tls_connect_insecure(tls);
CHECK(insecure.some && insecure.value);
CHECK(is(moq_tls_connect_host_name(tls), "relay.example"));
moq_tls_connect_free(tls);
CHECK(is(moq_connect_config_implementation(connect), "moq.c"));
moq_connect_config_free(connect);

/* A backoff's fields are settings left unset, and the methods of their names resolve them. */
moq_backoff *backoff = moq_backoff_default();
CHECK(moq_backoff_initial_setting(backoff) == NULL);
Expand Down
16 changes: 15 additions & 1 deletion ffi/moq/moq.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// moq.c's script through the generated C++ header: a broadcast's track, published and
// subscribed to in one process, with every read polled as a future, and an origin, with
// moq-pattern, moq-clock, moq-tokio, hang, and moq-mux exported into the same library,
// and the catalog lent to C++ for a call.
// the catalog lent to C++ for a call, and a session's config filled in field by field.
//
// It needs no runtime: the waker counts wakes, and each poll that must wait is polled
// again after the write that wakes it.
Expand Down Expand Up @@ -197,6 +197,20 @@ int main() {
CHECK(listed_state == 1);
}

// A session's config, filled in as Rust assigns it, and a nested field by getting a copy,
// editing it, and setting it back.
{
moq::connect_config connect = moq::connect_config::default_();
moq::tls_connect tls = connect.tls();
tls.set_insecure(true);
tls.set_host_name("relay.example");
connect.set_tls(std::move(tls));
connect.set_implementation("moq.cpp");
CHECK(connect.tls().insecure() == std::optional<bool>(true));
CHECK(is(*connect.tls().host_name(), "relay.example"));
CHECK(is(*connect.implementation(), "moq.cpp"));
}

// moq-tokio's terminal connect errors, which moq-net's `Error` shares no names with.
CHECK(moq::connect_error_is_auth(moq::connect_error::unauthorized));
CHECK(is(moq::connect_error_to_string(moq::connect_error::unauthorized), "unauthorized"));
Expand Down
53 changes: 32 additions & 21 deletions ffi/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,35 +230,45 @@ impl<'a> Abi<'a> {

/// A function's C name: a method's through its type's, unless renamed itself, then
/// each argument of the instance it is. A field is renamed by `field@` and its path,
/// or by its path unless a method or constant takes it.
/// or by its path unless a method or constant takes it, and its setter is named as it
/// is, with `set_` after its type's name.
fn function_name(&self, function: &Function, owner: Option<&Ty>) -> String {
let path = function.path.join("::");
let shared = match function.access {
Access::Field { shared } => {
let key = format!("field@{path}");
if let Some(renamed) = self.rename.get(&key) {
self.renamed.borrow_mut().insert(key);
return format!("{}_{renamed}", self.prefix);
}
shared
let owner_name = match owner {
Some(Ty::Struct(owner) | Ty::Enum(owner) | Ty::Handle { name: owner, .. }) => Some(owner.as_str()),
_ => None,
};
let Access::Field { shared, set } = function.access else {
return self.method_name(function, owner_name, false);
};
let key = format!("field@{}", function.path.join("::"));
let name = match self.rename.get(&key) {
Some(renamed) => {
self.renamed.borrow_mut().insert(key);
format!("{}_{renamed}", self.prefix)
}
_ => false,
None => self.method_name(function, owner_name, shared),
};
if !set {
return name;
}
// A rename need not start with the type's name, but always with the prefix.
let at = owner_name
.filter(|owner| name.starts_with(&format!("{owner}_")))
.unwrap_or(&self.prefix);
format!("{at}_set_{}", &name[at.len() + 1..])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Document setter-name collisions in the migration guide

For an existing exported object with a public field x and a method set_x, the new setter claims the method's C name and makes a previously valid export fail until the method is renamed in the config. The new reject fixture confirms this collision, so the public API change is not purely additive. Add an entry under ## Unreleased in ffi/MIGRATE.md describing the collision and the required rename; the commit description alone does not satisfy the repository's breaking-change requirement.

AGENTS.md reference: AGENTS.md:L47-L47

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 410fb74: added an ## Unreleased entry to ffi/MIGRATE.md, retitled the PR feat(ffi)!, and marked the Impact bullet breaking.

(Written by Claude Opus 5.5)

}

/// A function's C name through its type's, unless renamed by its path and no method
/// or constant `shared` its name, then each argument of the instance it is.
fn method_name(&self, function: &Function, owner: Option<&str>, shared: bool) -> String {
let path = function.path.join("::");
let name = match owner {
Some(Ty::Struct(owner) | Ty::Enum(owner) | Ty::Handle { name: owner, .. })
if shared || !self.rename.contains_key(&path) =>
{
format!("{owner}_{}", snake(function.name()))
}
Some(owner) if shared || !self.rename.contains_key(&path) => format!("{owner}_{}", snake(function.name())),
_ => self.name(&function.path),
};
let Some(instance) = &function.instance else {
return name;
};
let owner = match owner {
Some(Ty::Struct(owner) | Ty::Enum(owner) | Ty::Handle { name: owner, .. }) => Some(owner.as_str()),
_ => None,
};
self.instance(true, name, &instance.named, || {
let api = self.api;
let records = (0..api.records.len()).map(|i| (Some(self.record(i)), &api.records[i].methods));
Expand Down Expand Up @@ -575,7 +585,8 @@ impl<'a> Abi<'a> {
for (function, owner) in functions {
let export = self.export(function, owner.as_ref());
let what = match function.access {
Access::Field { .. } => format!("field `{}`", function.path.join("::")),
Access::Field { set: false, .. } => format!("field `{}`", function.path.join("::")),
Access::Field { set: true, .. } => format!("setter of field `{}`", function.path.join("::")),
_ => format!("fn `{}`", function.path.join("::")),
};
self.claim(export.call.name.clone(), what.clone(), function.span);
Expand Down
14 changes: 10 additions & 4 deletions ffi/src/census.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use rustc_span::Span;

use crate::abi::Clash;
use crate::collect::{Refusal, Report};
use crate::ir::Api;
use crate::ir::{Access, Api, Function};

/// The census of one export as Markdown, `[crates.<package>]` in the config unless it is
/// the configured package; `at` locates a span.
Expand All @@ -21,9 +21,15 @@ pub fn render(api: &Api, collected: &Report, top: bool, clashes: &[Clash], at: &
let callbacks = api.callbacks.iter().filter(|c| ours(&c.path)).count();
let constants = api.constants.iter().filter(|c| ours(&c.path)).count();
let refused = |kinds: &[&str]| collected.refusals.iter().filter(|r| kinds.contains(&r.kind)).count();
let methods: usize = objects.iter().map(|o| o.methods.len()).sum::<usize>()
+ records.iter().map(|r| r.methods.len()).sum::<usize>()
+ enums.iter().map(|e| e.methods.len()).sum::<usize>();
// A field counts once, by its getter, though it exports a setter too.
let items = |methods: &[Function]| {
(methods.iter())
.filter(|f| !matches!(f.access, Access::Field { set: true, .. }))
.count()
};
let methods: usize = objects.iter().map(|o| items(&o.methods)).sum::<usize>()
+ records.iter().map(|r| items(&r.methods)).sum::<usize>()
+ enums.iter().map(|e| items(&e.methods)).sum::<usize>();
let types = records.len() + enums.len() + objects.len();

let mut out = String::new();
Expand Down
Loading