From fbd42d23f9c215c59464c08c2a705a03a3a79a08 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:46:44 -0800 Subject: [PATCH 1/7] chore(quest): claim quest/m1/ffi-export/copy-values.md Quest-Claim: 0b2d5c60a2d501fa From 33c2c759144e377edb62018dbf21354d111f651d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:05:53 -0800 Subject: [PATCH 2/7] feat(ffi)!: a Copy type changed in place crosses by value Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 18 ++++++- ffi/fixtures/api/src/lib.rs | 63 +++++++++++++++++++++-- ffi/fixtures/reject/expected.txt | 2 + ffi/fixtures/reject/src/lib.rs | 22 ++++++++ ffi/src/abi.rs | 68 ++++++++++++++++++++++++- ffi/src/c.rs | 5 +- ffi/src/collect.rs | 55 ++++++++++---------- ffi/src/cpp.rs | 19 ++++--- ffi/src/dart.rs | 22 +++++++- ffi/src/glue.rs | 26 +++++++--- ffi/src/go.rs | 32 +++++++++--- ffi/src/ir.rs | 8 +-- ffi/src/kotlin.rs | 20 ++++++-- ffi/src/python.rs | 16 +++++- ffi/src/swift.rs | 7 ++- ffi/tests/api.c | 47 ++++++++++++----- ffi/tests/api.cpp | 23 ++++++++- ffi/tests/api.dart | 26 ++++++++-- ffi/tests/api.go | 28 +++++++--- ffi/tests/api.kt | 28 ++++++++-- ffi/tests/api.py | 22 ++++++-- ffi/tests/api.swift | 20 +++++++- 22 files changed, 478 insertions(+), 99 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index e4c2d36e2..822fef4bb 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -330,12 +330,28 @@ fn main() { let berth = api::Berth::new(Some(4)); println!("berth {:?} {:?}", berth.at(), api::Berth::new(None).at()); - // A `Copy` type changed in place is a handle, which a call taking it by value copies. + // A `Copy` type changed in place is a value, whose change reaches only the copy changed. let mut score = api::Score::of(2); let step = api::Score::of(3); score.add(step); score.add(step); println!("score {} {} {}", score.count(), step.doubled().count(), step.count()); + let mut copy = score; + let taken = copy.take(); + println!("taken {taken} {} {}", copy.count(), score.count()); + let mut other = step; + let before = copy.absorb(&mut other); + println!("absorbed {} {} {} {} {}", before.0, before.1, copy.count(), other.count(), step.count()); + let mut hits = api::Hits::of(1, 2); + let kept = hits; + hits.add(api::Hits::of(10, 20)); + hits.hits = 7; + println!("hits {} {} {} {} {}", hits.hits, hits.misses, kept.hits, kept.misses, hits == kept); + let mut extent = api::Extent::new(5, 3); + let start = extent; + let old = extent.slide(10); + extent.start += 1; + println!("extent {old} {} {} {} {}", extent.start, extent.end(), start.start, start.end()); let weighted = api::Weighted { score: step, weight: 4 }; println!( "weighted {} {}", diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 119a8842b..2467e8265 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1285,9 +1285,8 @@ impl Berth { } } -/// A running count, as moq's `stats::Traffic`: `Copy` with private fields, but changed in -/// place through `&mut self`, which a copy could not write back, so a handle. A call taking -/// one by value copies it out of its handle, leaving the caller's as it was. +/// A running count, as moq's `stats::Traffic`: `Copy` with private fields, changed in place +/// through `&mut self`, so a value whose every copy changes alone. #[derive(Clone, Copy, Debug)] pub struct Score { count: u64, @@ -1313,6 +1312,64 @@ impl Score { count: self.count.wrapping_mul(2), } } + + /// The count, leaving zero in its place. + pub fn take(&mut self) -> u64 { + std::mem::take(&mut self.count) + } + + /// Moves `other`'s count into this one, as `&mut` of a value Rust writes back too, and + /// returns both counts before, as a tuple. + pub fn absorb(&mut self, other: &mut Score) -> (u64, u64) { + let before = (self.count, other.count); + self.count = self.count.wrapping_add(std::mem::take(&mut other.count)); + before + } +} + +/// A tally, as moq's `stats::Presence`: `Copy`, its fields `pub` but `#[non_exhaustive]`, +/// so a value whose fields read and write through accessors. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct Hits { + pub hits: u64, + pub misses: u32, +} + +impl Hits { + pub fn of(hits: u64, misses: u32) -> Self { + Self { hits, misses } + } + + /// Adds `other` into this one, as moq's `add` does. + pub fn add(&mut self, other: Hits) { + self.hits = self.hits.wrapping_add(other.hits); + self.misses = self.misses.wrapping_add(other.misses); + } +} + +/// A span whose `pub` start sits beside a private length, which no record could hold. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Extent { + pub start: u64, + len: u32, +} + +impl Extent { + pub fn new(start: u64, len: u32) -> Self { + Self { start, len } + } + + pub fn end(&self) -> u64 { + self.start.wrapping_add(u64::from(self.len)) + } + + /// Moves the window `by` later, returning its old start. + pub fn slide(&mut self, by: u64) -> u64 { + let start = self.start; + self.start = start.wrapping_add(by); + start + } } /// A score and its weight: a record holding a `Copy` handle, copied in and out. diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index ac7449ee9..b57867143 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -33,6 +33,8 @@ fixtures/reject/src/lib.rs:1182:1: rust2-ffi: cannot export fn `hidden_items`: o fixtures/reject/src/lib.rs:1187:1: rust2-ffi: cannot export fn `hidden_option`: opaque type `impl std::clone::Clone`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1192:1: rust2-ffi: cannot export fn `boxed_bytes`: boxed slice of bytes `std::boxed::Box<[u8]>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:11:1: rust2-ffi: cannot export fn `map`: foreign type `std::collections::HashMap`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1207:2: rust2-ffi: cannot export method `Counter::try_bump`: `&mut self` of a value returning a Result; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1212:2: rust2-ffi: cannot export method `Counter::bump_later`: `&mut self` of a value in a future; exclude it in the config to leave it out fixtures/reject/src/lib.rs:122:1: rust2-ffi: cannot export fn `parse_later`: returned object that borrows `impl std::future::Future>>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:136:1: rust2-ffi: cannot export fn `poll_ready`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:153:2: rust2-ffi: cannot export method `Link::session`: borrowed return that is not Clone `tls::held::Handoff`; 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 a9791f914..cfe29af88 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1192,3 +1192,25 @@ pub fn hidden_option() -> impl Clone { pub fn boxed_bytes(bytes: Box<[u8]>) -> usize { bytes.len() } + +/// A `Copy` count, a value, whose change a raised error or a future would lose. +#[derive(Clone, Copy)] +pub struct Counter { + count: u8, +} + +impl Counter { + pub fn zero() -> Self { + Self { count: 0 } + } + + pub fn try_bump(&mut self) -> Result { + self.count = self.count.checked_add(1).ok_or("overflow")?; + Ok(self.count) + } + + pub fn bump_later(&mut self) -> impl std::future::Future + use<> { + self.count += 1; + std::future::ready(self.count) + } +} diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index f437cfd86..d3a26cbfb 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -92,6 +92,8 @@ pub enum Ty { Out(Box), /// A pointer the callee only reads through: a value's receiver. In(Box), + /// A pointer the callee reads and writes back through: a value's `&mut self`. + InOut(Box), /// A function lent for the call, taking its data first: what it takes and returns. Fn(Vec, Box), /// The data a lent function takes, which Rust only passes back to it. @@ -711,7 +713,9 @@ impl<'a> Abi<'a> { && (0..self.api.objects.len()) .any(|i| self.api.objects[i].copy && &self.object(i) == name)), }, - // A value's receiver is read through a pointer, and never changed. + // A value's receiver is read through a pointer, and written back in place for + // `&mut self`. + value if receiver == Receiver::Mut => Ty::InOut(Box::new(value.clone())), value => Ty::In(Box::new(value.clone())), }; params.push(("self".to_string(), ty)); @@ -845,6 +849,68 @@ impl<'a> Abi<'a> { out } + /// A value's `&mut self` method as a language whose values are immutable calls it: + /// through `&self`, returning the value as the call left it, before Rust's own return + /// or each element of its tuple; and the Rust function `back_::call`, of that + /// function's C signature, that calls the C one with a copy and hands the copy back. + /// `None` for any other function. + pub fn handed_back(&self, function: &Function, owner: &Ty, owner_ty: &Type) -> Option<(Function, String)> { + if function.receiver != Some(Receiver::Mut) || matches!(owner, Ty::Handle { .. }) { + return None; + } + // `written_back` in collect.rs refuses a future's and a `Result`'s. + assert!(!function.future && function.err.is_none(), "a value's `&mut self` returns a plain value"); + let real = self.export(function, Some(owner)); + let returned = match &function.ok { + Type::Unit => Vec::new(), + Type::Tuple(elements) => elements.clone(), + ok => vec![ok.clone()], + }; + let back = Function { + receiver: Some(Receiver::Ref), + ok: match returned.is_empty() { + true => owner_ty.clone(), + false => Type::Tuple([vec![owner_ty.clone()], returned].concat()), + }, + ..function.clone() + }; + let sig = self.export(&back, Some(owner)).call; + let params: Vec = (sig.params.iter().enumerate()) + .map(|(n, (_, ty))| format!("p{n}: {}", crate::glue::rs(ty))) + .collect(); + // What both take after `self`, then the outs the real one writes its tuple through, + // which the other's take after the value's own. + let elements = match &function.ok { + Type::Tuple(elements) => elements.len(), + _ => 0, + }; + let tuple = elements > 0; + let lead = real.call.params.len() - 1 - elements; + let mut args = vec!["&mut v".to_string()]; + args.extend((1..=lead).map(|n| format!("p{n}"))); + if tuple { + args.extend((lead + 2..sig.params.len()).map(|n| format!("p{n}"))); + } + let call = format!("crate::{}({})", real.call.name, args.join(", ")); + let body = match (&function.ok, tuple) { + (Type::Unit, _) => format!("{call};\n\t\t\tv"), + (_, true) => format!("{call};\n\t\t\tp{}.write(v);", lead + 1), + (_, false) => format!( + "let r = {call};\n\t\t\tp{}.write(v);\n\t\t\tp{}.write(r);", + lead + 1, + lead + 2 + ), + }; + // In a module of its own, which names the C types as the crate's root does. + let shim = format!( + "mod back_{} {{\n\tuse crate::*;\n\n\tpub unsafe fn call({}) -> {} {{\n\t\tunsafe {{\n\t\t\tlet mut v = *p0;\n\t\t\t{body}\n\t\t}}\n\t}}\n}}\n\n", + real.call.name, + params.join(", "), + crate::glue::rs(&sig.ret), + ); + Some((back, shim)) + } + fn claim(&mut self, name: String, what: String, span: Span, owner: Option) { self.claims.push(Claim { name, diff --git a/ffi/src/c.rs b/ffi/src/c.rs index 840680c41..ea74e0601 100644 --- a/ffi/src/c.rs +++ b/ffi/src/c.rs @@ -440,6 +440,9 @@ impl Header<'_> { moved.join(" and ") )); } + if matches!(export.call.params.first(), Some((_, Ty::InOut(_)))) { + docs.push_str("\n\nRust writes what the call left in `self` back in place."); + } for param in function.params.iter().filter(|p| p.ty.written()) { let name = abi::escape(¶m.name); docs.push_str(&format!( @@ -528,7 +531,7 @@ pub fn decl(abi: &Abi<'_>, ty: &Ty, name: &str) -> String { Ty::ForeignFuture => space(&abi.rt("foreign_future")), Ty::ForeignReader => space(&abi.rt("foreign_reader")), Ty::Poll => space(&abi.rt("poll")), - Ty::Out(inner) => decl(abi, inner, &format!("*{name}")), + Ty::Out(inner) | Ty::InOut(inner) => decl(abi, inner, &format!("*{name}")), Ty::In(inner) => format!("const {}", decl(abi, inner, &format!("*{name}"))), Ty::Fn(params, ret) => { let params: Vec = std::iter::once("void *data".to_string()) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 1c5500595..739c0e50f 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1962,12 +1962,12 @@ impl<'tcx> Collector<'tcx> { } /// An object, if the type can move across threads, or if it is also `Copy`, a value C - /// holds as its bytes, unless C changes it in place, which a copy could not write back, - /// or which of its bytes it initializes depends on its value, so its padding could not - /// be zeroed. Shared borrows of an object that is not `Sync` are exclusive. + /// holds as its bytes, unless which of its bytes it initializes depends on its value, so + /// its padding could not be zeroed. Shared borrows of an object that is not `Sync` are + /// exclusive. fn object(&self, site: &Site<'tcx>) -> Decl { let (tcx, ty, def_id) = (self.tcx, self.site_ty(site), site.key.def_id); - let copy = implements(tcx, ty, def_id, sym::Copy) && !self.changed(def_id) && padding(tcx, ty).is_some(); + let copy = implements(tcx, ty, def_id, sym::Copy) && padding(tcx, ty).is_some(); if self.orphans.contains(&site.key) { let construct = match copy { true => "value no export returns", @@ -1982,25 +1982,6 @@ impl<'tcx> Collector<'tcx> { } } - /// Whether C may change the type `def_id` in place: through a `pub` field's setter, or - /// an inherent `pub` method taking `&mut self`. - fn changed(&self, def_id: DefId) -> bool { - let tcx = self.tcx; - let fields = matches!(tcx.def_kind(def_id), DefKind::Struct) - && tcx.adt_def(def_id).all_fields().any(|field| field.vis.is_public()); - fields - || (tcx.inherent_impls(def_id).iter()).any(|&imp| { - (tcx.associated_items(imp).in_definition_order()).any(|item| { - item.is_method() - && tcx.visibility(item.def_id).is_public() - && matches!( - tcx.fn_sig(item.def_id).skip_binder().inputs().skip_binder().first().map(|input| input.kind()), - Some(ty::Ref(_, _, mutability)) if mutability.is_mut() - ) - }) - }) - } - /// The objects C can never hold a handle to: no export it can call returns one. fn orphans(&self) -> Vec> { let api = &self.api; @@ -2262,9 +2243,12 @@ impl<'tcx> Collector<'tcx> { e.methods = methods; e.traits = traits; } - // One with no `pub` field, nor a `&mut self` method, as `object` decides. Some(Decl::Value(index)) => { - let (methods, traits) = self.methods(&site); + let (mut methods, traits) = self.methods(&site); + if kind == DefKind::Struct { + methods.splice(0..0, self.accessors(&site)); + } + let methods = self.written_back(methods); let record = &mut self.api.records[index]; record.args = args; record.methods = methods; @@ -2422,8 +2406,9 @@ impl<'tcx> Collector<'tcx> { (!self.exclude(&key) && (shared || !self.exclude(shown))).then_some((key, shared)) } - /// 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. + /// A getter and a setter for each `pub` field of a struct exported as an object or an + /// opaque value: 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 accessors = Vec::new(); @@ -2530,6 +2515,22 @@ impl<'tcx> Collector<'tcx> { kept } + /// An opaque value's methods, refusing each through `&mut self` whose change Rust could + /// not hand back with what it returns: a future's, which outlives the call, and a + /// `Result`'s, whose error a language raising it would lose the change with. + fn written_back(&mut self, methods: Vec) -> Vec { + let (refused, kept): (Vec, Vec) = (methods.into_iter()) + .partition(|m| m.receiver == Some(Receiver::Mut) && (m.future || m.err.is_some())); + for m in refused { + let construct = match m.future { + true => "`&mut self` of a value in a future", + false => "`&mut self` of a value returning a Result", + }; + self.refuse(&m.shown, "method", m.span, vec![why(construct, "")]); + } + kept + } + fn methods(&mut self, site: &Site<'tcx>) -> (Vec, Traits) { let tcx = self.tcx; let def_id = site.key.def_id; diff --git a/ffi/src/cpp.rs b/ffi/src/cpp.rs index 4321a8973..857c42915 100644 --- a/ffi/src/cpp.rs +++ b/ffi/src/cpp.rs @@ -1546,14 +1546,21 @@ impl<'a> Header<'a> { } } let outs: Vec<(String, Ty)> = c_params.cloned().collect(); - // Each value passed for `&mut` takes what Rust wrote back, on every path. - let writes: Vec = (function.params.iter().zip(&names)) - .filter(|(param, _)| param.ty.written()) - .map(|(param, name)| { + // Each value passed for `&mut` takes what Rust wrote back, on every path, as does a + // value's own `&mut self`, which Rust wrote back in place. + let mut writes: Vec = match export.call.params.first() { + Some((_, Ty::InOut(_))) => { + let ty = record(abi, owner_c.as_deref().expect("a member method has its record")); + vec![format!("*this = {};", self.lift(&ty, "c_self_"))] + } + _ => Vec::new(), + }; + writes.extend((function.params.iter().zip(&names)).filter(|(param, _)| param.ty.written()).map( + |(param, name)| { let out = Abi::written(function, &abi::escape(¶m.name)); format!("{name} = {};", self.lift(param.ty.base(), &format!("c_{out}_"))) - }) - .collect(); + }, + )); for (name, _) in &outs { args.push(format!("&c_{name}_")); } diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 1eb2014f8..077460665 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -88,6 +88,7 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result { on: On, /// The namespace of the glue's C names, apart from the export's. space: String, + /// The C functions of a value's `&mut self` methods, which a call reaches through the + /// glue's `back_`, handing back the value as the call left it. + handed: BTreeSet, } impl<'a> Gen<'a> { @@ -794,12 +798,15 @@ impl<'a> Gen<'a> { .map(|(n, (_, ty))| format!(", p{n}: {}", rs(ty))) .collect(); let args: Vec = (0..call.params.len()).map(|n| format!("p{n}")).collect(); + let callee = match self.handed.contains(&call.name) { + true => format!("back_{}::call", call.name), + false => format!("crate::{}", call.name), + }; let _ = write!( self.glue, - "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {name}(home: *const c_void{}) -> {} {{\n\tlet home = unsafe {{ &*home.cast::() }};\n\tunsafe {{ home.serve(move || crate::{}({})) }}\n}}\n\n", + "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {name}(home: *const c_void{}) -> {} {{\n\tlet home = unsafe {{ &*home.cast::() }};\n\tunsafe {{ home.serve(move || {callee}({})) }}\n}}\n\n", decls.concat(), rs(&call.ret), - call.name, args.join(", ") ); let native = self.native_fn(&name, params, call.ret.clone()); @@ -2006,6 +2013,17 @@ impl<'a> Gen<'a> { ) -> Option<(String, String)> { let abi = self.abi; let _p = abi.prefix.clone(); + // A value is immutable in Dart, so its `&mut self` method returns it as the call left + // it, through a function of the glue's that hands back a copy. + let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); + let function = match &handed { + Some((back, shim)) => { + self.glue.push_str(shim); + self.handed.insert(abi.export(back, owner).call.name); + back + } + None => function, + }; let export = abi.export(function, owner); let c_name = export.call.name.clone(); let owner_c = match owner { diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 209255496..9264d9174 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -111,6 +111,7 @@ pub fn rs(ty: &Ty) -> String { Ty::ForeignReader => "rt::ForeignReader".to_string(), Ty::Out(inner) => format!("*mut {}", rs(inner)), Ty::In(inner) => format!("*const {}", rs(inner)), + Ty::InOut(inner) => format!("*mut {}", rs(inner)), Ty::Fn(params, ret) => { let params: Vec = std::iter::once("*mut ::std::ffi::c_void".to_string()) .chain(params.iter().map(rs)) @@ -1777,14 +1778,20 @@ impl Gen<'_> { if function.holds && *receiver != Receiver::Owned { held.push("a_self".to_string()); } - // Read through a pointer, so the caller keeps it. + // Read through a pointer, so the caller keeps it, and for `&mut self` + // written back through it once the call returns. + let binding = match receiver { + Receiver::Mut => "let mut", + _ => "let", + }; stmts.push(format!( - "let a_self = {};", + "{binding} a_self = {};", self.lift(value, "unsafe { *this }", "false") )); args.push(match receiver { Receiver::Owned => "a_self".to_string(), - _ => "&a_self".to_string(), + Receiver::Ref => "&a_self".to_string(), + Receiver::Mut => "&mut a_self".to_string(), }); } } @@ -1887,8 +1894,15 @@ impl Gen<'_> { args.insert(usize::from(receiver_ty.is_some()) + at, arg); } // Rust writes back what the call left in each value C passed for `&mut`, on every - // path, errors included. - let writes: String = (function.params.iter().enumerate()) + // path, errors included, and in a value's `&mut self`, in place. + let mut writes: String = match &receiver_ty { + Some(((_, value), Receiver::Mut)) if !matches!(value, Type::Object(_)) => format!( + "\n\tunsafe {{ this.write({}) }};", + self.lower(value, "a_self") + ), + _ => String::new(), + }; + writes += &(function.params.iter().enumerate()) .filter(|(_, param)| param.ty.written()) .map(|(n, param)| { let Type::Ref(_, inner) = ¶m.ty else { @@ -1901,7 +1915,7 @@ impl Gen<'_> { self.lower(inner, &format!("a{n}")) ) }) - .collect(); + .collect::(); let mut callee = match &owner { Some((_, owner_type)) => format!("<{}>::{}", self.rust(owner_type), function.name()), None => self.path(&function.path), diff --git a/ffi/src/go.rs b/ffi/src/go.rs index f8dbc2862..c9cd920a0 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2308,7 +2308,12 @@ impl<'a> Gen<'a> { let (_, c) = c_params.next().expect("a method has its receiver"); let ty = owner_ty.expect("a method has its type").clone(); let go = self.go(&ty); - go_receiver = Some(format!("self {go}")); + // A value's `&mut self` is a pointer receiver, which Rust writes back through. + let pointer = matches!(c, Ty::InOut(_)); + go_receiver = Some(match pointer { + true => format!("self *{go}"), + false => format!("self {go}"), + }); match c { Ty::Handle { name, .. } => { prelude.push(format!( @@ -2332,7 +2337,11 @@ impl<'a> Gen<'a> { true => "a_, ", false => "", }; - prelude.push(format!("c_self_ := lower_{c}({a}self)")); + let deref = match pointer { + true => "*", + false => "", + }; + prelude.push(format!("c_self_ := lower_{c}({a}{deref}self)")); args.push("&c_self_".to_string()); checked |= self.holds(&ty); } @@ -2571,14 +2580,21 @@ impl<'a> Gen<'a> { let mut call_args = args.clone(); call_args.extend(outs.iter().map(|(n, _)| format!("&c_{n}_"))); let mut call = format!("C.{c_name}({})", call_args.join(", ")); - // Each value passed for `&mut` takes what Rust wrote back, on every path. - let writes: Vec = (function.params.iter().zip(&names)) - .filter(|(param, _)| param.ty.written()) - .map(|(param, name)| { + // Each value passed for `&mut` takes what Rust wrote back, on every path, as does a + // value's own `&mut self`, which Rust wrote back in place. + let mut writes: Vec = match export.call.params.first() { + Some((_, Ty::InOut(_))) => { + let ty = owner_ty.expect("a method has its type"); + vec![format!("*self = {}", self.lift(ty, "c_self_"))] + } + _ => Vec::new(), + }; + writes.extend((function.params.iter().zip(&names)).filter(|(param, _)| param.ty.written()).map( + |(param, name)| { let out = Abi::written(function, &abi::escape(¶m.name)); format!("*{name} = {}", self.lift(param.ty.base(), &format!("c_{out}_"))) - }) - .collect(); + }, + )); if !writes.is_empty() { let made = match &err { Some(_) => { diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index cfd780642..b3bebcfdf 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -165,7 +165,7 @@ pub struct Record { pub methods: Vec, pub traits: Traits, /// For a `Copy` type with private fields, which has no `fields`: its bytes, which only - /// Rust reads. + /// Rust reads or writes, its `pub` fields through accessors among its `methods`. pub opaque: Option, /// For an opaque value, its padding on each target, by target, as `(offset, length)` /// ranges, which the glue zeroes, so no byte Rust leaves uninitialized reaches a @@ -286,9 +286,9 @@ pub struct Object { pub docs: String, /// Whether it is `Sync`: if not, `&self` borrows it on one thread at a time. pub sync: bool, - /// Whether it is `Copy`, which only one with a `pub` field or a `&mut self` method - /// is, any other being a value: taken by value, it is copied out of its handle, as - /// Rust copies it, rather than moved out. + /// Whether it is `Copy`, which only one whose padding depends on its value is, any + /// other being a value: taken by value, it is copied out of its handle, as Rust copies + /// it, rather than moved out. pub copy: bool, /// Whether copies of its handle may share one value, since no call tells that apart /// from `Clone` but by an `Arc`'s or `Rc`'s count: it is `Clone` and `Sync`, its clone owns no state that changes diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 54f5f9a8f..2d2242632 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -1128,7 +1128,8 @@ impl<'a> Gen<'a> { arg.exprs.push(format!("_Native.Pollable({e}, {context})")); arg.rust_args.push(format!("rt::future(env, {p})")); } - Ty::Void | Ty::Future(_) | Ty::Poll | Ty::Out(_) | Ty::Data => { + // A value's `&mut self` is handed back, through `&self`. + Ty::Void | Ty::Future(_) | Ty::Poll | Ty::Out(_) | Ty::InOut(_) | Ty::Data => { unreachable!("{c:?} is no parameter Kotlin passes") } } @@ -2117,6 +2118,16 @@ impl<'a> Gen<'a> { taken: &[String], ) -> Option { let abi = self.abi; + // A value is immutable in Kotlin, so its `&mut self` method returns it as the call + // left it, through a function of the glue's that hands back a copy. + let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); + let function = match &handed { + Some((back, shim)) => { + self.glue.push_str(shim); + back + } + None => function, + }; self.params = locals(&function.params); let export = abi.export(function, owner); let written = function @@ -2304,7 +2315,10 @@ impl<'a> Gen<'a> { let rust_call = |outs: &[String]| { let args: Vec<&String> = rust_args.iter().chain(outs).collect(); let args: Vec<&str> = args.iter().map(|a| a.as_str()).collect(); - format!("crate::{c_name}({})", args.join(", ")) + match handed { + Some(_) => format!("back_{c_name}::call({})", args.join(", ")), + None => format!("crate::{c_name}({})", args.join(", ")), + } }; if let Some(abi::Future { poll, free, .. }) = &export.future { // The call makes the future and polls it once, returning its result if ready, or @@ -3172,7 +3186,7 @@ fn jni_type(abi: &Abi<'_>, c: &Ty, ty: &Type) -> (&'static str, &'static str) { Ty::Waker => ("jobject", "Waker"), Ty::ForeignReader => ("jobject", "java.nio.channels.SeekableByteChannel"), Ty::ForeignFuture => ("jobject", "Any"), - Ty::Poll | Ty::Out(_) | Ty::Data => unreachable!("{c:?} never crosses JNI"), + Ty::Poll | Ty::Out(_) | Ty::InOut(_) | Ty::Data => unreachable!("{c:?} never crosses JNI"), } } diff --git a/ffi/src/python.rs b/ffi/src/python.rs index fdb508a9d..f82f3d628 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1600,8 +1600,22 @@ impl<'a> Gen<'a> { place: Place, ) -> Option
{ let abi = self.abi; + // A value is immutable in Python, so its `&mut self` method returns it as the call + // left it, through a function of the glue's that hands back a copy. + let handed = (owner.zip(owner_ty)).and_then(|(owner, (ty, _))| abi.handed_back(function, owner, ty)); + let function = match &handed { + Some((back, shim)) => { + self.glue.push_str(shim); + back + } + None => function, + }; let export = abi.export(function, owner); let c_name = export.call.name.clone(); + let callee = match handed { + Some(_) => format!("back_{c_name}::call"), + None => format!("crate::{c_name}"), + }; let bare = self.bare(&c_name).to_string(); let owner_c = match owner { Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), @@ -1767,7 +1781,7 @@ impl<'a> Gen<'a> { }; let args: Vec = c_args.iter().cloned().chain(ptrs).collect(); stmts.push(format!( - "{decl}\n\t\tlet ret = rt::call(|| crate::{c_name}({}));\n\t\ts.done();\n\t\t{value}", + "{decl}\n\t\tlet ret = rt::call(|| {callee}({}));\n\t\ts.done();\n\t\t{value}", args.join(", ") )); } diff --git a/ffi/src/swift.rs b/ffi/src/swift.rs index 82ff4b02e..3b189473d 100644 --- a/ffi/src/swift.rs +++ b/ffi/src/swift.rs @@ -1469,9 +1469,11 @@ impl<'a> Gen<'a> { // A struct's method takes `self` as Rust does: by value, it consumes it, and Swift // then frees the handle Rust moved the value out of. let unique = owner_ty.is_some_and(|ty| self.unique(ty)); + // A value's `&mut self` is too, as Rust writes back the value it changed. + let value = matches!(export.call.params.first(), Some((_, Ty::InOut(_)))); let mutation = match receiver { Some(Receiver::Owned) if unique => "consuming ", - Some(Receiver::Mut) if unique => "mutating ", + Some(Receiver::Mut) if unique || value => "mutating ", _ => "", }; // Only a future or a `Result` throws, and a future only once it is awaited. @@ -1508,6 +1510,9 @@ impl<'a> Gen<'a> { _ => { arena |= self.arena(&ty); prelude.push(format!("var c_self_ = self._lower({})", self.arena_arg(&ty))); + if value { + prelude.push(format!("defer {{ self = {} }}", self.lift(&ty, "c_self_"))); + } arg.exprs.push("&c_self_".to_string()); } } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 84bff2cd1..627cf0ecf 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1072,21 +1072,42 @@ static int script(void) { api_Berth_free(empty_berth); api_Berth_free(berth); - /* A `Copy` type changed in place is a handle, which a call taking it by value copies. */ - api_Score *score = api_Score_of(2); - api_Score *step = api_Score_of(3); - api_Score_add(score, step); - api_Score_add(score, step); - api_Score *doubled_score = api_Score_doubled(step); - printf("score %llu %llu %llu\n", (unsigned long long)api_Score_count(score), - (unsigned long long)api_Score_count(doubled_score), (unsigned long long)api_Score_count(step)); - api_Weighted weighted = {.score = api_Score_clone(step), .weight = 4}; + /* A `Copy` type changed in place is a value, whose change reaches only the copy changed. */ + api_Score score = api_Score_of(2); + api_Score step = api_Score_of(3); + api_Score_add(&score, step); + api_Score_add(&score, step); + api_Score doubled_score = api_Score_doubled(&step); + printf("score %llu %llu %llu\n", (unsigned long long)api_Score_count(&score), + (unsigned long long)api_Score_count(&doubled_score), (unsigned long long)api_Score_count(&step)); + api_Score score_copy = score; + uint64_t taken = api_Score_take(&score_copy); + printf("taken %llu %llu %llu\n", (unsigned long long)taken, (unsigned long long)api_Score_count(&score_copy), + (unsigned long long)api_Score_count(&score)); + api_Score other_score = step; + uint64_t before0, before1; + api_Score_absorb(&score_copy, other_score, &other_score, &before0, &before1); + printf("absorbed %llu %llu %llu %llu %llu\n", (unsigned long long)before0, (unsigned long long)before1, + (unsigned long long)api_Score_count(&score_copy), (unsigned long long)api_Score_count(&other_score), + (unsigned long long)api_Score_count(&step)); + api_Hits hits = api_Hits_of(1, 2); + api_Hits kept = hits; + api_Hits_add(&hits, api_Hits_of(10, 20)); + api_Hits_hits_set(&hits, 7); + printf("hits %llu %u %llu %u %s\n", (unsigned long long)api_Hits_hits_get(&hits), api_Hits_misses_get(&hits), + (unsigned long long)api_Hits_hits_get(&kept), api_Hits_misses_get(&kept), + api_Hits_eq(&hits, &kept) ? "true" : "false"); + api_Extent extent = api_Extent_new(5, 3); + api_Extent extent_start = extent; + uint64_t old = api_Extent_slide(&extent, 10); + api_Extent_start_set(&extent, api_Extent_start_get(&extent) + 1); + printf("extent %llu %llu %llu %llu %llu\n", (unsigned long long)old, + (unsigned long long)api_Extent_start_get(&extent), (unsigned long long)api_Extent_end(&extent), + (unsigned long long)api_Extent_start_get(&extent_start), (unsigned long long)api_Extent_end(&extent_start)); + api_Weighted weighted = {.score = step, .weight = 4}; printf("weighted %llu %llu\n", (unsigned long long)api_Weighted_total(&weighted), - (unsigned long long)(api_Score_count(weighted.score) + api_Score_count(step))); + (unsigned long long)(api_Score_count(&weighted.score) + api_Score_count(&step))); api_Weighted_free(&weighted); - api_Score_free(doubled_score); - api_Score_free(step); - api_Score_free(score); static const api_Log_vtable print_log = {.free = log_free, .log = log_line}; uint8_t levels[] = {1, 2, 3, 4}; diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index c57ee5116..9279e37fa 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -607,14 +607,33 @@ int script() { std::printf("berth Some(%u) %s\n", *berth.at(), api::Berth::new_(std::nullopt).at() ? "Some" : "None"); } - // A `Copy` type changed in place is a handle, which a call taking it by value copies. + // A `Copy` type changed in place is a value, whose change reaches only the copy changed. { api::Score score = api::Score::of(2); api::Score step = api::Score::of(3); score.add(step); score.add(step); std::printf("score %llu %llu %llu\n", ull(score.count()), ull(step.doubled().count()), ull(step.count())); - api::Weighted weighted{step.clone(), 4}; + api::Score copy = score; + std::uint64_t taken = copy.take(); + std::printf("taken %llu %llu %llu\n", ull(taken), ull(copy.count()), ull(score.count())); + api::Score other = step; + auto [before0, before1] = copy.absorb(other); + std::printf("absorbed %llu %llu %llu %llu %llu\n", ull(before0), ull(before1), ull(copy.count()), + ull(other.count()), ull(step.count())); + api::Hits hits = api::Hits::of(1, 2); + api::Hits kept = hits; + hits.add(api::Hits::of(10, 20)); + hits.hits_set(7); + std::printf("hits %llu %u %llu %u %s\n", ull(hits.hits_get()), hits.misses_get(), ull(kept.hits_get()), + kept.misses_get(), yes(hits == kept)); + api::Extent extent = api::Extent::new_(5, 3); + api::Extent extent_start = extent; + std::uint64_t old = extent.slide(10); + extent.start_set(extent.start_get() + 1); + std::printf("extent %llu %llu %llu %llu %llu\n", ull(old), ull(extent.start_get()), ull(extent.end()), + ull(extent_start.start_get()), ull(extent_start.end())); + api::Weighted weighted{step, 4}; std::printf("weighted %llu %llu\n", ull(weighted.total()), ull(weighted.score.count() + step.count())); } diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 29acba459..f640969f9 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -366,12 +366,30 @@ Future script() async { final berth = api.Berth(4); print('berth Some(${berth.at()}) ${api.Berth(null).at() == null ? 'None' : 'Some'}'); - // A `Copy` type changed in place is a handle, which a call taking it by value copies. - final score = api.Score.of(2); + // A `Copy` type changed in place is a value, which a `&mut self` method returns as the + // call left it, Rust's own return beside it: a change reaches only the copy it replaces. + var score = api.Score.of(2); final increment = api.Score.of(3); - score.add(increment); - score.add(increment); + score = score.add(increment); + score = score.add(increment); print('score ${score.count()} ${increment.doubled().count()} ${increment.count()}'); + var (scoreCopy, taken) = score.take(); + print('taken $taken ${scoreCopy.count()} ${score.count()}'); + final otherScore = api.Mut(increment); + final (absorbed, before0, before1) = scoreCopy.absorb(otherScore); + scoreCopy = absorbed; + print('absorbed $before0 $before1 ${scoreCopy.count()} ${otherScore.value.count()} ${increment.count()}'); + var hits = api.Hits.of(1, 2); + final keptHits = hits; + hits = hits.add(api.Hits.of(10, 20)); + hits = hits.hitsSet(7); + print('hits ${hits.hitsGet} ${hits.missesGet} ${keptHits.hitsGet} ${keptHits.missesGet} ${hits == keptHits}'); + var extent = api.Extent(5, 3); + final extentStart = extent; + final (slid, old) = extent.slide(10); + extent = slid; + extent = extent.startSet(extent.startGet + 1); + print('extent $old ${extent.startGet} ${extent.end()} ${extentStart.startGet} ${extentStart.end()}'); final weighted = api.Weighted(score: increment, weight: 4); print('weighted ${weighted.total()} ${weighted.score.count() + increment.count()}'); diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 86c984eb1..43bafd40c 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -468,16 +468,30 @@ func script() { berth.Close() empty.Close() - // A `Copy` type changed in place is a handle, which a call taking it by value copies. + // A `Copy` type changed in place is a value, whose change reaches only the copy changed. score := api.ScoreOf(2) step := api.ScoreOf(3) - ok(score.Add(step)) - ok(score.Add(step)) - fmt.Printf("score %d %d %d\n", must(score.Count()), must(must(step.Doubled()).Count()), must(step.Count())) + score.Add(step) + score.Add(step) + fmt.Printf("score %d %d %d\n", score.Count(), step.Doubled().Count(), step.Count()) + scoreCopy := score + taken := scoreCopy.Take() + fmt.Printf("taken %d %d %d\n", taken, scoreCopy.Count(), score.Count()) + otherScore := step + before0, before1 := scoreCopy.Absorb(&otherScore) + fmt.Printf("absorbed %d %d %d %d %d\n", before0, before1, scoreCopy.Count(), otherScore.Count(), step.Count()) + hits := api.HitsOf(1, 2) + keptHits := hits + hits.Add(api.HitsOf(10, 20)) + hits.HitsSet(7) + fmt.Printf("hits %d %d %d %d %t\n", hits.HitsGet(), hits.MissesGet(), keptHits.HitsGet(), keptHits.MissesGet(), hits.Equal(keptHits)) + extent := api.NewExtent(5, 3) + extentStart := extent + old := extent.Slide(10) + extent.StartSet(extent.StartGet() + 1) + fmt.Printf("extent %d %d %d %d %d\n", old, extent.StartGet(), extent.End(), extentStart.StartGet(), extentStart.End()) weighted := api.Weighted{Score: step, Weight: 4} - fmt.Printf("weighted %d %d\n", must(weighted.Total()), must(weighted.Score.Count())+must(step.Count())) - score.Close() - step.Close() + fmt.Printf("weighted %d %d\n", weighted.Total(), weighted.Score.Count()+step.Count()) // Rust frees the implementation once it drops it, releasing Go's. fmt.Printf("kept %d\n", api.Emit(printLog{}, rt.NewBytes([]byte{1, 2, 3, 4}))) diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index d82978add..b8a463866 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -289,12 +289,32 @@ fun script() { val berth = Berth.new(4u) println("berth Some(${berth.at()}) ${if (Berth.new(null).at() == null) "None" else "Some"}") - // A `Copy` type changed in place is a handle, which a call taking it by value copies. - val score = Score.of(2u) + // A `Copy` type changed in place is a value, which a `&mut self` method returns as the + // call left it, Rust's own return beside it: a change reaches only the copy it replaces. + var score = Score.of(2u) val step = Score.of(3u) - score.add(step) - score.add(step) + score = score.add(step) + score = score.add(step) println("score ${score.count()} ${step.doubled().count()} ${step.count()}") + var scoreCopy = score + val (taken, taken0) = scoreCopy.take() + scoreCopy = taken + println("taken $taken0 ${scoreCopy.count()} ${score.count()}") + val otherScore = Mut(step) + val (absorbed, before0, before1) = scoreCopy.absorb(otherScore) + scoreCopy = absorbed + println("absorbed $before0 $before1 ${scoreCopy.count()} ${otherScore.value.count()} ${step.count()}") + var hits = Hits.of(1u, 2u) + val keptHits = hits + hits = hits.add(Hits.of(10u, 20u)) + hits = hits.hitsSet(7u) + println("hits ${hits.hitsGet} ${hits.missesGet} ${keptHits.hitsGet} ${keptHits.missesGet} ${hits == keptHits}") + var extent = Extent.new(5u, 3u) + val extentStart = extent + val (slid, old) = extent.slide(10u) + extent = slid + extent = extent.startSet(extent.startGet + 1u) + println("extent $old ${extent.startGet} ${extent.end()} ${extentStart.startGet} ${extentStart.end()}") val weighted = Weighted(step, 4u) println("weighted ${weighted.total()} ${weighted.score.count() + step.count()}") diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 29dd0eb15..b1c6cd2f4 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -358,12 +358,28 @@ def edit(counter): berth = api.Berth.new(4) print(f"berth Some({berth.at()}) {'None' if api.Berth.new(None).at() is None else 'Some'}") - # A `Copy` type changed in place is a handle, which a call taking it by value copies. + # A `Copy` type changed in place is a value, which a `&mut self` method returns as the + # call left it, Rust's own return beside it: a change reaches only the copy it replaces. score = api.Score.of(2) increment = api.Score.of(3) - score.add(increment) - score.add(increment) + score = score.add(increment) + score = score.add(increment) print(f"score {score.count()} {increment.doubled().count()} {increment.count()}") + score_copy, taken = score.take() + print(f"taken {taken} {score_copy.count()} {score.count()}") + other_score = api.Mut(increment) + score_copy, before0, before1 = score_copy.absorb(other_score) + print(f"absorbed {before0} {before1} {score_copy.count()} {other_score.value.count()} {increment.count()}") + hits = api.Hits.of(1, 2) + kept_hits = hits + hits = hits.add(api.Hits.of(10, 20)) + hits = hits.hits_set(7) + print(f"hits {hits.hits_get} {hits.misses_get} {kept_hits.hits_get} {kept_hits.misses_get} {flag(hits == kept_hits)}") + extent = api.Extent.new(5, 3) + extent_start = extent + extent, old = extent.slide(10) + extent = extent.start_set(extent.start_get + 1) + print(f"extent {old} {extent.start_get} {extent.end()} {extent_start.start_get} {extent_start.end()}") weighted = api.Weighted(increment, 4) print(f"weighted {weighted.total()} {weighted.score.count() + increment.count()}") diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index e2838b355..d5d4a6b9f 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -437,12 +437,28 @@ func script() { let berth = Berth.new(4) print("berth Some(\(berth.at()!)) \(Berth.new(nil).at() == nil ? "None" : "Some")") - // A `Copy` type changed in place is a handle, which a call taking it by value copies. - let score = Score.of(2) + // A `Copy` type changed in place is a value, whose change reaches only the copy changed. + var score = Score.of(2) let step = Score.of(3) score.add(step) score.add(step) print("score \(score.count()) \(step.doubled().count()) \(step.count())") + var scoreCopy = score + let taken = scoreCopy.take() + print("taken \(taken) \(scoreCopy.count()) \(score.count())") + var otherScore = step + let before = scoreCopy.absorb(&otherScore) + print("absorbed \(before.0) \(before.1) \(scoreCopy.count()) \(otherScore.count()) \(step.count())") + var hits = Hits.of(1, 2) + let keptHits = hits + hits.add(Hits.of(10, 20)) + hits.hitsSet(7) + print("hits \(hits.hitsGet) \(hits.missesGet) \(keptHits.hitsGet) \(keptHits.missesGet) \(hits == keptHits)") + var extent = Extent.new(5, 3) + let extentStart = extent + let old = extent.slide(10) + extent.startSet(extent.startGet + 1) + print("extent \(old) \(extent.startGet) \(extent.end()) \(extentStart.startGet) \(extentStart.end())") let weighted = Weighted(score: step, weight: 4) print("weighted \(weighted.total()) \(weighted.score.count() + step.count())") From 00cddaf76ad46b7cfa76ea94435a71588682c4f6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:22:53 -0800 Subject: [PATCH 3/7] docs(ffi): document Copy values changed in place, and finish the quest Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 40 +++++++++++++++++++---------- ffi/src/dart.rs | 3 +++ ffi/src/kotlin.rs | 3 +++ ffi/src/python.rs | 3 +++ quest/m1/ffi-export/copy-values.md | 36 -------------------------- quest/m1/ffi-export/ship.md | 1 - quest/m1/ffi-speed/kotlin-values.md | 4 --- 7 files changed, 35 insertions(+), 55 deletions(-) delete mode 100644 quest/m1/ffi-export/copy-values.md diff --git a/ffi/README.md b/ffi/README.md index 0e1a3afc2..89f273023 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -92,11 +92,11 @@ public path names, or an error taken by value, is held by value as an opaque han | --- | --- | | a struct whose fields are all `pub`, not `#[non_exhaustive]`, which map, with no `Drop` of its own | a record: a struct, copied across | | an enum with variants whose fields map, with no `Drop` of its own | a C enum without fields, or a struct of a tag and a union | -| any other type that is `Copy` and `Send`, with no `pub` field, no `pub` method taking `&mut self`, and no union or enum whose variants initialize different bytes, such as an `Option`, in it, such as moq's `Timestamp` or std's `Instant` | an opaque value: a struct of its bytes, copied across, which only Rust makes or reads, with its padding zeroed; one no export returns is left out, since C could never make one | -| any other type, if `Send` | an object: an opaque handle to an `Arc`, freed with `_free`; one that is `Copy`, since C may change it in place, is copied out of its handle where Rust takes it by value, and a closure neither takes nor returns one by value | +| any other type that is `Copy` and `Send`, with no union or enum whose variants initialize different bytes, such as an `Option`, in it, such as moq's `Timestamp`, `stats::Traffic`, or std's `Instant` | an opaque value: a struct of its bytes, copied across, which only Rust makes, reads, or changes, with its padding zeroed; its `pub` fields are a getter and a setter, and a `&mut self` method writes back the caller's copy alone, one returning a future or a `Result` refused, since a language raising the error would lose the change; one no export returns is left out, since C could never make one | +| any other type, if `Send` | an object: an opaque handle to an `Arc`, freed with `_free`; one that is `Copy`, since its handle is shared, is copied out of its handle where Rust takes it by value, and a closure neither takes nor returns one by value | | 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, and a setter assigning in place, as `x.field = value` does | +| a `pub` field of an object or opaque value | 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 trait C cannot implement, such as one with a blanket impl, an associated type, or a supertrait but a marker, is left out, since C never passes one, and a signature taking one from C is refused | | a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce` alone, taking what a callback takes, objects by reference, or opaque values, and returning a scalar, a `String`, an opaque value, an `Option` of one, or a `Result` of one and a `String` | a C function and its `void *` data; one a lifetime bound or the return lets outlive the call, as kio's `clock::drive` and a spawned task's are, adds a `free` Rust calls once it drops it; a closure of any other signature is refused | | a type parameter or `impl` taken by value and bounded by `Future` or `IntoFuture`, whose every bound `Pin + Send>>` meets, as kio's `clock::timeout` takes, or taken as `Pin<&mut F>` by a poll, as kio's `Waiter::poll_future` takes | `_foreign_future`: a future of `()` C implements, which Rust takes as that type, or which the future the poll makes owns and pins; a future of another output is refused | @@ -253,9 +253,9 @@ where it was while its file is unchanged. - **Handles** are `Arc`s, and a call borrows the value as Rust's receiver or parameter does, checked at run time: shared for `&T`, exclusive for `&mut T`, and moved out for - `T`, after which the handle is only freed. A `Copy` object, one with a `pub` field, a - `pub` method taking `&mut self`, or bytes its value decides are initialized, as an - `Option` in it does, is copied out instead, leaving its handle as it was. A + `T`, after which the handle is only freed. A `Copy` object, one whose bytes its value + decides are initialized, as an `Option` in it does, is copied out instead, leaving + its handle as it was. A 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: @@ -266,8 +266,9 @@ where it was while its file is unchanged. it, so moving it out would abort. - **Opaque values** are `typedef struct { uintN_t opaque[n]; } ;`, the bytes of a `Copy` type with private fields, in units of its alignment up to 8 bytes: C copies one - as any struct, and passes `&self` as a `const *`, but never makes or changes one, - and frees none. Its padding is zero, from a table of each target's padding rustc's + as any struct, and passes `&self` as a `const *` and `&mut self`, a field's setter + included, as a ` *` Rust writes what the call left back through, so only that copy + changes; it never makes or reads one itself, and frees none. Its padding is zero, from a table of each target's padding rustc's layout gives, so no byte Rust left uninitialized reaches a language, which may serialize what it holds. Its size and alignment are the largest of the export's targets, so one header serves them all, a few bytes past a 32-bit target's own. A change of size is an @@ -427,7 +428,8 @@ packages place it in. `std::variant` of a struct per variant, `_`. An enum's methods and traits are free functions taking it first. `PartialEq` is `==`, `Display` `to_string()`, `Debug` `debug()`, and `Default` `default_()`. An **opaque value** is a trivially - copyable class holding its C struct, with no public constructor, so only Rust makes one. + copyable class holding its C struct, with no public constructor, so only Rust makes one; + a `&mut self` method is not `const`, and assigns `*this` what Rust wrote back. - **Bytes** are passed as a `view`, which any contiguous bytes convert to, and returned as a `buf`, which owns Rust's buffer without a copy, so it outlives the object it came from. From C++20, either converts to `std::span`. A `view` or span @@ -515,7 +517,10 @@ out, with only its other fields encoded. derived or std `PartialEq`, a value class over a `Long`, compared by its bits, which allocates nothing unless Kotlin boxes it, as in a `List` or a nullable; otherwise one over a `LongArray`, whose `==` is Rust's, and whose `hashCode` is 0, since none Kotlin - computes agrees with it. + computes agrees with it. Either is shared by reference, so it never changes: a `&mut + self` method, a field's setter included, returns the value as the call left it, + `x = x.add(o)`, and beside Rust's own return, a `Pair`, or each element of its tuple, + `val (y, n) = x.take()`. - **Bytes** are a `Bytes`. Passed in, Rust's own are shared with no copy, and Kotlin's, which `Bytes(ByteArray)` holds without a copy, are copied once into a buffer Rust takes, at a call's top level or in a record; those Rust lends a closure or trait method are @@ -619,7 +624,10 @@ caller imports it with no ignores. `Event.Moved(p)`. `Display` is `str()`, `Debug` `repr()`, and `Default` a static `default()`. Constants are module or class attributes, made anew on each read unless a literal. An **opaque value** is a class of the runtime's `Value`, which holds its bytes - in place, so only Rust makes or reads one: making one raises `TypeError`. + in place, so only Rust makes or reads one: making one raises `TypeError`. It is shared + by reference, so it never changes: a `&mut self` method, a field's setter included, + returns the value as the call left it, `x = x.add(o)`, and beside Rust's own return, a + `tuple`, with each element of a tuple Rust returns, `x, n = x.take()`. - **Bytes** passed in are any buffer, `bytes | bytearray | memoryview`: `bytes` is read in place, and others, which Python may change while Rust reads, are copied. Bytes Rust returns, or a record holds, are a read-only `memoryview` lending Rust's buffer until it @@ -719,7 +727,8 @@ and, for `Swift.Duration`, macOS 13 or iOS 16, and builds in either language mod - **Records** are structs and **enums** Swift enums, with a variant's data as associated values, all `Sendable`. `PartialEq` is `==`, through Rust's; `Display` is `description`, `Debug` `debugDescription`, and `Default` a static `default()`. An **opaque value** is - a struct holding its C struct, with no public initializer, so only Rust makes one. + a struct holding its C struct, with no public initializer, so only Rust makes one; a + `&mut self` method is `mutating`, and assigns `self` what Rust wrote back. - **Bytes** are the runtime's `Bytes`, a `RandomAccessCollection` of `UInt8` whose slices are `Bytes` too. Bytes Rust returns lend its buffer until Swift releases the last `Bytes` or slice reading it, and pass back to Rust as a second owner of it, with no copy, except @@ -829,7 +838,8 @@ reads a go.mod. since cgo gives each its own C types: callers use neither. An **opaque value** is a struct of its bytes, `Bytes_`, and `Made_`, true once Rust made it: a zero value panics where Rust would read it, and `==` does not compile, since bytes alike need not be - equal, so `Equal`, if it has one, is Rust's. + equal, so `Equal`, if it has one, is Rust's. A `&mut self` method has a pointer + receiver, which it assigns what Rust wrote back. - **Bytes** a call takes are a `[]byte`, and text a `string`, each read in place: Go's memory, pinned where C reads it through other memory. Bytes Rust passes a callback are copied into a `[]byte`. Bytes anywhere else, such as those Rust returns or a record @@ -932,7 +942,9 @@ the library's own URI, mapped to the library by a build hook or by `--native-ass through Rust's, with a `hashCode` that throws an `UnsupportedError`, since no hash Dart computes agrees with Rust's `==`, and `Default` a constructor, `default_()`. An **opaque value** is a final class of its bytes as `int`s, with a private constructor, - so only Rust makes one. A plain enum's `==` is Dart's, by its value. + so only Rust makes one. It never changes: a `&mut self` method, a field's setter + included, returns the value as the call left it, `x = x.add(o)`, and beside Rust's own + return, a record, with each element of a tuple Rust returns, `final (y, n) = x.take()`. A plain enum's `==` is Dart's, by its value. - **Integers** are `int`. A narrower one passed in throws a `RangeError` when out of its range, and a `u64` passes its 64 bits, so one past `i64`'s range is negative in Dart. A `char` is a `String` of one Unicode scalar. diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 077460665..76035e85c 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -2296,6 +2296,9 @@ impl<'a> Gen<'a> { } let mut text = function.docs.clone(); + if handed.is_some() { + text.push_str("\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes."); + } for param in &function.params { let name = param_name(¶m.name); match ¶m.ty { diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 2d2242632..97b4db31d 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -2716,6 +2716,9 @@ impl<'a> Gen<'a> { } let mut text = function.docs.clone(); + if handed.is_some() { + text.push_str("\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes."); + } for (param, name) in function.params.iter().zip(&names) { if let Type::Closure(closure_) = ¶m.ty { let lent = &closure_.params; diff --git a/ffi/src/python.rs b/ffi/src/python.rs index f82f3d628..a5b0e05a0 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1787,6 +1787,9 @@ impl<'a> Gen<'a> { } // The Python. let mut text = function.docs.clone(); + if handed.is_some() { + text.push_str("\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes."); + } for param in &function.params { let name = param_name(¶m.name); if let Type::Closure(closure_) = ¶m.ty { diff --git a/quest/m1/ffi-export/copy-values.md b/quest/m1/ffi-export/copy-values.md deleted file mode 100644 index f4aab9b5e..000000000 --- a/quest/m1/ffi-export/copy-values.md +++ /dev/null @@ -1,36 +0,0 @@ -# [M] Copy types that change cross by value - -## Goal - -A [rust2-ffi](/ffi/README.md) export's `Copy` type with a `pub` field or a `pub` method -taking `&mut self` crosses as an opaque value, as a `Send` `Copy` type with only private -fields and value-independent padding does since -[#742](https://github.com/kixel-ai/rust2/pull/742), instead of an `Arc` handle. A setter -or `&mut self` method writes the new bytes back into the language's own copy, so -`x.add(other)` changes `x` and only `x`, as in Rust. moq has five today, each -still a handle: `stats::Traffic`, `stats::Presence`, `stats::Failures`, and -`stats::Refusals` (`add`), and `clock::WallMap` (`sample`). - -## Plan - -- C takes `T *` for `&mut self` and writes the value back in place; C++ makes the method - non-`const`; Swift makes it `mutating`; Go takes a pointer receiver. Each writes only - the caller's copy. -- A `pub` field gets a getter and a setter over the bytes, through Rust, as an object's - field does; the bytes stay opaque. -- Prove it with the api fixture's differential tests: a `Copy` type with a `pub` field and - a `&mut self` method, mutated through a copy and through the original, and the copy left - as it was. -- Kotlin, Dart, and Python, whose values are immutable, hand back a `&mut self` method's - result as its new value, `x = x.add(o)`, with Rust's own return, if any, as a pair: - Python's `Value` and Kotlin's class over words are shared by reference, so mutating one - in place would change every alias, unlike a Rust copy. ✅ the method returns the new - value (rejected: a mutable wrapper type, which allocates; keeping such types as handles - in these three, which splits one Rust type across languages). -- Then `ffi/src/collect.rs`'s `changed`, which keeps these types objects today, goes. - -Public API: how every generated API holds these types (breaking). - -## Related - -- [Kotlin values without a LongArray](/quest/m1/ffi-speed/kotlin-values.md) - how Kotlin holds the bytes this writes back diff --git a/quest/m1/ffi-export/ship.md b/quest/m1/ffi-export/ship.md index fab62a833..06f3d3202 100644 --- a/quest/m1/ffi-export/ship.md +++ b/quest/m1/ffi-export/ship.md @@ -22,7 +22,6 @@ then see change. A sibling planned later adds itself to `Required` here. - [Refusals](/quest/m1/ffi-refusals/README.md) - the census lists no refusals at the moq pin, and `ffi.toml` is gone - [Failed checks raise](/quest/m1/ffi-export/checks-raise.md) - which generated functions throw - [Lossless binding types](/quest/m1/ffi-export/lossless.md) - the types of durations, addresses, paths, and text -- [Copy types that change cross by value](/quest/m1/ffi-export/copy-values.md) - how moq's stats and `WallMap` are held in every language - [Opaque padding from the glue's rustc](/quest/m1/ffi-export/padding-layout.md) - that zeroing an opaque value's padding never zeroes a live field - [Not Send](/quest/m1/ffi-export/not-send.md) - the types and futures that export checked by thread - [Export moq for every target](/quest/m1/ffi-export/moq-targets.md) - one binding across the targets moq ships diff --git a/quest/m1/ffi-speed/kotlin-values.md b/quest/m1/ffi-speed/kotlin-values.md index 12ca762a8..036c0590d 100644 --- a/quest/m1/ffi-speed/kotlin-values.md +++ b/quest/m1/ffi-speed/kotlin-values.md @@ -17,7 +17,3 @@ within its `from_micros` call of the plain write, as Go's and Dart's do. - `equals` and `hashCode` keep today's rules, so only the storage changes. - Re-measure the stamped write, CPU and wall, on HotSpot and on ART in the nightly emulator job. - -## Related - -- [Copy types that change cross by value](/quest/m1/ffi-export/copy-values.md) - writes a value's bytes back, through the same fields From e50f483ab6218f6d75f303388141975a8bf01107 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:23:40 -0800 Subject: [PATCH 4/7] style(ffi): fmt Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 26 ++++++++++++++++++++++--- ffi/src/abi.rs | 5 ++++- ffi/src/collect.rs | 4 ++-- ffi/src/cpp.rs | 14 +++++++------ ffi/src/dart.rs | 4 +++- ffi/src/glue.rs | 7 +++---- ffi/src/go.rs | 14 +++++++------ ffi/src/kotlin.rs | 4 +++- ffi/src/python.rs | 4 +++- 9 files changed, 57 insertions(+), 25 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 822fef4bb..e77c17803 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -341,17 +341,37 @@ fn main() { println!("taken {taken} {} {}", copy.count(), score.count()); let mut other = step; let before = copy.absorb(&mut other); - println!("absorbed {} {} {} {} {}", before.0, before.1, copy.count(), other.count(), step.count()); + println!( + "absorbed {} {} {} {} {}", + before.0, + before.1, + copy.count(), + other.count(), + step.count() + ); let mut hits = api::Hits::of(1, 2); let kept = hits; hits.add(api::Hits::of(10, 20)); hits.hits = 7; - println!("hits {} {} {} {} {}", hits.hits, hits.misses, kept.hits, kept.misses, hits == kept); + println!( + "hits {} {} {} {} {}", + hits.hits, + hits.misses, + kept.hits, + kept.misses, + hits == kept + ); let mut extent = api::Extent::new(5, 3); let start = extent; let old = extent.slide(10); extent.start += 1; - println!("extent {old} {} {} {} {}", extent.start, extent.end(), start.start, start.end()); + println!( + "extent {old} {} {} {} {}", + extent.start, + extent.end(), + start.start, + start.end() + ); let weighted = api::Weighted { score: step, weight: 4 }; println!( "weighted {} {}", diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index d3a26cbfb..642d34e3c 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -859,7 +859,10 @@ impl<'a> Abi<'a> { return None; } // `written_back` in collect.rs refuses a future's and a `Result`'s. - assert!(!function.future && function.err.is_none(), "a value's `&mut self` returns a plain value"); + assert!( + !function.future && function.err.is_none(), + "a value's `&mut self` returns a plain value" + ); let real = self.export(function, Some(owner)); let returned = match &function.ok { Type::Unit => Vec::new(), diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 739c0e50f..48884c195 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2519,8 +2519,8 @@ impl<'tcx> Collector<'tcx> { /// not hand back with what it returns: a future's, which outlives the call, and a /// `Result`'s, whose error a language raising it would lose the change with. fn written_back(&mut self, methods: Vec) -> Vec { - let (refused, kept): (Vec, Vec) = (methods.into_iter()) - .partition(|m| m.receiver == Some(Receiver::Mut) && (m.future || m.err.is_some())); + let (refused, kept): (Vec, Vec) = + (methods.into_iter()).partition(|m| m.receiver == Some(Receiver::Mut) && (m.future || m.err.is_some())); for m in refused { let construct = match m.future { true => "`&mut self` of a value in a future", diff --git a/ffi/src/cpp.rs b/ffi/src/cpp.rs index 857c42915..76b63be10 100644 --- a/ffi/src/cpp.rs +++ b/ffi/src/cpp.rs @@ -1555,12 +1555,14 @@ impl<'a> Header<'a> { } _ => Vec::new(), }; - writes.extend((function.params.iter().zip(&names)).filter(|(param, _)| param.ty.written()).map( - |(param, name)| { - let out = Abi::written(function, &abi::escape(¶m.name)); - format!("{name} = {};", self.lift(param.ty.base(), &format!("c_{out}_"))) - }, - )); + writes.extend( + (function.params.iter().zip(&names)) + .filter(|(param, _)| param.ty.written()) + .map(|(param, name)| { + let out = Abi::written(function, &abi::escape(¶m.name)); + format!("{name} = {};", self.lift(param.ty.base(), &format!("c_{out}_"))) + }), + ); for (name, _) in &outs { args.push(format!("&c_{name}_")); } diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 76035e85c..613ebbbe5 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -2297,7 +2297,9 @@ impl<'a> Gen<'a> { let mut text = function.docs.clone(); if handed.is_some() { - text.push_str("\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes."); + text.push_str( + "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", + ); } for param in &function.params { let name = param_name(¶m.name); diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 9264d9174..8bdb0880c 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -1896,10 +1896,9 @@ impl Gen<'_> { // Rust writes back what the call left in each value C passed for `&mut`, on every // path, errors included, and in a value's `&mut self`, in place. let mut writes: String = match &receiver_ty { - Some(((_, value), Receiver::Mut)) if !matches!(value, Type::Object(_)) => format!( - "\n\tunsafe {{ this.write({}) }};", - self.lower(value, "a_self") - ), + Some(((_, value), Receiver::Mut)) if !matches!(value, Type::Object(_)) => { + format!("\n\tunsafe {{ this.write({}) }};", self.lower(value, "a_self")) + } _ => String::new(), }; writes += &(function.params.iter().enumerate()) diff --git a/ffi/src/go.rs b/ffi/src/go.rs index c9cd920a0..b8bb49d1e 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2589,12 +2589,14 @@ impl<'a> Gen<'a> { } _ => Vec::new(), }; - writes.extend((function.params.iter().zip(&names)).filter(|(param, _)| param.ty.written()).map( - |(param, name)| { - let out = Abi::written(function, &abi::escape(¶m.name)); - format!("*{name} = {}", self.lift(param.ty.base(), &format!("c_{out}_"))) - }, - )); + writes.extend( + (function.params.iter().zip(&names)) + .filter(|(param, _)| param.ty.written()) + .map(|(param, name)| { + let out = Abi::written(function, &abi::escape(¶m.name)); + format!("*{name} = {}", self.lift(param.ty.base(), &format!("c_{out}_"))) + }), + ); if !writes.is_empty() { let made = match &err { Some(_) => { diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 97b4db31d..6e926a374 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -2717,7 +2717,9 @@ impl<'a> Gen<'a> { let mut text = function.docs.clone(); if handed.is_some() { - text.push_str("\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes."); + text.push_str( + "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", + ); } for (param, name) in function.params.iter().zip(&names) { if let Type::Closure(closure_) = ¶m.ty { diff --git a/ffi/src/python.rs b/ffi/src/python.rs index a5b0e05a0..579100731 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1788,7 +1788,9 @@ impl<'a> Gen<'a> { // The Python. let mut text = function.docs.clone(); if handed.is_some() { - text.push_str("\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes."); + text.push_str( + "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", + ); } for param in &function.params { let name = param_name(¶m.name); From d318c87d5fd513bb9fbdff89343a08d9c69f10b3 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:38:42 -0800 Subject: [PATCH 5/7] fix(ffi): a handed-back method keeps its renamed C name Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 3 +++ ffi/fixtures/api/src/lib.rs | 8 ++++++++ ffi/src/abi.rs | 13 +++++++++---- ffi/src/dart.rs | 14 +++++++------- ffi/src/kotlin.rs | 12 ++++++------ ffi/src/python.rs | 12 ++++++------ ffi/tests/api.c | 3 +++ ffi/tests/api.cpp | 3 +++ ffi/tests/api.dart | 2 ++ ffi/tests/api.go | 3 +++ ffi/tests/api.kt | 2 ++ ffi/tests/api.py | 2 ++ ffi/tests/api.swift | 3 +++ 13 files changed, 57 insertions(+), 23 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index e77c17803..93a1a5573 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -361,6 +361,9 @@ fn main() { kept.misses, hits == kept ); + let mut counted = kept; + let same = api::Hits::eq(&mut counted, kept); + println!("counted {same} {}", counted.hits); let mut extent = api::Extent::new(5, 3); let start = extent; let old = extent.slide(10); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 2467e8265..c6315476c 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1346,6 +1346,14 @@ impl Hits { self.hits = self.hits.wrapping_add(other.hits); self.misses = self.misses.wrapping_add(other.misses); } + + /// Whether `other` equals this one, counting it a hit: named as `PartialEq`'s C + /// function, which the clash renames. + pub fn eq(&mut self, other: Hits) -> bool { + let same = *self == other; + self.hits = self.hits.wrapping_add(1); + same + } } /// A span whose `pub` start sits beside a private length, which no record could hold. diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index 642d34e3c..9017d2fd8 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -853,8 +853,9 @@ impl<'a> Abi<'a> { /// through `&self`, returning the value as the call left it, before Rust's own return /// or each element of its tuple; and the Rust function `back_::call`, of that /// function's C signature, that calls the C one with a copy and hands the copy back. - /// `None` for any other function. - pub fn handed_back(&self, function: &Function, owner: &Ty, owner_ty: &Type) -> Option<(Function, String)> { + /// That function's export keeps the C name of the method's, which a clash may have + /// renamed. `None` for any other function. + pub fn handed_back(&self, function: &Function, owner: &Ty, owner_ty: &Type) -> Option<(Function, Export, String)> { if function.receiver != Some(Receiver::Mut) || matches!(owner, Ty::Handle { .. }) { return None; } @@ -877,7 +878,11 @@ impl<'a> Abi<'a> { }, ..function.clone() }; - let sig = self.export(&back, Some(owner)).call; + // Named as the method is: a rename is keyed by the API's own function. + let mut export = self.export(&back, Some(owner)); + export.call.name = real.call.name.clone(); + export.named = real.named.clone(); + let sig = &export.call; let params: Vec = (sig.params.iter().enumerate()) .map(|(n, (_, ty))| format!("p{n}: {}", crate::glue::rs(ty))) .collect(); @@ -911,7 +916,7 @@ impl<'a> Abi<'a> { params.join(", "), crate::glue::rs(&sig.ret), ); - Some((back, shim)) + Some((back, export, shim)) } fn claim(&mut self, name: String, what: String, span: Span, owner: Option) { diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 613ebbbe5..f8e8b5e5c 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -2016,15 +2016,15 @@ impl<'a> Gen<'a> { // A value is immutable in Dart, so its `&mut self` method returns it as the call left // it, through a function of the glue's that hands back a copy. let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); - let function = match &handed { - Some((back, shim)) => { - self.glue.push_str(shim); - self.handed.insert(abi.export(back, owner).call.name); - back + let (handed, export) = match handed { + Some((back, export, shim)) => { + self.glue.push_str(&shim); + self.handed.insert(export.call.name.clone()); + (Some(back), export) } - None => function, + None => (None, abi.export(function, owner)), }; - let export = abi.export(function, owner); + let function = handed.as_ref().unwrap_or(function); let c_name = export.call.name.clone(); let owner_c = match owner { Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 6e926a374..71edea453 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -2121,15 +2121,15 @@ impl<'a> Gen<'a> { // A value is immutable in Kotlin, so its `&mut self` method returns it as the call // left it, through a function of the glue's that hands back a copy. let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); - let function = match &handed { - Some((back, shim)) => { - self.glue.push_str(shim); - back + let (handed, export) = match handed { + Some((back, export, shim)) => { + self.glue.push_str(&shim); + (Some(back), export) } - None => function, + None => (None, abi.export(function, owner)), }; + let function = handed.as_ref().unwrap_or(function); self.params = locals(&function.params); - let export = abi.export(function, owner); let written = function .params .iter() diff --git a/ffi/src/python.rs b/ffi/src/python.rs index 579100731..84ed8e6d8 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1603,14 +1603,14 @@ impl<'a> Gen<'a> { // A value is immutable in Python, so its `&mut self` method returns it as the call // left it, through a function of the glue's that hands back a copy. let handed = (owner.zip(owner_ty)).and_then(|(owner, (ty, _))| abi.handed_back(function, owner, ty)); - let function = match &handed { - Some((back, shim)) => { - self.glue.push_str(shim); - back + let (handed, export) = match handed { + Some((back, export, shim)) => { + self.glue.push_str(&shim); + (Some(back), export) } - None => function, + None => (None, abi.export(function, owner)), }; - let export = abi.export(function, owner); + let function = handed.as_ref().unwrap_or(function); let c_name = export.call.name.clone(); let callee = match handed { Some(_) => format!("back_{c_name}::call"), diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 627cf0ecf..3cebce763 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1097,6 +1097,9 @@ static int script(void) { printf("hits %llu %u %llu %u %s\n", (unsigned long long)api_Hits_hits_get(&hits), api_Hits_misses_get(&hits), (unsigned long long)api_Hits_hits_get(&kept), api_Hits_misses_get(&kept), api_Hits_eq(&hits, &kept) ? "true" : "false"); + api_Hits counted = kept; + bool counted_same = api_Hits_eq_(&counted, kept); + printf("counted %s %llu\n", counted_same ? "true" : "false", (unsigned long long)api_Hits_hits_get(&counted)); api_Extent extent = api_Extent_new(5, 3); api_Extent extent_start = extent; uint64_t old = api_Extent_slide(&extent, 10); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 9279e37fa..42af6bbc1 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -627,6 +627,9 @@ int script() { hits.hits_set(7); std::printf("hits %llu %u %llu %u %s\n", ull(hits.hits_get()), hits.misses_get(), ull(kept.hits_get()), kept.misses_get(), yes(hits == kept)); + api::Hits counted = kept; + bool counted_same = counted.eq_(kept); + std::printf("counted %s %llu\n", yes(counted_same), ull(counted.hits_get())); api::Extent extent = api::Extent::new_(5, 3); api::Extent extent_start = extent; std::uint64_t old = extent.slide(10); diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index f640969f9..b5b5f956e 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -384,6 +384,8 @@ Future script() async { hits = hits.add(api.Hits.of(10, 20)); hits = hits.hitsSet(7); print('hits ${hits.hitsGet} ${hits.missesGet} ${keptHits.hitsGet} ${keptHits.missesGet} ${hits == keptHits}'); + final (counted, countedSame) = keptHits.eq(keptHits); + print('counted $countedSame ${counted.hitsGet}'); var extent = api.Extent(5, 3); final extentStart = extent; final (slid, old) = extent.slide(10); diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 43bafd40c..612207184 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -485,6 +485,9 @@ func script() { hits.Add(api.HitsOf(10, 20)) hits.HitsSet(7) fmt.Printf("hits %d %d %d %d %t\n", hits.HitsGet(), hits.MissesGet(), keptHits.HitsGet(), keptHits.MissesGet(), hits.Equal(keptHits)) + counted := keptHits + countedSame := counted.Eq(keptHits) + fmt.Printf("counted %t %d\n", countedSame, counted.HitsGet()) extent := api.NewExtent(5, 3) extentStart := extent old := extent.Slide(10) diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index b8a463866..29afe6d19 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -309,6 +309,8 @@ fun script() { hits = hits.add(Hits.of(10u, 20u)) hits = hits.hitsSet(7u) println("hits ${hits.hitsGet} ${hits.missesGet} ${keptHits.hitsGet} ${keptHits.missesGet} ${hits == keptHits}") + val (counted, countedSame) = keptHits.eq(keptHits) + println("counted $countedSame ${counted.hitsGet}") var extent = Extent.new(5u, 3u) val extentStart = extent val (slid, old) = extent.slide(10u) diff --git a/ffi/tests/api.py b/ffi/tests/api.py index b1c6cd2f4..54f59dea2 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -375,6 +375,8 @@ def edit(counter): hits = hits.add(api.Hits.of(10, 20)) hits = hits.hits_set(7) print(f"hits {hits.hits_get} {hits.misses_get} {kept_hits.hits_get} {kept_hits.misses_get} {flag(hits == kept_hits)}") + counted, same = kept_hits.eq(kept_hits) + print(f"counted {flag(same)} {counted.hits_get}") extent = api.Extent.new(5, 3) extent_start = extent extent, old = extent.slide(10) diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index d5d4a6b9f..f45068437 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -454,6 +454,9 @@ func script() { hits.add(Hits.of(10, 20)) hits.hitsSet(7) print("hits \(hits.hitsGet) \(hits.missesGet) \(keptHits.hitsGet) \(keptHits.missesGet) \(hits == keptHits)") + var counted = keptHits + let countedSame = counted.eq(keptHits) + print("counted \(countedSame) \(counted.hitsGet)") var extent = Extent.new(5, 3) let extentStart = extent let old = extent.slide(10) From bd3cddf202732719d1e31b32797c9ac57df3f845 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:05:42 -0800 Subject: [PATCH 6/7] refactor(ffi): hand a value back in each generator's call path, not a Rust shim Kotlin's, Python's, and Dart's glue now call a value's in-place C function on their own copy and write that copy back inline. Abi::handed_back no longer builds the back_::call module. Co-Authored-By: Claude Opus 5.5 --- ffi/src/abi.rs | 89 ++++++++++++++++++++++++++++------------------- ffi/src/dart.rs | 24 ++++++------- ffi/src/kotlin.rs | 20 +++++------ ffi/src/python.rs | 24 ++++++------- 4 files changed, 82 insertions(+), 75 deletions(-) diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index 9017d2fd8..0da323c3c 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -118,6 +118,48 @@ pub struct Export { pub future: Option, } +/// How the glue calls a value's `&mut self` method for a language whose values are +/// immutable, which [`Abi::handed_back`] makes. +#[derive(Clone)] +pub struct Handed { + /// The C name of the method's function, which a clash may have renamed. + name: String, + /// How many parameters both take after `self`, before the outs. + lead: usize, + /// Whether the method returns nothing. + unit: bool, + /// Whether it returns a tuple, which the C function writes through its outs. + tuple: bool, +} + +impl Handed { + /// The glue's expression, of the handed-back export's C return, calling the C function + /// in place on a copy of the value that `args[0]` points to and handing the copy back. + /// `args` are of that export's C signature: `self`, what both take after it, then the outs the value and + /// each element Rust returns are written through, which the C function takes from the + /// one after the value's. + pub fn call(&self, args: &[String]) -> String { + let lead = self.lead; + let mut real = vec!["&mut handed_".to_string()]; + real.extend(args[1..=lead].iter().cloned()); + if self.tuple { + real.extend(args[lead + 2..].iter().cloned()); + } + let call = format!("crate::{}({})", self.name, real.join(", ")); + // Apart from the names the glue gives its arguments, which are numbered. + let body = match (self.unit, self.tuple) { + (true, _) => format!("{call};\n\thanded_"), + (_, true) => format!("{call};\n\tstd::ptr::write({}, handed_)", args[lead + 1]), + (_, false) => format!( + "let handed_r_ = {call};\n\tstd::ptr::write({}, handed_);\n\tstd::ptr::write({}, handed_r_)", + args[lead + 1], + args[lead + 2] + ), + }; + format!("unsafe {{\n\tlet mut handed_ = *({});\n\t{body}\n}}", args[0]) + } +} + /// The C functions of a future besides the call that makes it. pub struct Future { /// The handle's type. @@ -851,11 +893,10 @@ impl<'a> Abi<'a> { /// A value's `&mut self` method as a language whose values are immutable calls it: /// through `&self`, returning the value as the call left it, before Rust's own return - /// or each element of its tuple; and the Rust function `back_::call`, of that - /// function's C signature, that calls the C one with a copy and hands the copy back. - /// That function's export keeps the C name of the method's, which a clash may have - /// renamed. `None` for any other function. - pub fn handed_back(&self, function: &Function, owner: &Ty, owner_ty: &Type) -> Option<(Function, Export, String)> { + /// or each element of its tuple: that function, its export, and how the glue calls it. + /// The export keeps the C name of the method's, which a clash may have renamed. `None` + /// for any other function. + pub fn handed_back(&self, function: &Function, owner: &Ty, owner_ty: &Type) -> Option<(Function, Export, Handed)> { if function.receiver != Some(Receiver::Mut) || matches!(owner, Ty::Handle { .. }) { return None; } @@ -881,42 +922,18 @@ impl<'a> Abi<'a> { // Named as the method is: a rename is keyed by the API's own function. let mut export = self.export(&back, Some(owner)); export.call.name = real.call.name.clone(); - export.named = real.named.clone(); - let sig = &export.call; - let params: Vec = (sig.params.iter().enumerate()) - .map(|(n, (_, ty))| format!("p{n}: {}", crate::glue::rs(ty))) - .collect(); - // What both take after `self`, then the outs the real one writes its tuple through, - // which the other's take after the value's own. + export.named = real.named; let elements = match &function.ok { Type::Tuple(elements) => elements.len(), _ => 0, }; - let tuple = elements > 0; - let lead = real.call.params.len() - 1 - elements; - let mut args = vec!["&mut v".to_string()]; - args.extend((1..=lead).map(|n| format!("p{n}"))); - if tuple { - args.extend((lead + 2..sig.params.len()).map(|n| format!("p{n}"))); - } - let call = format!("crate::{}({})", real.call.name, args.join(", ")); - let body = match (&function.ok, tuple) { - (Type::Unit, _) => format!("{call};\n\t\t\tv"), - (_, true) => format!("{call};\n\t\t\tp{}.write(v);", lead + 1), - (_, false) => format!( - "let r = {call};\n\t\t\tp{}.write(v);\n\t\t\tp{}.write(r);", - lead + 1, - lead + 2 - ), + let handed = Handed { + name: real.call.name, + lead: real.call.params.len() - 1 - elements, + unit: function.ok == Type::Unit, + tuple: elements > 0, }; - // In a module of its own, which names the C types as the crate's root does. - let shim = format!( - "mod back_{} {{\n\tuse crate::*;\n\n\tpub unsafe fn call({}) -> {} {{\n\t\tunsafe {{\n\t\t\tlet mut v = *p0;\n\t\t\t{body}\n\t\t}}\n\t}}\n}}\n\n", - real.call.name, - params.join(", "), - crate::glue::rs(&sig.ret), - ); - Some((back, export, shim)) + Some((back, export, handed)) } fn claim(&mut self, name: String, what: String, span: Span, owner: Option) { diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index f8e8b5e5c..7f3dbb81c 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -88,7 +88,7 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result { on: On, /// The namespace of the glue's C names, apart from the export's. space: String, - /// The C functions of a value's `&mut self` methods, which a call reaches through the - /// glue's `back_`, handing back the value as the call left it. - handed: BTreeSet, + /// A value's `&mut self` methods by their C names, which a call makes in place on a + /// copy it hands back. + handed: BTreeMap, } impl<'a> Gen<'a> { @@ -798,16 +798,15 @@ impl<'a> Gen<'a> { .map(|(n, (_, ty))| format!(", p{n}: {}", rs(ty))) .collect(); let args: Vec = (0..call.params.len()).map(|n| format!("p{n}")).collect(); - let callee = match self.handed.contains(&call.name) { - true => format!("back_{}::call", call.name), - false => format!("crate::{}", call.name), + let call_ = match self.handed.get(&call.name) { + Some(h) => h.call(&args), + None => format!("crate::{}({})", call.name, args.join(", ")), }; let _ = write!( self.glue, - "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {name}(home: *const c_void{}) -> {} {{\n\tlet home = unsafe {{ &*home.cast::() }};\n\tunsafe {{ home.serve(move || {callee}({})) }}\n}}\n\n", + "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {name}(home: *const c_void{}) -> {} {{\n\tlet home = unsafe {{ &*home.cast::() }};\n\tunsafe {{ home.serve(move || {call_}) }}\n}}\n\n", decls.concat(), rs(&call.ret), - args.join(", ") ); let native = self.native_fn(&name, params, call.ret.clone()); let api = self.abi.api; @@ -2014,12 +2013,11 @@ impl<'a> Gen<'a> { let abi = self.abi; let _p = abi.prefix.clone(); // A value is immutable in Dart, so its `&mut self` method returns it as the call left - // it, through a function of the glue's that hands back a copy. + // it, calling the C function in place on a copy it hands back. let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); let (handed, export) = match handed { - Some((back, export, shim)) => { - self.glue.push_str(&shim); - self.handed.insert(export.call.name.clone()); + Some((back, export, handed)) => { + self.handed.insert(export.call.name.clone(), handed); (Some(back), export) } None => (None, abi.export(function, owner)), diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 71edea453..11faca6b4 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -2119,16 +2119,13 @@ impl<'a> Gen<'a> { ) -> Option { let abi = self.abi; // A value is immutable in Kotlin, so its `&mut self` method returns it as the call - // left it, through a function of the glue's that hands back a copy. + // left it, calling the C function in place on a copy it hands back. let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); - let (handed, export) = match handed { - Some((back, export, shim)) => { - self.glue.push_str(&shim); - (Some(back), export) - } - None => (None, abi.export(function, owner)), + let (back, export, handed) = match handed { + Some((back, export, handed)) => (Some(back), export, Some(handed)), + None => (None, abi.export(function, owner), None), }; - let function = handed.as_ref().unwrap_or(function); + let function = back.as_ref().unwrap_or(function); self.params = locals(&function.params); let written = function .params @@ -2313,10 +2310,9 @@ impl<'a> Gen<'a> { let value; // The C call, with the out pointers after its arguments. let rust_call = |outs: &[String]| { - let args: Vec<&String> = rust_args.iter().chain(outs).collect(); - let args: Vec<&str> = args.iter().map(|a| a.as_str()).collect(); - match handed { - Some(_) => format!("back_{c_name}::call({})", args.join(", ")), + let args: Vec = rust_args.iter().chain(outs).cloned().collect(); + match &handed { + Some(h) => h.call(&args), None => format!("crate::{c_name}({})", args.join(", ")), } }; diff --git a/ffi/src/python.rs b/ffi/src/python.rs index 84ed8e6d8..5010af5fb 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1601,21 +1601,14 @@ impl<'a> Gen<'a> { ) -> Option { let abi = self.abi; // A value is immutable in Python, so its `&mut self` method returns it as the call - // left it, through a function of the glue's that hands back a copy. + // left it, calling the C function in place on a copy it hands back. let handed = (owner.zip(owner_ty)).and_then(|(owner, (ty, _))| abi.handed_back(function, owner, ty)); - let (handed, export) = match handed { - Some((back, export, shim)) => { - self.glue.push_str(&shim); - (Some(back), export) - } - None => (None, abi.export(function, owner)), + let (back, export, handed) = match handed { + Some((back, export, handed)) => (Some(back), export, Some(handed)), + None => (None, abi.export(function, owner), None), }; - let function = handed.as_ref().unwrap_or(function); + let function = back.as_ref().unwrap_or(function); let c_name = export.call.name.clone(); - let callee = match handed { - Some(_) => format!("back_{c_name}::call"), - None => format!("crate::{c_name}"), - }; let bare = self.bare(&c_name).to_string(); let owner_c = match owner { Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), @@ -1780,9 +1773,12 @@ impl<'a> Gen<'a> { false => self.outs(&outs, &written, &function.ok, err.as_ref(), exception.as_deref(), "ret"), }; let args: Vec = c_args.iter().cloned().chain(ptrs).collect(); + let call = match &handed { + Some(h) => h.call(&args), + None => format!("crate::{c_name}({})", args.join(", ")), + }; stmts.push(format!( - "{decl}\n\t\tlet ret = rt::call(|| {callee}({}));\n\t\ts.done();\n\t\t{value}", - args.join(", ") + "{decl}\n\t\tlet ret = rt::call(|| {call});\n\t\ts.done();\n\t\t{value}" )); } // The Python. From 7e82a7a259973f6638fee4397d7ca68bc47ee5a9 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:19:46 -0800 Subject: [PATCH 7/7] test(ffi): a value's &mut self returning a borrow of itself is refused Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/expected.txt | 5 +++-- ffi/fixtures/reject/src/lib.rs | 8 +++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index b57867143..1472d824d 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -33,8 +33,9 @@ fixtures/reject/src/lib.rs:1182:1: rust2-ffi: cannot export fn `hidden_items`: o fixtures/reject/src/lib.rs:1187:1: rust2-ffi: cannot export fn `hidden_option`: opaque type `impl std::clone::Clone`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1192:1: rust2-ffi: cannot export fn `boxed_bytes`: boxed slice of bytes `std::boxed::Box<[u8]>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:11:1: rust2-ffi: cannot export fn `map`: foreign type `std::collections::HashMap`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1207:2: rust2-ffi: cannot export method `Counter::try_bump`: `&mut self` of a value returning a Result; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1212:2: rust2-ffi: cannot export method `Counter::bump_later`: `&mut self` of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1208:2: rust2-ffi: cannot export method `Counter::try_bump`: `&mut self` of a value returning a Result; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1213:2: rust2-ffi: cannot export method `Counter::bump_later`: `&mut self` of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1218:2: rust2-ffi: cannot export method `Counter::bump_ref`: returned borrow of a value written back `&u8`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:122:1: rust2-ffi: cannot export fn `parse_later`: returned object that borrows `impl std::future::Future>>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:136:1: rust2-ffi: cannot export fn `poll_ready`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:153:2: rust2-ffi: cannot export method `Link::session`: borrowed return that is not Clone `tls::held::Handoff`; 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 cfe29af88..601f69ee4 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1193,7 +1193,8 @@ pub fn boxed_bytes(bytes: Box<[u8]>) -> usize { bytes.len() } -/// A `Copy` count, a value, whose change a raised error or a future would lose. +/// A `Copy` count, a value, whose change a raised error or a future would lose, and which a +/// returned borrow would still hold as it is written back. #[derive(Clone, Copy)] pub struct Counter { count: u8, @@ -1213,4 +1214,9 @@ impl Counter { self.count += 1; std::future::ready(self.count) } + + pub fn bump_ref(&mut self) -> &u8 { + self.count += 1; + &self.count + } }