diff --git a/ffi/MIGRATE.md b/ffi/MIGRATE.md index 9d40b452b..245518f2d 100644 --- a/ffi/MIGRATE.md +++ b/ffi/MIGRATE.md @@ -2,6 +2,12 @@ ## Unreleased +- Each `pub` field of an object exports a setter, `_set_`, so a method + named `set_` 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. diff --git a/ffi/README.md b/ffi/README.md index f3e779d8e..1f77d6b74 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -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 | @@ -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 `_waker` and polls again when woken. @@ -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 @@ -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()`. diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 9b172f883..3f90514e6 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -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)); @@ -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)); @@ -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 {} {} {} {}", @@ -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::::new(200).value()); } diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 99454bb6c..b732e4908 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -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>>`; 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`; 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 diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index b8aac2ede..2facfceeb 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -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. diff --git a/ffi/moq/moq.c b/ffi/moq/moq.c index 6fa284343..7ee6bc365 100644 --- a/ffi/moq/moq.c +++ b/ffi/moq/moq.c @@ -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. */ @@ -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) { @@ -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); @@ -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); diff --git a/ffi/moq/moq.cpp b/ffi/moq/moq.cpp index 782c214e8..04fc78eb6 100644 --- a/ffi/moq/moq.cpp +++ b/ffi/moq/moq.cpp @@ -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. @@ -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(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")); diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index b31176418..8d6859add 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -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..]) + } + + /// 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)); @@ -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); diff --git a/ffi/src/census.rs b/ffi/src/census.rs index b80ad9baf..fca7ffedf 100644 --- a/ffi/src/census.rs +++ b/ffi/src/census.rs @@ -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.]` in the config unless it is /// the configured package; `at` locates a span. @@ -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::() - + records.iter().map(|r| r.methods.len()).sum::() - + enums.iter().map(|e| e.methods.len()).sum::(); + // 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::() + + records.iter().map(|r| items(&r.methods)).sum::() + + enums.iter().map(|e| items(&e.methods)).sum::(); let types = records.len() + enums.len() + objects.len(); let mut out = String::new(); diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 72be6a09e..5fe74f220 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1183,7 +1183,7 @@ impl<'tcx> Collector<'tcx> { Some(Decl::Object(index)) => { let (mut methods, traits) = self.methods(&site); if kind == DefKind::Struct { - methods.splice(0..0, self.getters(&site)); + methods.splice(0..0, self.accessors(&site)); } let object = &mut self.api.objects[index]; object.args = args; @@ -1196,10 +1196,11 @@ impl<'tcx> Collector<'tcx> { } } - /// A getter for each `pub` field of a struct exported as an object, returning a copy. - fn getters(&mut self, site: &Site<'tcx>) -> Vec { + /// A getter and a setter for each `pub` field of a struct exported as an object: the + /// getter returns a copy, and the setter assigns in place, as `x.field = value` does. + fn accessors(&mut self, site: &Site<'tcx>) -> Vec { let tcx = self.tcx; - let mut getters = Vec::new(); + let mut accessors = Vec::new(); let self_ty = self.site_ty(site); for field in &tcx.adt_def(site.key.def_id).non_enum_variant().fields { if !field.vis.is_public() { @@ -1230,26 +1231,60 @@ impl<'tcx> Collector<'tcx> { if ty.is_unit() { continue; } - // Read through `&self`, so returned as a copy, as a borrowed return is. + // Read through `&self`, so returned as a copy, as a borrowed return is, and + // written with a value C gives up, as an owned parameter is. let read = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); - match self.ty(read, Pos::Return) { - Ok(ty) => getters.push(Function { - path: [&site.path[..], &[name]].concat(), - span, - docs: docs(tcx, field.did), - receiver: Some(Receiver::Ref), - params: Vec::new(), - ok: ty, - err: None, - future: false, - eager: false, - access: Access::Field { shared }, - instance: None, - }), - Err(why) => self.refuse(if shared { &key } else { &shown }, "field", span, vec![why]), - } - } - getters + let mapped = { + let get = self.ty(read, Pos::Return); + // A handle outlives every call, so a reference it holds is `'static`, which + // C's borrow for the call is not. + let set = match self.ty(ty, Pos::Param) { + Ok(set) if matches!(set, Type::Ref(..)) || lends_inside(&set) => { + Err(why("'static borrow", ty.to_string())) + } + set => set, + }; + match (get, set) { + (Ok(get), Ok(set)) => Ok((get, set)), + (get, set) => { + let mut whys: Vec = get.err().into_iter().collect(); + // A type neither way maps is one reason, not two. + let new = set.err().filter(|set| { + !whys + .iter() + .any(|get| get.construct == set.construct && get.detail == set.detail) + }); + whys.extend(new); + Err(whys) + } + } + }; + match mapped { + Ok((get, set)) => { + let accessor = |receiver, params, ok, set| Function { + path: [&site.path[..], std::slice::from_ref(&name)].concat(), + span, + docs: docs(tcx, field.did), + receiver: Some(receiver), + params, + ok, + err: None, + future: false, + eager: false, + access: Access::Field { shared, set }, + instance: None, + }; + accessors.push(accessor(Receiver::Ref, Vec::new(), get, false)); + let value = Param { + name: "value".to_string(), + ty: set, + }; + accessors.push(accessor(Receiver::Mut, vec![value], Type::Unit, true)); + } + Err(why) => self.refuse(if shared { &key } else { &shown }, "field", span, why), + } + } + accessors } /// A type's inherent `pub` methods, from each impl that applies to it, and the std diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 1f4d8a595..792c8c106 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -976,7 +976,8 @@ impl Gen<'_> { } let call = match function.access { Access::Call => format!("{callee}({})", args.join(", ")), - Access::Field { .. } => format!("&({}).{}", args[0], function.name()), + Access::Field { set: false, .. } => format!("&({}).{}", args[0], function.name()), + Access::Field { set: true, .. } => format!("({}).{} = {}", args[0], function.name(), args[1]), Access::Const => callee, }; let body = stmts.join("\n\t"); diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 837f07430..4808659ec 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -157,7 +157,7 @@ pub struct Function { /// For a future, whether the call itself runs code, as a function that is not /// `async` returning one does: the export calls it at once, and polls what it returns. pub eager: bool, - /// What it reads: Rust's function, or a field or constant named as it is. + /// What it reads: Rust's function, a field it reads or writes, or a constant named as it is. pub access: Access, /// The instance it is, if a type parameter exports at several. pub instance: Option, @@ -179,10 +179,10 @@ pub struct Instance { pub enum Access { /// It calls the function. Call, - /// It reads a `pub` field of its receiver. `shared` when a method or constant of its - /// type takes its name, which its path then names, so the config names the field - /// `field@`, as rustdoc does. - Field { shared: bool }, + /// It reads a `pub` field of its receiver, or with `set` assigns it. `shared` when a + /// method or constant of its type takes its name, which its path then names, so the + /// config names the field `field@`, as rustdoc does. + Field { shared: bool, set: bool }, /// It reads a constant that is not a `bool` or integer. Const, } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 93cc2891e..c5b213fa2 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -211,6 +211,14 @@ static int script(void) { first = api_registry_first(registry); printf("edit %s %llu\n", edited ? "true" : "false", (unsigned long long)api_counter_get(first)); api_counter_free(first); + /* A setter moves an object in, as assignment does, leaving the handle to be freed. */ + api_counter *second = api_counter_new(str("second"), 3); + api_registry_set_first(registry, second); + api_counter_free(second); + first = api_registry_first(registry); + printf("set first %llu ", (unsigned long long)api_counter_get(first)); + print("", api_counter_name(first), "\n"); + api_counter_free(first); printf("walk %llu\n", (unsigned long long)api_walk(3, visit, NULL)); printf("offset %u\n", api_offset(seven, NULL, 3)); api_registry_free(registry); @@ -289,6 +297,18 @@ static int script(void) { print("stamp ", api_stamp_debug(read), "\n"); api_stamp_free(read); printf("sent %s\n", api_message_sent(message) ? "true" : "false"); + /* Setters assign in place: the bytes are copied in, and a `Copy` handle copied. */ + api_stamp *reset = api_stamp_from_millis(4000); + api_message_set_stamp(message, reset); + api_message_set_payload(message, str("edited")); + print("payload ", api_message_payload(message), "\n"); + read = api_message_stamp(message); + print("stamp ", api_stamp_debug(read), "\n"); + api_stamp_free(read); + printf("secs %llu\n", (unsigned long long)api_stamp_secs(reset)); + api_stamp_free(reset); + api_message_set_stamp(message, NULL); + printf("stamp %s\n", api_message_stamp(message) != NULL ? "true" : "false"); api_message_free(message); static const api_log_vtable print_log = {.free = log_free, .log = log_line}; @@ -450,6 +470,9 @@ static int script(void) { api_retry *retry = api_retry_new((api_option_u32){.some = true, .value = 5}); api_option_u32 limit = api_retry_limit_setting(retry); printf("retry %d %u %u %u\n", limit.some, limit.value, api_retry_limit(retry), api_retry_delay(retry)); + /* The renamed field's setter, named as its getter. */ + api_retry_set_limit_setting(retry, (api_option_u32){0}); + printf("retry %u\n", api_retry_limit(retry)); api_retry_free(retry); api_slot_u8 *slot = api_slot_u8_new(200); printf("slot %u\n", api_slot_u8_value(slot)); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index e2521af56..cd996af6c 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -164,6 +164,10 @@ int script() { return counter.edited() && counter.get() == 6; }); std::printf("edit %s %llu\n", yes(edited), ull(registry.first().get())); + // A setter moves an object in, as assignment does. + registry.set_first(api::counter::new_("second", 3)); + std::printf("set first %llu ", ull(registry.first().get())); + print("", registry.first().name(), "\n"); std::printf("walk %llu\n", ull(api::walk(3, [](const api::cursor &cursor) { return cursor.at() * 2; }))); std::printf("offset %u\n", api::offset([] { return 7u; }, 3)); @@ -223,6 +227,15 @@ int script() { print("payload ", message.payload(), "\n"); print("stamp ", message.stamp()->debug(), "\n"); std::printf("sent %s\n", yes(message.sent())); + // Setters assign in place: the bytes are copied in, and a `Copy` handle copied. + api::stamp reset = api::stamp::from_millis(4000); + message.set_stamp(&reset); + message.set_payload("edited"); + print("payload ", message.payload(), "\n"); + print("stamp ", message.stamp()->debug(), "\n"); + std::printf("secs %llu\n", ull(reset.secs())); + message.set_stamp(nullptr); + std::printf("stamp %s\n", yes(message.stamp().has_value())); } std::uint8_t levels[] = {1, 2, 3, 4}; @@ -373,6 +386,9 @@ int script() { api::retry retry = api::retry::new_(5u); std::optional limit = retry.limit_setting(); std::printf("retry %d %u %u %u\n", limit.has_value(), limit.value_or(0), retry.limit(), retry.delay()); + // The renamed field's setter, named as its getter. + retry.set_limit_setting(std::nullopt); + std::printf("retry %u\n", retry.limit()); std::printf("slot %u\n", api::slot_u8::new_(200).value()); return 0; } diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 3ecf4bb56..4169d7e54 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -101,6 +101,9 @@ fun script() { counter.edited() && counter.get() == 6uL } println("edit $edited ${registry.first.get()}") + // A setter moves an object in, as assignment does, closing its handle. + registry.setFirst(Counter.new("second", 3u)) + println("set first ${registry.first.get()} ${registry.first.name()}") println("walk ${walk(3u) { cursor -> cursor.at() * 2u }}") println("offset ${offset({ 7u }, 3u)}") @@ -143,6 +146,15 @@ fun script() { println("payload ${message.payload.decodeToString()}") println("stamp ${message.stamp!!.debug()}") println("sent ${message.sent()}") + // Setters assign in place: the bytes are copied in, and a `Copy` handle copied. + val reset = Stamp.fromMillis(4000u) + message.setStamp(reset) + message.setPayload("edited".encodeToByteArray()) + println("payload ${message.payload.decodeToString()}") + println("stamp ${message.stamp!!.debug()}") + println("secs ${reset.secs()}") + message.setStamp(null) + println("stamp ${message.stamp != null}") println("kept ${emit(PrintLog(), byteArrayOf(1, 2, 3, 4))}") Logger.new(PrintLog()).use { logger -> println("write ${logger.write("hi")}") } @@ -255,6 +267,9 @@ fun script() { val retry = Retry.new(5u) val limit = retry.limitSetting println("retry ${if (limit != null) 1 else 0} ${limit ?: 0u} ${retry.limit()} ${retry.delay()}") + // The renamed field's setter, named as its getter. + retry.setLimitSetting(null) + println("retry ${retry.limit()}") println("slot ${SlotU8.new(200u).value()}") } diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index 2b5000354..3858bf286 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -51,7 +51,6 @@ Every generator on the C ABI: - [Iterator and JSON arguments the exporter can't map yet](/quest/m1/ffi-export/instance-keys.md) - `IntoIterator` as a `Vec`, and `serde_json::Value` - [Fail CI on an instance not inferred](/quest/m1/ffi-export/inference-gate.md) - a gap in instance inference fails CI instead of sitting in the census - [moq-clock's C names once it moves into kio](/quest/m1/ffi-export/crates.md) - `moq_now` and `moq_origin` become the clock's, after moq moves it into `kio::clock` -- [Setters for an object's pub fields](/quest/m1/ffi-export/field-setters.md) - C fills in a session's config, as Rust assigns it - [Session config's foreign types](/quest/m1/ffi-export/foreign-types.md) - `Url`, `SocketAddr`, `PathBuf`, and `Vec` cross the C ABI - [Sessions on moq-tokio](/quest/m1/ffi-export/session-tokio.md) - bindings connect and accept with one call, the library running moq-tokio inside - [Sessions on sans-IO QUIC](/quest/m1/ffi-export/session-quic.md) - bindings move UDP datagrams and drive the session's poll themselves diff --git a/quest/m1/ffi-export/field-setters.md b/quest/m1/ffi-export/field-setters.md deleted file mode 100644 index 66e4a88ec..000000000 --- a/quest/m1/ffi-export/field-setters.md +++ /dev/null @@ -1,20 +0,0 @@ -# [M] Setters for an object's pub fields - -## Goal - -A binding sets each `pub` field of an exported object, as Rust assigns it, so C can fill -in moq-tokio's session config: `connect::Config::url`, `tls.insecure`, `tls.fingerprint`, -a server's `listen.bind`, and `tls.generate`. Proven from C in `moq/moq.c`. - -## Plan - -Found from C on 2026-10-27 in [#161](https://github.com/kixelated/rust2/pull/161): a -`pub` field of an object exports only a getter returning a copy. - -- An object is a handle to an `Arc`, so a setter needs a rule for a handle another - handle shares; pick one that matches Rust's aliasing rather than hiding a copy. -- A nested field (`tls.insecure`) is a field of a field; decide whether the setter reaches - through, or the binding gets, edits, and sets the whole value. -- Report the census before and after. - -Public API: the C names the exporter emits. diff --git a/quest/m1/ffi-export/session-tokio.md b/quest/m1/ffi-export/session-tokio.md index d21b44a6d..4c3ef192e 100644 --- a/quest/m1/ffi-export/session-tokio.md +++ b/quest/m1/ffi-export/session-tokio.md @@ -36,6 +36,5 @@ Public API: the C names moq's bindings get. ## Required - [Bump the moq pin past the fallback runtime](/quest/m1/moq-pin.md) - C reaches moq-tokio's fallback runtime -- [Setters for an object's pub fields](/quest/m1/ffi-export/field-setters.md) - C fills in the session config - [Session config's foreign types](/quest/m1/ffi-export/foreign-types.md) - `Url`, `SocketAddr`, `PathBuf`, and `Vec` cross the C ABI